Basementup commited on
Commit
d291dce
Β·
verified Β·
1 Parent(s): 4541628

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +558 -277
app.py CHANGED
@@ -1,293 +1,574 @@
1
- gradio
2
- spaces
3
- pypdfimport os
4
- import re
5
- import time
6
  import tempfile
7
  from datetime import datetime
 
 
8
  from difflib import SequenceMatcher
9
- from typing import List, Dict, Optional
10
-
11
- import gradio as gr
12
- import spaces
13
-
14
- # ============================================================
15
- # 1. SAFE TEXT EXTRACTION
16
- # ============================================================
17
- def _pdf_text(path: str) -> str:
18
- from pypdf import PdfReader
19
- return "\n".join(p.extract_text() or "" for p in PdfReader(path).pages)
20
-
21
- def _docx_text(path: str) -> str:
22
- from docx import Document
23
- return "\n".join(p.text for p in Document(path).paragraphs)
24
-
25
- def _txt_text(path: str) -> str:
26
- with open(path, encoding="utf-8", errors="ignore") as f:
27
- return f.read()
28
-
29
- def extract(file) -> str:
30
- if not file:
31
- return ""
32
- if isinstance(file, str) and os.path.exists(file):
33
- path = file
34
- else:
35
- tmp = tempfile.mkdtemp()
36
- path = os.path.join(tmp, file.name)
37
- with open(path, "wb") as f:
38
- f.write(file.read())
39
- ext = os.path.splitext(path)[1].lower()
40
- if ext == ".pdf":
41
- return _pdf_text(path)
42
- elif ext == ".docx":
43
- return _docx_text(path)
44
- elif ext in [".txt", ".md"]:
45
- return _txt_text(path)
46
- return "[Unsupported file type]"
47
-
48
- # ============================================================
49
- # 2. SAFE PARAGRAPH & SENTENCE PROCESSING
50
- # ============================================================
51
- def _clean(txt: str) -> str:
52
- return re.sub(r"\s+", " ", txt).strip()
53
-
54
- def _split_paragraphs(text: str, max_paras: int = 200) -> List[str]:
55
- # raw split then trim to avoid overload
56
- parts = text.split('\n\n')
57
- cleaned = [_clean(p) for p in parts if _clean(p)]
58
- # Keep only first max_paras to avoid hanging
59
- return cleaned[:max_paras]
60
-
61
- def _split_sentences(para: str, max_sents: int = 10) -> List[str]:
62
- sents = re.split(r'(?<=[.!?])\s+', para)
63
- return [s.strip() for s in sents if len(s.strip()) > 10][:max_sents]
64
-
65
- # ============================================================
66
- # 3. QUICK KEYWORD PRE‑FILTER (avoids heavy comparisons)
67
- # ============================================================
68
- def _share_keywords(p1: str, p2: str, min_shared: int = 4) -> bool:
69
- words1 = set(re.findall(r'\b\w{5,}\b', p1.lower()))
70
- words2 = set(re.findall(r'\b\w{5,}\b', p2.lower()))
71
- return len(words1 & words2) >= min_shared
72
-
73
- # ============================================================
74
- # 4. DUPLICATE DETECTION WITH STRICT LIMITS
75
- # ============================================================
76
- _HEDGING = re.compile(
77
- r"\b(may|might|could|possibly|alleged|allegedly|appears|seems|perhaps)\b",
78
- re.IGNORECASE
79
- )
80
-
81
- def _authority_score(para: str) -> float:
82
- length = min(len(para)/500.0, 1.0)
83
- hedges = len(_HEDGING.findall(para))
84
- return length*0.4 + max(0, 1.0 - hedges*0.15)*0.6
85
-
86
- def _best(p1: str, p2: str) -> str:
87
- return p1 if _authority_score(p1) >= _authority_score(p2) else p2
88
-
89
- def safe_duplicate_analysis(docs_paras: List[List[str]]) -> Dict:
90
- duplicates = []
91
- best_lookup = {}
92
- for i, paras in enumerate(docs_paras):
93
- for j, para in enumerate(paras):
94
- best_lookup[(i, j)] = para
95
-
96
- MAX_PAIRS = 4000
97
- count = 0
98
- start_time = time.time()
99
-
100
- for i in range(len(docs_paras)):
101
- for j in range(i+1, len(docs_paras)):
102
- for pi, p1 in enumerate(docs_paras[i]):
103
- for pj, p2 in enumerate(docs_paras[j]):
104
- if count >= MAX_PAIRS or time.time() - start_time > 4:
105
- return {"duplicates": duplicates, "best_lookup": best_lookup}
106
- if len(p1) < 30 or len(p2) < 30:
107
- continue
108
- if not _share_keywords(p1, p2):
109
- continue
110
- count += 1
111
- try:
112
- ratio = SequenceMatcher(None, p1, p2).ratio()
113
- except Exception:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  continue
115
- if ratio >= 0.85:
116
- best_para = _best(p1, p2)
117
- duplicates.append({
118
- "doc1": i+1, "doc2": j+1,
119
- "similarity": round(ratio, 3),
120
- "best": best_para[:300] + "..."
121
- })
122
- best_lookup[(i, pi)] = best_para
123
- best_lookup[(j, pj)] = best_para
124
- return {"duplicates": duplicates, "best_lookup": best_lookup}
125
-
126
- # ============================================================
127
- # 5. CONTRADICTION DETECTION (lightweight, strictly limited)
128
- # ============================================================
129
- _NEG_WORDS = re.compile(r'\b(no|not|never|neither|nor|nothing)\b', re.IGNORECASE)
130
- _AFF_WORDS = re.compile(r'\b(yes|certainly|always|indeed|absolutely)\b', re.IGNORECASE)
131
-
132
- def safe_contradictions(docs_paras: List[List[str]]) -> List[Dict]:
133
- # Collect a limited number of sentences from each doc
134
- all_sents = []
135
- for i, paras in enumerate(docs_paras):
136
- for j, para in enumerate(paras[:50]): # only first 50 paras per doc
137
- for sent in _split_sentences(para, max_sents=5):
138
- all_sents.append((i, sent))
139
-
140
- contradictions = []
141
- MAX_SENT_PAIRS = 1500
142
- count = 0
143
- start_time = time.time()
144
-
145
- for a in range(len(all_sents)):
146
- for b in range(a+1, len(all_sents)):
147
- if count >= MAX_SENT_PAIRS or time.time() - start_time > 3:
148
- return contradictions
149
- if all_sents[a][0] == all_sents[b][0]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  continue
151
- s1, s2 = all_sents[a][1], all_sents[b][1]
152
- if len(s1) < 20 or len(s2) < 20:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  continue
154
- count += 1
155
- try:
156
- ratio = SequenceMatcher(None, s1, s2).ratio()
157
- except Exception:
 
 
 
 
 
 
 
 
 
 
158
  continue
159
- if ratio > 0.75:
160
- # Quick negative/affirmative check
161
- neg1 = bool(_NEG_WORDS.search(s1))
162
- aff1 = bool(_AFF_WORDS.search(s1))
163
- neg2 = bool(_NEG_WORDS.search(s2))
164
- aff2 = bool(_AFF_WORDS.search(s2))
165
- if (neg1 and aff2) or (aff1 and neg2) or (neg1 and not neg2 and ratio > 0.85):
166
- contradictions.append({
167
- "doc1": all_sents[a][0]+1,
168
- "doc2": all_sents[b][0]+1,
169
- "sentence1": s1[:180],
170
- "sentence2": s2[:180],
171
- "similarity": round(ratio, 3)
172
- })
173
- if len(contradictions) >= 20:
174
- return contradictions
175
- return contradictions
176
-
177
- # ============================================================
178
- # 6. MASTER DOCUMENT COMPILATION (PhD‑level English)
179
- # ============================================================
180
- def build_master(docs_text: List[str], best_lookup: Dict, contradictions: List[Dict]) -> str:
181
- now = datetime.now().strftime("%d %B %Y, %H:%M")
182
- lines = [
183
- "=" * 72,
184
- "MASTER EVIDENCE DOCUMENT".center(72),
185
- "Compiled by the Seamstresses Framework".center(72),
186
- f"Date of Compilation: {now}".center(72),
187
- "=" * 72,
188
- "",
189
- "1. Preamble",
190
- " This document represents the harmonised, best‑available content derived from the",
191
- " source materials submitted for forensic analysis. Where substantially identical",
192
- " passages were found, the version exhibiting greater clarity, completeness, and",
193
- " authoritative language has been retained. Contradictions identified between",
194
- " documents are enumerated in the accompanying Forensic Analysis Report.",
195
- "",
196
- "2. Consolidated Findings"
197
- ]
198
-
199
- for i, text in enumerate(docs_text):
200
- lines.append(f"\n Section {2+i}. Source Document {i+1}")
201
- paras = _split_paragraphs(text, max_paras=150)
202
- for j, para in enumerate(paras):
203
- best_ver = best_lookup.get((i, j), para)
204
- lines.append(f" [{i+1}.{j+1}] {_clean(best_ver)}")
205
-
206
- lines.append("\n3. Identified Contradictions")
207
- if contradictions:
208
- for i, c in enumerate(contradictions[:20]):
209
- lines.append(f" {i+1}. Document {c['doc1']} states: '{c['sentence1']}'")
210
- lines.append(f" Document {c['doc2']} states: '{c['sentence2']}'")
211
- lines.append(" These statements are materially irreconcilable.")
212
- else:
213
- lines.append(" No direct contradictions were detected in the source materials.")
214
-
215
- lines.append("\n" + "=" * 72)
216
- lines.append("END OF MASTER DOCUMENT")
217
- return "\n".join(lines)
218
-
219
- # ============================================================
220
- # 7. GRADIO PROCESS FUNCTION
221
- # ============================================================
222
- def process(file1, file2, file3):
223
- files = [f for f in (file1, file2, file3) if f is not None]
224
- if not files:
225
- return "Upload at least one document.", "", None
226
-
227
- docs_text = []
228
- docs_paras = []
229
- for f in files:
230
- txt = extract(f)
231
- if txt.startswith("[Unsupported"):
232
- return f"File error: {txt}", "", None
233
- docs_text.append(txt)
234
- docs_paras.append(_split_paragraphs(txt, max_paras=150))
235
-
236
- # Safe analysis
237
- dup_result = safe_duplicate_analysis(docs_paras)
238
- contradictions = safe_contradictions(docs_paras)
239
- master = build_master(docs_text, dup_result["best_lookup"], contradictions)
240
-
241
- # Analysis report
242
- report = []
243
- report.append("FORENSIC ANALYSIS REPORT")
244
- report.append("=" * 72)
245
- report.append(f"Compiled: {datetime.now().strftime('%d %B %Y, %H:%M')}")
246
- report.append(f"Documents examined: {len(files)}")
247
- report.append(f"Duplicate passages identified: {len(dup_result['duplicates'])}")
248
- report.append(f"Contradictions found: {len(contradictions)}")
249
- if dup_result["duplicates"]:
250
- report.append("\nDuplicate Details (best version selected):")
251
- for d in dup_result["duplicates"][:20]:
252
- report.append(f" Doc {d['doc1']} ↔ Doc {d['doc2']} | Similarity {d['similarity']}")
253
- if contradictions:
254
- report.append("\nContradictions:")
255
- for c in contradictions[:20]:
256
- report.append(f" Doc {c['doc1']}: '{c['sentence1']}'")
257
- report.append(f" Doc {c['doc2']}: '{c['sentence2']}'")
258
- report.append("=" * 72)
259
-
260
- # TXT export
261
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8")
262
- tmp.write(master + "\n\n" + "\n".join(report))
263
- tmp.close()
264
-
265
- return master, "\n".join(report), tmp.name
266
-
267
- # ============================================================
268
- # 8. GRADIO UI
269
- # ============================================================
270
- with gr.Blocks(title="Seamstresses Framework", theme=gr.themes.Soft(primary_hue="cyan")) as demo:
271
- gr.Markdown("## 🧡 Seamstresses Framework")
272
- gr.Markdown("Forensic harmonisation of legal documents. Finds duplicates, selects the most authoritative version, and flags contradictions β€” all in polished English.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
  with gr.Row():
275
- file1 = gr.File(label="Document 1", file_types=[".pdf", ".txt", ".docx"])
276
- file2 = gr.File(label="Document 2", file_types=[".pdf", ".txt", ".docx"])
277
- file3 = gr.File(label="Document 3 (Optional)", file_types=[".pdf", ".txt", ".docx"])
278
-
279
- btn = gr.Button("Analyse & Compile Master Document", variant="primary")
 
280
 
281
  with gr.Tabs():
282
  with gr.TabItem("πŸ“„ Master Document"):
283
- master_out = gr.Textbox(label="Master Evidence Document", lines=25)
 
284
  with gr.TabItem("πŸ”¬ Analysis Report"):
285
- report_out = gr.Textbox(label="Forensic Analysis Report", lines=20)
286
- with gr.TabItem("πŸ“₯ Export"):
287
- download = gr.File(label="Download TXT", interactive=False)
 
288
 
289
- btn.click(fn=process, inputs=[file1, file2, file3], outputs=[master_out, report_out, download])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').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('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').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()