File size: 9,306 Bytes
7ced643
 
cb55723
ff1359f
9270e54
cb55723
 
 
dd66b19
49f2a82
9c3de60
cb55723
7471241
cb55723
 
9c3de60
f09938e
5635c5e
c309f5d
b54b20c
dd66b19
9270e54
5b9a3a4
b54b20c
9ce5fea
d45d9e1
0b83b3d
9ce5fea
0b83b3d
d45d9e1
0b83b3d
62f4d85
7ced643
5b9a3a4
af551ae
 
 
 
 
 
 
 
0ff6a51
5b9a3a4
af551ae
5b9a3a4
 
af551ae
8150e13
 
af551ae
 
 
8150e13
5b9a3a4
af551ae
5b9a3a4
 
af551ae
5b9a3a4
394f654
d45d9e1
394f654
011deb8
dd66b19
b54b20c
d45d9e1
 
 
011deb8
dd66b19
b54b20c
d45d9e1
 
dd66b19
 
5b9a3a4
394f654
5b9a3a4
 
 
0ff6a51
5b9a3a4
d2c954e
b54b20c
384f5fe
dd66b19
d45d9e1
 
 
37f330d
dd66b19
 
384f5fe
8150e13
 
 
 
 
 
 
 
 
 
 
 
 
dd66b19
384f5fe
 
 
cb55723
7ced643
 
8707304
2a522d7
058fd25
8150e13
7471241
8150e13
 
5b9a3a4
7471241
8150e13
5b9a3a4
7ced643
 
058fd25
7ced643
7471241
 
 
 
 
cc4cae5
d45d9e1
 
d2c954e
2a522d7
b54b20c
db6d664
7ced643
d45d9e1
5f8fe09
cb55723
8150e13
ff1359f
7471241
5b9a3a4
 
d487f80
5b9a3a4
7471241
 
 
 
5b9a3a4
 
 
 
 
 
 
 
d45d9e1
5b9a3a4
 
 
 
 
 
d45d9e1
5b9a3a4
8150e13
7e018c7
d487f80
5b9a3a4
 
ff1359f
8150e13
23f873a
058fd25
5bccda2
8150e13
7471241
8e698cd
d45d9e1
8150e13
 
 
 
d45d9e1
 
 
8150e13
7e018c7
ff1359f
058fd25
5b9a3a4
5bccda2
7e018c7
e1d5ff3
058fd25
5bccda2
 
8150e13
5bccda2
058fd25
8150e13
49f2a82
8150e13
 
e1d5ff3
8150e13
6cf034e
8150e13
 
 
 
 
7ced643
8150e13
 
384f5fe
 
8150e13
 
7471241
8150e13
 
 
7ced643
8150e13
 
7ced643
6cf034e
8150e13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import os
import time
import logging
import re
from datetime import datetime, timedelta
from dotenv import load_dotenv
from cryptography.fernet import Fernet
from simple_salesforce import Salesforce
from transformers import pipeline
from PIL import Image
import pytesseract
import pandas as pd
from docx import Document
import PyPDF2
import gradio as gr
from pdf2image import convert_from_path
import tempfile
from pytz import timezone
import shutil
import unicodedata
import asyncio
import torch
from dateutil import parser as date_parser

# Setup logging
log_file = os.path.join(tempfile.gettempdir(), 'contract_app.log')
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[logging.FileHandler(log_file), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

# Initialize dependencies
def init_globals():
    load_dotenv()
    required_env_vars = [
        'ENCRYPTION_KEY', 'SALESFORCE_USERNAME', 'SALESFORCE_PASSWORD',
        'SALESFORCE_SECURITY_TOKEN', 'SALESFORCE_DOMAIN'
    ]
    env = {var: os.getenv(var) for var in required_env_vars}
    if missing := [k for k in required_env_vars if not env[k]]:
        logger.error(f"Missing env vars: {', '.join(missing)}")
        return None, None
    try:
        fernet = Fernet(env['ENCRYPTION_KEY'].encode())
        summarizer = pipeline(
            "summarization",
            model="facebook/bart-large-cnn",
            tokenizer="facebook/bart-large-cnn",
            framework="pt",
            device=0 if torch.cuda.is_available() else -1
        )
        logger.info("Summarizer initialized with BART-large-cnn")
        return fernet, summarizer
    except Exception as e:
        logger.error(f"Initialization failed: {str(e)}")
        return None, None

# Check dependencies
def check_dependencies():
    missing = []
    try:
        tesseract_path = shutil.which('tesseract')
        if not tesseract_path:
            logger.warning("Tesseract not found. OCR unavailable.")
            missing.append("Tesseract")
        else:
            pytesseract.pytesseract.tesseract_cmd = tesseract_path
        poppler_path = shutil.which('pdfinfo')
        if not poppler_path:
            logger.warning("Poppler not found.")
            missing.append("Poppler")
        return missing
    except Exception as e:
        logger.error(f"Dependency check failed: {str(e)}")
        return ["Tesseract", "Poppler"]

fernet, summarizer = init_globals()
if not fernet or not summarizer:
    raise RuntimeError("Failed to initialize dependencies")

missing_deps = check_dependencies()

# Validate file
def validate_file(file_path):
    ext = os.path.splitext(file_path)[1].lower()
    supported = ['.pdf', '.docx', '.png', '.jpg', '.jpeg', '.csv', '.xls', '.xlsx']
    if ext not in supported:
        return False, f"Unsupported file type: {ext}. Supported types: {', '.join(supported)}"
    if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
        return False, f"File not found or empty: {file_path}"
    return True, None

# Preprocess image
def preprocess_image(image):
    img = image.convert('L')
    img = img.point(lambda x: 0 if x < 140 else 255, '1')
    return img

# Clean text
def clean_text(text):
    text = unicodedata.normalize('NFKC', text)
    text = re.sub(r'\s+', ' ', text.strip())
    return text[:4096]

# Extract text
async def extract_text_async(file_path):
    is_valid, error = validate_file(file_path)
    if not is_valid:
        return None, error
    ext = os.path.splitext(file_path)[1].lower()
    try:
        if ext == '.pdf':
            with open(file_path, 'rb') as f:
                pdf_reader = PyPDF2.PdfReader(f)
                text = "".join([p.extract_text() or "" for p in pdf_reader.pages])
                if text.strip():
                    return clean_text(text), None
                if "Tesseract" not in missing_deps:
                    images = convert_from_path(file_path, dpi=200)
                    text = "\n".join([
                        pytesseract.image_to_string(preprocess_image(img), config='--psm 6 --oem 3 -l eng')
                        for img in images[:2]
                    ])
        elif ext == '.docx':
            doc = Document(file_path)
            text = "\n".join([p.text for p in doc.paragraphs if p.text.strip()])
        elif ext in ['.png', '.jpg', '.jpeg']:
            if "Tesseract" not in missing_deps:
                img = Image.open(file_path)
                text = pytesseract.image_to_string(preprocess_image(img), config='--psm 6 --oem 3 -l eng')
            else:
                return None, "Tesseract not available for image processing"
        elif ext in ['.csv', '.xls', '.xlsx']:
            df = pd.read_csv(file_path, encoding='utf-8', errors='ignore') if ext == '.csv' else pd.read_excel(file_path)
            text = " ".join(df.astype(str).values.flatten())[:2000]
        text = clean_text(text)
        if not text or len(text) < 50:
            return None, f"No valid text extracted from {file_path}"
        return text, None
    except Exception as e:
        logger.error(f"Text extraction failed for {file_path}: {str(e)}")
        return None, f"Text extraction failed: {str(e)}"

# Parse dates
def parse_dates(text):
    ist = timezone('Asia/Kolkata')
    current_date = datetime.now(ist)
    default_date = current_date.strftime('%Y-%m-%d')
    try:
        date_patterns = [
            r'\b(\d{4}-\d{2}-\d{2})\b',
            r'\b(\d{2}/\d{2}/\d{4})\b',
            r'\b(\w+\s+\d{1,2},\s+\d{4})\b',
            r'\b(\d{1,2}\s+\w+\s+\d{4})\b',
        ]
        dates = []
        for pattern in date_patterns:
            dates.extend(re.findall(pattern, text, re.IGNORECASE))
        parsed_dates = []
        for date_str in dates:
            try:
                parsed_date = date_parser.parse(date_str, fuzzy=True, dayfirst=True)
                if parsed_date <= current_date + timedelta(days=365):
                    parsed_dates.append(parsed_date)
            except ValueError:
                continue
        start_date = default_date
        end_date = default_date
        if parsed_dates:
            parsed_dates.sort()
            start_date = parsed_dates[0].strftime('%Y-%m-%d')
            end_date = (parsed_dates[-1] + timedelta(days=730)).strftime('%Y-%m-%d')
        return start_date, end_date
    except Exception as e:
        logger.error(f"Date parsing failed: {str(e)}")
        return default_date, default_date

# Summarize
async def summarize_contract_async(text, summarizer, file_name):
    aspects = ["parties", "payment terms", "obligations", "termination clauses"]
    try:
        summary_result = summarizer(text[:2048], max_length=150, min_length=30, do_sample=False)
        full_summary = summary_result[0]['summary_text'] if summary_result else text[:150]
        aspect_summaries = {}
        patterns = {
            "parties": r"between\s+(.+?)\s+and\s+(.+?)(?:,|\.)",
            "payment terms": r"(?:shall\s+pay|payment\s+of)\s+(.+?)(?:\.|\s|with|,)",
            "obligations": r"(?:obligations|services|shall\s+provide|support|responsibilities)\s+(.+?)(?:\.|\s|by|for|,)",
            "termination clauses": r"(?:terminate|termination\s+clause.*?)\s+(.+?)(?:\.|\s|with|,)"
        }
        for asp, pattern in patterns.items():
            match = re.search(pattern, text, re.IGNORECASE | re.DOTALL)
            aspect_summaries[asp] = clean_text(match.group(1)) if match else "Not extracted"
        start_date, end_date = parse_dates(text)
        return {
            "contract_name": file_name,
            "full_summary": clean_text(full_summary),
            "aspect_summaries": aspect_summaries,
            "start_date": start_date,
            "end_date": end_date,
            "validation_status": "Validated"
        }, None
    except Exception as e:
        logger.error(f"Summarization failed: {str(e)}")
        return {
            "contract_name": file_name,
            "full_summary": "Summarization error",
            "aspect_summaries": {asp: "Not extracted" for asp in aspects},
            "start_date": datetime.now().strftime('%Y-%m-%d'),
            "end_date": datetime.now().strftime('%Y-%m-%d'),
            "validation_status": "Pending"
        }, str(e)

# Gradio UI
with gr.Blocks(theme=gr.themes.Soft()) as iface:
    gr.Markdown("## Contract Summarization Tool")
    file_input = gr.File(label="Upload Contract", file_types=['.pdf', '.docx', '.png', '.jpg', '.jpeg', '.csv', '.xls', '.xlsx'])
    result_output = gr.Textbox(label="Result")

    async def process(file):
        file_path = file.name
        is_valid, error = validate_file(file_path)
        if not is_valid:
            return f"Error: {error}"
        text, text_error = await extract_text_async(file_path)
        if text_error:
            return f"Text extraction failed: {text_error}"
        summary_data, summ_error = await summarize_contract_async(text, summarizer, os.path.basename(file_path))
        return summary_data['full_summary'] if not summ_error else f"Error: {summ_error}"

    submit_btn = gr.Button("Summarize")
    submit_btn.click(process, inputs=[file_input], outputs=[result_output])

if __name__ == "__main__":
    iface.launch()