Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,293 +1,574 @@
|
|
| 1 |
-
gradio
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import re
|
| 5 |
-
import time
|
| 6 |
import tempfile
|
| 7 |
from datetime import datetime
|
|
|
|
|
|
|
| 8 |
from difflib import SequenceMatcher
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
# ============================================================
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def
|
| 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 |
continue
|
| 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 |
continue
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
continue
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
continue
|
| 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 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
with gr.Row():
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
| 280 |
|
| 281 |
with gr.Tabs():
|
| 282 |
with gr.TabItem("π Master Document"):
|
| 283 |
-
|
|
|
|
| 284 |
with gr.TabItem("π¬ Analysis Report"):
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
|
|
|
| 288 |
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
if __name__ == "__main__":
|
| 292 |
-
demo.launch()
|
| 293 |
-
python-docx
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import json
|
|
|
|
|
|
|
| 4 |
import tempfile
|
| 5 |
from datetime import datetime
|
| 6 |
+
from typing import List, Dict
|
| 7 |
+
import PyPDF2
|
| 8 |
from difflib import SequenceMatcher
|
| 9 |
+
import re
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
# ============================================================================
|
| 13 |
+
# OPTIONAL: Hugging Face zero-shot classifier (CPU mode, loads lazily)
|
| 14 |
+
# ============================================================================
|
| 15 |
+
zero_shot_classifier = None
|
| 16 |
+
|
| 17 |
+
def get_classifier():
|
| 18 |
+
global zero_shot_classifier
|
| 19 |
+
if zero_shot_classifier is None:
|
| 20 |
+
try:
|
| 21 |
+
from transformers import pipeline
|
| 22 |
+
zero_shot_classifier = pipeline(
|
| 23 |
+
"zero-shot-classification",
|
| 24 |
+
model="facebook/bart-large-mnli",
|
| 25 |
+
device=-1
|
| 26 |
+
)
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"Warning: Could not load zero-shot classifier: {e}")
|
| 29 |
+
return zero_shot_classifier
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# ============================================================================
|
| 33 |
+
# MODULE 1: Document Parser
|
| 34 |
+
# ============================================================================
|
| 35 |
+
|
| 36 |
+
class DocumentParser:
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def extract_text_from_pdf(file_path: str) -> str:
|
| 40 |
+
try:
|
| 41 |
+
with open(file_path, 'rb') as f:
|
| 42 |
+
reader = PyPDF2.PdfReader(f)
|
| 43 |
+
text = ""
|
| 44 |
+
for page in reader.pages:
|
| 45 |
+
extracted = page.extract_text()
|
| 46 |
+
if extracted:
|
| 47 |
+
text += extracted + "\n"
|
| 48 |
+
return text
|
| 49 |
+
except Exception as e:
|
| 50 |
+
return f"Error reading PDF: {str(e)}"
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def extract_text_from_file(file_path: str) -> str:
|
| 54 |
+
if not file_path:
|
| 55 |
+
return "Error: No file path provided"
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
lower_path = file_path.lower()
|
| 59 |
+
|
| 60 |
+
if lower_path.endswith('.pdf'):
|
| 61 |
+
return DocumentParser.extract_text_from_pdf(file_path)
|
| 62 |
+
|
| 63 |
+
if lower_path.endswith('.docx'):
|
| 64 |
+
from docx import Document as DocxDocument
|
| 65 |
+
doc = DocxDocument(file_path)
|
| 66 |
+
paragraphs = [p.text.strip() for p in doc.paragraphs if p.text and p.text.strip()]
|
| 67 |
+
return "\n\n".join(paragraphs)
|
| 68 |
+
|
| 69 |
+
if lower_path.endswith('.txt'):
|
| 70 |
+
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
|
| 71 |
+
return f.read()
|
| 72 |
+
|
| 73 |
+
return "Error reading file: Unsupported file type"
|
| 74 |
+
|
| 75 |
+
except Exception as e:
|
| 76 |
+
return f"Error reading file: {str(e)}"
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def parse_document(text: str) -> Dict:
|
| 80 |
+
text = text.replace('\r\n', '\n').replace('\r', '\n')
|
| 81 |
+
text = re.sub(r'\n[ \t]*\n+', '\n\n', text).strip()
|
| 82 |
+
|
| 83 |
+
paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()]
|
| 84 |
+
|
| 85 |
+
sentences = []
|
| 86 |
+
for para in paragraphs:
|
| 87 |
+
parts = re.split(r'(?<=[.!?])\s+', para)
|
| 88 |
+
sentences.extend([s.strip() for s in parts if s.strip()])
|
| 89 |
+
|
| 90 |
+
return {
|
| 91 |
+
'full_text': text,
|
| 92 |
+
'paragraphs': paragraphs,
|
| 93 |
+
'sentences': sentences,
|
| 94 |
+
'word_count': len(text.split()),
|
| 95 |
+
'char_count': len(text)
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# ============================================================================
|
| 100 |
+
# MODULE 2: Forensic Analyzer
|
| 101 |
+
# ============================================================================
|
| 102 |
+
|
| 103 |
+
class ForensicAnalyzer:
|
| 104 |
+
|
| 105 |
+
RISK_PATTERNS = {
|
| 106 |
+
'denial_trap': r"\b(deny|denies|denied|denial|no such|never|not applicable)\b",
|
| 107 |
+
'admission_by_silence': r"\b(fail|failed|failure|omit|omitted|omission|no response|no reply)\b",
|
| 108 |
+
'procedural_hedging': r"\b(without prejudice|subject to|conditional|provided that|notwithstanding)\b",
|
| 109 |
+
'burden_flip': r"\b(claimant must|burden|onus|responsibility|incumbent upon|required to prove)\b"
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
@staticmethod
|
| 113 |
+
def find_duplicates(docs: List[Dict]) -> List[Dict]:
|
| 114 |
+
duplicates = []
|
| 115 |
+
for i, doc1 in enumerate(docs):
|
| 116 |
+
for j, doc2 in enumerate(docs[i + 1:], start=i + 1):
|
| 117 |
+
for para1 in doc1['paragraphs']:
|
| 118 |
+
for para2 in doc2['paragraphs']:
|
| 119 |
+
if len(para1) < 20 or len(para2) < 20:
|
| 120 |
+
continue
|
| 121 |
+
ratio = SequenceMatcher(None, para1, para2).ratio()
|
| 122 |
+
if ratio > 0.85:
|
| 123 |
+
duplicates.append({
|
| 124 |
+
'doc1': i, 'doc2': j,
|
| 125 |
+
'similarity': ratio,
|
| 126 |
+
'text': para1[:50000] + "...",
|
| 127 |
+
'type': 'duplicate' if ratio > 0.95 else 'near_duplicate'
|
| 128 |
+
})
|
| 129 |
+
return duplicates
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def find_unique_content(docs: List[Dict]) -> List[Dict]:
|
| 133 |
+
unique_items = []
|
| 134 |
+
for i, doc in enumerate(docs):
|
| 135 |
+
for para in doc['paragraphs']:
|
| 136 |
+
if len(para) < 20:
|
| 137 |
+
continue
|
| 138 |
+
is_unique = True
|
| 139 |
+
for j, other_doc in enumerate(docs):
|
| 140 |
+
if i == j:
|
| 141 |
continue
|
| 142 |
+
for other_para in other_doc['paragraphs']:
|
| 143 |
+
if SequenceMatcher(None, para, other_para).ratio() > 0.8:
|
| 144 |
+
is_unique = False
|
| 145 |
+
break
|
| 146 |
+
if not is_unique:
|
| 147 |
+
break
|
| 148 |
+
if is_unique:
|
| 149 |
+
unique_items.append({
|
| 150 |
+
'doc_index': i,
|
| 151 |
+
'content': para,
|
| 152 |
+
'length': len(para),
|
| 153 |
+
'type': 'unique_paragraph'
|
| 154 |
+
})
|
| 155 |
+
return unique_items
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def detect_risk_language(text: str) -> List[Dict]:
|
| 159 |
+
findings = []
|
| 160 |
+
for risk_type, pattern in ForensicAnalyzer.RISK_PATTERNS.items():
|
| 161 |
+
for match in re.finditer(pattern, text, re.IGNORECASE):
|
| 162 |
+
start = max(0, match.start() - 50)
|
| 163 |
+
end = min(len(text), match.end() + 50)
|
| 164 |
+
findings.append({
|
| 165 |
+
'type': risk_type,
|
| 166 |
+
'matched_text': match.group(),
|
| 167 |
+
'context': text[start:end],
|
| 168 |
+
'position': match.start()
|
| 169 |
+
})
|
| 170 |
+
return findings
|
| 171 |
+
|
| 172 |
+
@staticmethod
|
| 173 |
+
def analyze_documents(docs: List[Dict]) -> Dict:
|
| 174 |
+
return {
|
| 175 |
+
'duplicates': ForensicAnalyzer.find_duplicates(docs),
|
| 176 |
+
'unique_content': ForensicAnalyzer.find_unique_content(docs),
|
| 177 |
+
'risk_language': [
|
| 178 |
+
item for doc in docs
|
| 179 |
+
for item in ForensicAnalyzer.detect_risk_language(doc['full_text'])
|
| 180 |
+
]
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# ============================================================================
|
| 185 |
+
# MODULE 3 & 4: Document Merger
|
| 186 |
+
# ============================================================================
|
| 187 |
+
|
| 188 |
+
class DocumentMerger:
|
| 189 |
+
|
| 190 |
+
@staticmethod
|
| 191 |
+
def select_best_content(duplicates, docs):
|
| 192 |
+
best_versions = []
|
| 193 |
+
processed = set()
|
| 194 |
+
for dup in duplicates:
|
| 195 |
+
key = tuple(sorted([dup['doc1'], dup['doc2']]))
|
| 196 |
+
if key in processed:
|
| 197 |
continue
|
| 198 |
+
processed.add(key)
|
| 199 |
+
doc1_text = docs[dup['doc1']]['full_text']
|
| 200 |
+
doc2_text = docs[dup['doc2']]['full_text']
|
| 201 |
+
best_versions.append(doc1_text if len(doc1_text) > len(doc2_text) else doc2_text)
|
| 202 |
+
return best_versions
|
| 203 |
+
|
| 204 |
+
@staticmethod
|
| 205 |
+
def merge_documents(docs, analysis):
|
| 206 |
+
output = []
|
| 207 |
+
output.append("MASTER EVIDENCE DOCUMENT")
|
| 208 |
+
output.append("=" * 80)
|
| 209 |
+
output.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 210 |
+
output.append(f"Source Documents: {len(docs)}")
|
| 211 |
+
output.append("=" * 80 + "\n")
|
| 212 |
+
|
| 213 |
+
output.append("EXECUTIVE SUMMARY")
|
| 214 |
+
output.append("-" * 80)
|
| 215 |
+
output.append(f"Total Duplicates Found: {len(analysis['duplicates'])}")
|
| 216 |
+
output.append(f"Unique Content Items: {len(analysis['unique_content'])}")
|
| 217 |
+
output.append(f"Risk Language Instances: {len(analysis['risk_language'])}\n")
|
| 218 |
+
|
| 219 |
+
output.append("CONSOLIDATED CONTENT")
|
| 220 |
+
output.append("-" * 80)
|
| 221 |
+
best_versions = DocumentMerger.select_best_content(analysis['duplicates'], docs)
|
| 222 |
+
if best_versions:
|
| 223 |
+
for i, content in enumerate(best_versions, 1):
|
| 224 |
+
output.append(f"\n[Section {i}]")
|
| 225 |
+
output.append(content[:50000] + "..." if len(content) > 500 else content)
|
| 226 |
+
else:
|
| 227 |
+
output.append("No duplicate content found across documents.")
|
| 228 |
+
|
| 229 |
+
output.append("\n\nUNIQUE FINDINGS")
|
| 230 |
+
output.append("-" * 80)
|
| 231 |
+
for item in analysis['unique_content'][:100]:
|
| 232 |
+
output.append(f"\n[From Document {item['doc_index'] + 1}]")
|
| 233 |
+
c = item['content']
|
| 234 |
+
output.append(c[:50000] + "..." if len(c) > 300 else c)
|
| 235 |
+
|
| 236 |
+
output.append("\n\nRISK LANGUAGE ANALYSIS")
|
| 237 |
+
output.append("-" * 80)
|
| 238 |
+
risk_summary = {}
|
| 239 |
+
for risk in analysis['risk_language']:
|
| 240 |
+
risk_summary[risk['type']] = risk_summary.get(risk['type'], 0) + 1
|
| 241 |
+
if risk_summary:
|
| 242 |
+
for risk_type, count in risk_summary.items():
|
| 243 |
+
output.append(f"{risk_type.replace('_', ' ').title()}: {count} instances")
|
| 244 |
+
else:
|
| 245 |
+
output.append("No risk language patterns detected.")
|
| 246 |
+
|
| 247 |
+
output.append("\n" + "=" * 80)
|
| 248 |
+
output.append("END OF MASTER EVIDENCE DOCUMENT")
|
| 249 |
+
return "\n".join(output)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# ============================================================================
|
| 253 |
+
# AI SUMMARISATION
|
| 254 |
+
# ============================================================================
|
| 255 |
+
|
| 256 |
+
def ai_summarise(merged_doc: str, analysis: Dict) -> str:
|
| 257 |
+
try:
|
| 258 |
+
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
|
| 259 |
+
|
| 260 |
+
risk_summary = {}
|
| 261 |
+
for risk in analysis.get('risk_language', []):
|
| 262 |
+
risk_summary[risk['type']] = risk_summary.get(risk['type'], 0) + 1
|
| 263 |
+
|
| 264 |
+
# Condensed input for BART summarisation model
|
| 265 |
+
input_text = f"""
|
| 266 |
+
Forensic document analysis results:
|
| 267 |
+
- Duplicates found: {len(analysis.get('duplicates', []))}
|
| 268 |
+
- Unique content items: {len(analysis.get('unique_content', []))}
|
| 269 |
+
- Risk language: {json.dumps(risk_summary)}
|
| 270 |
+
|
| 271 |
+
Document excerpt:
|
| 272 |
+
{merged_doc[:50000]}
|
| 273 |
+
""".strip()
|
| 274 |
+
|
| 275 |
+
headers = {"Content-Type": "application/json"}
|
| 276 |
+
if hf_token:
|
| 277 |
+
headers["Authorization"] = f"Bearer {hf_token}"
|
| 278 |
+
|
| 279 |
+
response = requests.post(
|
| 280 |
+
"https://router.huggingface.co/hf-inference/models/facebook/bart-large-cnn",
|
| 281 |
+
headers=headers,
|
| 282 |
+
json={
|
| 283 |
+
"inputs": input_text,
|
| 284 |
+
"parameters": {
|
| 285 |
+
"max_length": 400,
|
| 286 |
+
"min_length": 100,
|
| 287 |
+
"do_sample": False
|
| 288 |
+
}
|
| 289 |
+
}
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
if response.status_code == 200:
|
| 293 |
+
data = response.json()
|
| 294 |
+
if isinstance(data, list) and data:
|
| 295 |
+
summary = data[0].get('summary_text', '')
|
| 296 |
+
risk_lines = "\n".join([
|
| 297 |
+
f"- {k.replace('_', ' ').title()}: {v} instances"
|
| 298 |
+
for k, v in risk_summary.items()
|
| 299 |
+
])
|
| 300 |
+
return f"AI SUMMARY\n{'=' * 60}\n\n{summary}\n\nRisk Language Breakdown:\n{risk_lines}"
|
| 301 |
+
return "Summary could not be extracted from model response."
|
| 302 |
+
elif response.status_code == 503:
|
| 303 |
+
return "Model is loading β please wait 20 seconds and try again."
|
| 304 |
+
else:
|
| 305 |
+
return f"Summarisation unavailable (status {response.status_code}): {response.text}"
|
| 306 |
+
|
| 307 |
+
except Exception as e:
|
| 308 |
+
return f"Summarisation error: {str(e)}"
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# ============================================================================
|
| 312 |
+
# EXPORT FUNCTIONS
|
| 313 |
+
# ============================================================================
|
| 314 |
+
|
| 315 |
+
def export_txt(merged_doc: str, analysis_report: str) -> str:
|
| 316 |
+
try:
|
| 317 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.txt', mode='w', encoding='utf-8')
|
| 318 |
+
tmp.write("SEAMSTRESSES FRAMEWORK β EXPORT\n")
|
| 319 |
+
tmp.write(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
|
| 320 |
+
tmp.write("=" * 80 + "\n\n")
|
| 321 |
+
tmp.write(merged_doc)
|
| 322 |
+
tmp.write("\n\n" + "=" * 80 + "\n\n")
|
| 323 |
+
tmp.write(analysis_report)
|
| 324 |
+
tmp.close()
|
| 325 |
+
return tmp.name
|
| 326 |
+
except Exception as e:
|
| 327 |
+
print(f"TXT export error: {e}")
|
| 328 |
+
return None
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def export_pdf(merged_doc: str, analysis_report: str) -> str:
|
| 332 |
+
try:
|
| 333 |
+
from reportlab.lib.pagesizes import A4
|
| 334 |
+
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 335 |
+
from reportlab.lib.units import mm
|
| 336 |
+
from reportlab.lib import colors
|
| 337 |
+
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, HRFlowable
|
| 338 |
+
from reportlab.lib.enums import TA_CENTER
|
| 339 |
+
|
| 340 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
|
| 341 |
+
tmp.close()
|
| 342 |
+
|
| 343 |
+
doc = SimpleDocTemplate(
|
| 344 |
+
tmp.name, pagesize=A4,
|
| 345 |
+
rightMargin=20*mm, leftMargin=20*mm,
|
| 346 |
+
topMargin=20*mm, bottomMargin=20*mm
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
styles = getSampleStyleSheet()
|
| 350 |
+
title_style = ParagraphStyle('Title', parent=styles['Heading1'], fontSize=16, alignment=TA_CENTER, spaceAfter=6)
|
| 351 |
+
heading_style = ParagraphStyle('Heading', parent=styles['Heading2'], fontSize=11, textColor=colors.HexColor('#1a1a2e'), spaceAfter=4)
|
| 352 |
+
body_style = ParagraphStyle('Body', parent=styles['Normal'], fontSize=9, leading=14, spaceAfter=3)
|
| 353 |
+
|
| 354 |
+
story = []
|
| 355 |
+
story.append(Paragraph("Seamstresses Framework", title_style))
|
| 356 |
+
story.append(Paragraph("Forensic Document Analysis Report", heading_style))
|
| 357 |
+
story.append(Paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", body_style))
|
| 358 |
+
story.append(HRFlowable(width="100%", thickness=1, color=colors.grey))
|
| 359 |
+
story.append(Spacer(1, 10))
|
| 360 |
+
|
| 361 |
+
story.append(Paragraph("Master Document", heading_style))
|
| 362 |
+
for block in re.split(r'\n\s*\n', merged_doc):
|
| 363 |
+
block = block.strip()
|
| 364 |
+
if not block:
|
| 365 |
continue
|
| 366 |
+
safe = block.replace('&', '&').replace('<', '<').replace('>', '>').replace('\n', '<br/>')
|
| 367 |
+
if set(block) <= {'=', '-'}:
|
| 368 |
+
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.lightgrey))
|
| 369 |
+
elif block.isupper() and len(block) > 3 and '\n' not in block and not block.startswith('['):
|
| 370 |
+
story.append(Paragraph(safe, heading_style))
|
| 371 |
+
else:
|
| 372 |
+
story.append(Paragraph(safe, body_style))
|
| 373 |
+
|
| 374 |
+
story.append(Spacer(1, 12))
|
| 375 |
+
story.append(Paragraph("Analysis Report", heading_style))
|
| 376 |
+
story.append(HRFlowable(width="100%", thickness=0.5, color=colors.lightgrey))
|
| 377 |
+
for block in re.split(r'\n\s*\n', analysis_report):
|
| 378 |
+
block = block.strip()
|
| 379 |
+
if not block:
|
| 380 |
continue
|
| 381 |
+
safe = block.replace('&', '&').replace('<', '<').replace('>', '>').replace('\n', '<br/>')
|
| 382 |
+
if block.isupper() and len(block) > 3 and '\n' not in block:
|
| 383 |
+
story.append(Paragraph(safe, heading_style))
|
| 384 |
+
else:
|
| 385 |
+
story.append(Paragraph(safe, body_style))
|
| 386 |
+
|
| 387 |
+
doc.build(story)
|
| 388 |
+
return tmp.name
|
| 389 |
+
|
| 390 |
+
except Exception as e:
|
| 391 |
+
print(f"PDF export error: {e}")
|
| 392 |
+
return None
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def export_docx(merged_doc: str, analysis_report: str, summary: str) -> str:
|
| 396 |
+
try:
|
| 397 |
+
from docx import Document as DocxDocument
|
| 398 |
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
| 399 |
+
|
| 400 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.docx')
|
| 401 |
+
tmp.close()
|
| 402 |
+
|
| 403 |
+
doc = DocxDocument()
|
| 404 |
+
|
| 405 |
+
title = doc.add_heading('Seamstresses Framework', 0)
|
| 406 |
+
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 407 |
+
sub = doc.add_heading('Forensic Document Analysis Report', level=2)
|
| 408 |
+
sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 409 |
+
doc.add_paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 410 |
+
doc.add_paragraph()
|
| 411 |
+
|
| 412 |
+
# AI Summary
|
| 413 |
+
if summary and not summary.startswith("AI summarisation"):
|
| 414 |
+
doc.add_heading('AI Summary', level=1)
|
| 415 |
+
doc.add_paragraph(summary)
|
| 416 |
+
doc.add_paragraph()
|
| 417 |
+
|
| 418 |
+
# Master document
|
| 419 |
+
doc.add_heading('Master Document', level=1)
|
| 420 |
+
for line in merged_doc.split('\n'):
|
| 421 |
+
if line.strip():
|
| 422 |
+
if line.startswith('===') or line.startswith('---'):
|
| 423 |
+
doc.add_paragraph('β' * 60)
|
| 424 |
+
elif line.isupper() and len(line) > 3 and not line.startswith('['):
|
| 425 |
+
doc.add_heading(line, level=2)
|
| 426 |
+
else:
|
| 427 |
+
doc.add_paragraph(line)
|
| 428 |
+
|
| 429 |
+
doc.add_page_break()
|
| 430 |
+
|
| 431 |
+
# Analysis report
|
| 432 |
+
doc.add_heading('Analysis Report', level=1)
|
| 433 |
+
for line in analysis_report.split('\n'):
|
| 434 |
+
if line.strip():
|
| 435 |
+
if line.isupper() and len(line) > 3:
|
| 436 |
+
doc.add_heading(line, level=2)
|
| 437 |
+
else:
|
| 438 |
+
doc.add_paragraph(line)
|
| 439 |
+
|
| 440 |
+
doc.save(tmp.name)
|
| 441 |
+
return tmp.name
|
| 442 |
+
|
| 443 |
+
except Exception as e:
|
| 444 |
+
print(f"DOCX export error: {e}")
|
| 445 |
+
return None
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# ============================================================================
|
| 449 |
+
# MAIN PROCESSING FUNCTION
|
| 450 |
+
# ============================================================================
|
| 451 |
+
|
| 452 |
+
def process_documents(file1, file2, file3):
|
| 453 |
+
try:
|
| 454 |
+
raw_inputs = [file1, file2, file3]
|
| 455 |
+
files = []
|
| 456 |
+
for f in raw_inputs:
|
| 457 |
+
if f is None:
|
| 458 |
+
continue
|
| 459 |
+
if isinstance(f, dict):
|
| 460 |
+
path = f.get('path') or f.get('name')
|
| 461 |
+
elif hasattr(f, 'name'):
|
| 462 |
+
path = f.name
|
| 463 |
+
elif isinstance(f, str):
|
| 464 |
+
path = f
|
| 465 |
+
else:
|
| 466 |
+
path = str(f)
|
| 467 |
+
if path:
|
| 468 |
+
files.append(path)
|
| 469 |
+
|
| 470 |
+
if not files:
|
| 471 |
+
return "Please upload at least one document.", "", "", None, None, None
|
| 472 |
+
|
| 473 |
+
docs = []
|
| 474 |
+
file_names = []
|
| 475 |
+
for file_path in files:
|
| 476 |
+
text = DocumentParser.extract_text_from_file(file_path)
|
| 477 |
+
if not text or text.startswith("Error"):
|
| 478 |
+
return f"Error: {text}", "", "", None, None, None
|
| 479 |
+
docs.append(DocumentParser.parse_document(text))
|
| 480 |
+
file_names.append(os.path.basename(file_path))
|
| 481 |
+
|
| 482 |
+
analysis = ForensicAnalyzer.analyze_documents(docs)
|
| 483 |
+
merged_doc = DocumentMerger.merge_documents(docs, analysis)
|
| 484 |
+
|
| 485 |
+
# Analysis report
|
| 486 |
+
analysis_report = f"FORENSIC ANALYSIS REPORT\n{'=' * 80}\n\n"
|
| 487 |
+
analysis_report += f"FILES ANALYZED: {', '.join(file_names)}\n\n"
|
| 488 |
+
analysis_report += f"DUPLICATE ANALYSIS\n{'-' * 80}\n"
|
| 489 |
+
analysis_report += f"Total Duplicates Found: {len(analysis['duplicates'])}\n\n"
|
| 490 |
+
for dup in analysis['duplicates'][:50]:
|
| 491 |
+
analysis_report += f"- Documents {dup['doc1']+1} & {dup['doc2']+1}: {dup['similarity']:.1%} similarity\n"
|
| 492 |
+
analysis_report += f"\nUNIQUE CONTENT\n{'-' * 80}\n"
|
| 493 |
+
analysis_report += f"Total Unique Items: {len(analysis['unique_content'])}\n\n"
|
| 494 |
+
for item in analysis['unique_content'][:50]:
|
| 495 |
+
analysis_report += f"- From Document {item['doc_index']+1}: {item['content'][:50000]}...\n"
|
| 496 |
+
analysis_report += f"\nRISK LANGUAGE DETECTED\n{'-' * 80}\n"
|
| 497 |
+
risk_types = {}
|
| 498 |
+
for risk in analysis['risk_language']:
|
| 499 |
+
risk_types[risk['type']] = risk_types.get(risk['type'], 0) + 1
|
| 500 |
+
for risk_type, count in risk_types.items():
|
| 501 |
+
analysis_report += f"- {risk_type.replace('_', ' ').title()}: {count} instances\n"
|
| 502 |
+
|
| 503 |
+
# AI Summary
|
| 504 |
+
summary = ai_summarise(merged_doc, analysis)
|
| 505 |
+
|
| 506 |
+
# Exports
|
| 507 |
+
txt_path = export_txt(merged_doc, analysis_report)
|
| 508 |
+
pdf_path = export_pdf(merged_doc, analysis_report)
|
| 509 |
+
docx_path = export_docx(merged_doc, analysis_report, summary)
|
| 510 |
+
|
| 511 |
+
return merged_doc, analysis_report, summary, txt_path, pdf_path, docx_path
|
| 512 |
+
|
| 513 |
+
except Exception as e:
|
| 514 |
+
import traceback
|
| 515 |
+
return f"Error: {str(e)}\n\n{traceback.format_exc()}", "", "", None, None, None
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
# ============================================================================
|
| 519 |
+
# GRADIO INTERFACE
|
| 520 |
+
# ============================================================================
|
| 521 |
+
|
| 522 |
+
with gr.Blocks(title="Seamstresses Framework", theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) as demo:
|
| 523 |
+
gr.Markdown("""
|
| 524 |
+
# π§΅ Seamstresses Framework
|
| 525 |
+
## Forensic Document Analysis, Intelligent Merging & AI Summarisation
|
| 526 |
+
Upload up to 3 legal documents to deduplicate, analyse risk language, and generate an AI-powered summary.
|
| 527 |
+
""")
|
| 528 |
|
| 529 |
with gr.Row():
|
| 530 |
+
with gr.Column():
|
| 531 |
+
gr.Markdown("### Upload Documents")
|
| 532 |
+
file1 = gr.File(label="Document 1", file_types=[".pdf", ".txt", ".docx"], type="filepath")
|
| 533 |
+
file2 = gr.File(label="Document 2", file_types=[".pdf", ".txt", ".docx"], type="filepath")
|
| 534 |
+
file3 = gr.File(label="Document 3 (Optional)", file_types=[".pdf", ".txt", ".docx"], type="filepath")
|
| 535 |
+
analyze_btn = gr.Button("π Analyze, Merge & Summarise", variant="primary", size="lg")
|
| 536 |
|
| 537 |
with gr.Tabs():
|
| 538 |
with gr.TabItem("π Master Document"):
|
| 539 |
+
merged_output = gr.Textbox(label="Merged Document", lines=30, max_lines=200)
|
| 540 |
+
|
| 541 |
with gr.TabItem("π¬ Analysis Report"):
|
| 542 |
+
analysis_output = gr.Textbox(label="Forensic Analysis", lines=30, max_lines=200)
|
| 543 |
+
|
| 544 |
+
with gr.TabItem("π€ AI Summary"):
|
| 545 |
+
summary_output = gr.Textbox(label="AI-Powered Summary", lines=30, max_lines=200)
|
| 546 |
|
| 547 |
+
with gr.TabItem("π₯ Export"):
|
| 548 |
+
gr.Markdown("### Download Your Reports")
|
| 549 |
+
with gr.Row():
|
| 550 |
+
txt_file = gr.File(label="π Plain Text (.txt)", interactive=False)
|
| 551 |
+
pdf_file = gr.File(label="π PDF (.pdf)", interactive=False)
|
| 552 |
+
docx_file = gr.File(label="π Word Document (.docx)", interactive=False)
|
| 553 |
+
gr.Markdown("""
|
| 554 |
+
> **Word document** includes AI summary, merged document, and full analysis.
|
| 555 |
+
> **PDF & TXT** contain the merged document and analysis report.
|
| 556 |
+
""")
|
| 557 |
+
|
| 558 |
+
analyze_btn.click(
|
| 559 |
+
fn=process_documents,
|
| 560 |
+
inputs=[file1, file2, file3],
|
| 561 |
+
outputs=[merged_output, analysis_output, summary_output, txt_file, pdf_file, docx_file]
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
gr.Markdown("""
|
| 565 |
+
---
|
| 566 |
+
### Risk Language Detected
|
| 567 |
+
- **Denial Trap** β deny, denied, never, not applicable
|
| 568 |
+
- **Admission by Silence** β failure, omission, no response
|
| 569 |
+
- **Procedural Hedging** β without prejudice, notwithstanding, subject to
|
| 570 |
+
- **Burden Flip** β burden, onus, required to prove, claimant must
|
| 571 |
+
""")
|
| 572 |
|
| 573 |
if __name__ == "__main__":
|
| 574 |
+
demo.launch()
|
|
|