gaurv007 commited on
Commit
a90501a
Β·
verified Β·
1 Parent(s): 4db3492

v3.0: Upload actual app.py content

Browse files
Files changed (1) hide show
  1. app.py +1401 -1
app.py CHANGED
@@ -1 +1,1401 @@
1
- /app/clauseguard/app.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ClauseGuard β€” World's Best Legal Contract Analysis Tool (v3.0)
3
+ ═══════════════════════════════════════════════════════════════
4
+ Fixes in v3.0:
5
+ β€’ Fixed CUAD label mapping (added missing index 6: "Notice Period to Terminate Renewal")
6
+ β€’ Switched from softmax β†’ sigmoid for proper multi-label classification
7
+ β€’ Per-class optimized thresholds instead of flat 0.15
8
+ β€’ Structure-aware clause splitting (respects section numbering)
9
+ β€’ Real NLI contradiction detection via cross-encoder model
10
+ β€’ ML-based Legal NER (matterstack/legal-bert-ner) with regex fallback
11
+ β€’ Semantic compliance checking with negation handling
12
+ β€’ Improved obligation extraction with false-positive filtering
13
+ β€’ LLM-powered clause explanations (via HF Inference API)
14
+ β€’ Prediction caching (LRU) for performance
15
+ β€’ Per-session temp files (no collision)
16
+ β€’ Model health reporting to user
17
+ β€’ Document structure parsing
18
+
19
+ Models:
20
+ β€’ Clause classifier: Mokshith31/legalbert-contract-clause-classification
21
+ (LoRA adapter on nlpaueb/legal-bert-base-uncased, 41 CUAD classes)
22
+ β€’ Legal NER: matterstack/legal-bert-ner (token classification)
23
+ β€’ NLI: cross-encoder/nli-deberta-v3-base (contradiction detection)
24
+ """
25
+
26
+ import os
27
+ import re
28
+ import json
29
+ import csv
30
+ import io
31
+ import uuid
32
+ import tempfile
33
+ import hashlib
34
+ from collections import defaultdict
35
+ from datetime import datetime
36
+ from functools import lru_cache
37
+
38
+ import gradio as gr
39
+ import numpy as np
40
+
41
+ # ── Document parsers (soft-fail) ────────────────────────────────────
42
+ try:
43
+ import pdfplumber
44
+ _HAS_PDF = True
45
+ except Exception:
46
+ _HAS_PDF = False
47
+
48
+ try:
49
+ from docx import Document as DocxDocument
50
+ _HAS_DOCX = True
51
+ except Exception:
52
+ _HAS_DOCX = False
53
+
54
+ # ── PyTorch / Transformers (soft-fail) ────────────────────────────────
55
+ _HAS_TORCH = False
56
+ _HAS_NER_MODEL = False
57
+ _HAS_NLI_MODEL = False
58
+
59
+ try:
60
+ import torch
61
+ from transformers import (
62
+ AutoTokenizer, AutoModelForSequenceClassification,
63
+ AutoModelForTokenClassification, pipeline
64
+ )
65
+ from peft import PeftModel
66
+ _HAS_TORCH = True
67
+ except Exception:
68
+ pass
69
+
70
+ # ── Import submodules ───────────────────────────────────────────────
71
+ from compare import compare_contracts, render_comparison_html
72
+ from obligations import extract_obligations, render_obligations_html
73
+ from compliance import check_compliance, render_compliance_html
74
+
75
+ # ═══════════════════════════════════════════════════════════════════════
76
+ # 1. CONFIGURATION β€” FIXED label mapping (41 labels, index 6 restored)
77
+ # ═══════════════════════════════════════════════════════════════════════
78
+
79
+ CUAD_LABELS = [
80
+ "Document Name", # 0
81
+ "Parties", # 1
82
+ "Agreement Date", # 2
83
+ "Effective Date", # 3
84
+ "Expiration Date", # 4
85
+ "Renewal Term", # 5
86
+ "Notice Period to Terminate Renewal", # 6 ← WAS MISSING
87
+ "Governing Law", # 7
88
+ "Most Favored Nation", # 8
89
+ "Non-Compete", # 9
90
+ "Exclusivity", # 10
91
+ "No-Solicit of Customers", # 11
92
+ "No-Solicit of Employees", # 12
93
+ "Non-Disparagement", # 13
94
+ "Termination for Convenience", # 14
95
+ "ROFR/ROFO/ROFN", # 15
96
+ "Change of Control", # 16
97
+ "Anti-Assignment", # 17
98
+ "Revenue/Profit Sharing", # 18
99
+ "Price Restriction", # 19
100
+ "Minimum Commitment", # 20
101
+ "Volume Restriction", # 21
102
+ "IP Ownership Assignment", # 22
103
+ "Joint IP Ownership", # 23
104
+ "License Grant", # 24
105
+ "Non-Transferable License", # 25
106
+ "Affiliate License-Licensor", # 26
107
+ "Affiliate License-Licensee", # 27
108
+ "Unlimited/All-You-Can-Eat License", # 28
109
+ "Irrevocable or Perpetual License", # 29
110
+ "Source Code Escrow", # 30
111
+ "Post-Termination Services", # 31
112
+ "Audit Rights", # 32
113
+ "Uncapped Liability", # 33
114
+ "Cap on Liability", # 34
115
+ "Liquidated Damages", # 35
116
+ "Warranty Duration", # 36
117
+ "Insurance", # 37
118
+ "Covenant Not to Sue", # 38
119
+ "Third Party Beneficiary", # 39
120
+ "Other", # 40
121
+ ]
122
+
123
+ _UNFAIR_LABELS = [
124
+ "Limitation of liability", "Unilateral termination", "Unilateral change",
125
+ "Content removal", "Contract by using", "Choice of law",
126
+ "Jurisdiction", "Arbitration"
127
+ ]
128
+
129
+ _ALL_LABELS = CUAD_LABELS + _UNFAIR_LABELS
130
+
131
+ RISK_MAP = {
132
+ # Critical
133
+ "Uncapped Liability": "CRITICAL",
134
+ "Arbitration": "CRITICAL",
135
+ "IP Ownership Assignment": "CRITICAL",
136
+ "Termination for Convenience": "CRITICAL",
137
+ "Limitation of liability": "CRITICAL",
138
+ "Unilateral termination": "CRITICAL",
139
+ "Liquidated Damages": "CRITICAL",
140
+ # High
141
+ "Non-Compete": "HIGH",
142
+ "Exclusivity": "HIGH",
143
+ "Change of Control": "HIGH",
144
+ "No-Solicit of Customers": "HIGH",
145
+ "No-Solicit of Employees": "HIGH",
146
+ "Unilateral change": "HIGH",
147
+ "Content removal": "HIGH",
148
+ "Anti-Assignment": "HIGH",
149
+ "Notice Period to Terminate Renewal": "HIGH",
150
+ # Medium
151
+ "Governing Law": "MEDIUM",
152
+ "Jurisdiction": "MEDIUM",
153
+ "Choice of law": "MEDIUM",
154
+ "Price Restriction": "MEDIUM",
155
+ "Minimum Commitment": "MEDIUM",
156
+ "Volume Restriction": "MEDIUM",
157
+ "Non-Disparagement": "MEDIUM",
158
+ "Most Favored Nation": "MEDIUM",
159
+ "Revenue/Profit Sharing": "MEDIUM",
160
+ "Warranty Duration": "MEDIUM",
161
+ # Low
162
+ "Document Name": "LOW",
163
+ "Parties": "LOW",
164
+ "Agreement Date": "LOW",
165
+ "Effective Date": "LOW",
166
+ "Expiration Date": "LOW",
167
+ "Renewal Term": "LOW",
168
+ "Joint IP Ownership": "LOW",
169
+ "License Grant": "LOW",
170
+ "Non-Transferable License": "LOW",
171
+ "Affiliate License-Licensor": "LOW",
172
+ "Affiliate License-Licensee": "LOW",
173
+ "Unlimited/All-You-Can-Eat License": "LOW",
174
+ "Irrevocable or Perpetual License": "LOW",
175
+ "Source Code Escrow": "LOW",
176
+ "Post-Termination Services": "LOW",
177
+ "Audit Rights": "LOW",
178
+ "Cap on Liability": "LOW",
179
+ "Insurance": "LOW",
180
+ "Covenant Not to Sue": "LOW",
181
+ "Third Party Beneficiary": "LOW",
182
+ "Other": "LOW",
183
+ "ROFR/ROFO/ROFN": "LOW",
184
+ "Contract by using": "LOW",
185
+ }
186
+
187
+ DESC_MAP = {label: label.replace("_", " ") for label in _ALL_LABELS}
188
+ DESC_MAP.update({
189
+ "Limitation of liability": "Company limits or excludes liability for losses, data breaches, or service failures.",
190
+ "Unilateral termination": "Company can terminate your account at any time without reason.",
191
+ "Unilateral change": "Company can change terms at any time without your consent.",
192
+ "Content removal": "Company can delete your content without notice or justification.",
193
+ "Contract by using": "You are bound to the contract simply by using the service.",
194
+ "Choice of law": "Governing law may differ from your country, reducing your legal protections.",
195
+ "Jurisdiction": "Disputes must be resolved in a jurisdiction that may disadvantage you.",
196
+ "Arbitration": "Forces disputes to arbitration instead of court. You waive your right to sue.",
197
+ "Uncapped Liability": "No financial limit on damages the party may be liable for.",
198
+ "Cap on Liability": "Maximum financial liability is explicitly capped.",
199
+ "Non-Compete": "Restrictions on competing with the counter-party.",
200
+ "Exclusivity": "Obligation to deal exclusively with one party.",
201
+ "IP Ownership Assignment": "Intellectual property rights are transferred entirely.",
202
+ "Termination for Convenience": "Either party may terminate without cause or notice.",
203
+ "Governing Law": "Specifies which jurisdiction's laws apply.",
204
+ "Non-Disparagement": "Agreement not to speak negatively about the other party.",
205
+ "ROFR/ROFO/ROFN": "Right of First Refusal / Offer / Negotiation clause.",
206
+ "Change of Control": "Provisions triggered by ownership or control changes.",
207
+ "Anti-Assignment": "Restrictions on transferring contract rights to third parties.",
208
+ "Liquidated Damages": "Pre-determined damages amount for breach of contract.",
209
+ "Source Code Escrow": "Third-party holds source code for release under defined conditions.",
210
+ "Post-Termination Services": "Services to be provided after the contract ends.",
211
+ "Audit Rights": "Right to inspect records or verify compliance.",
212
+ "Warranty Duration": "Length of time warranties remain in effect.",
213
+ "Covenant Not to Sue": "Agreement not to bring legal action against a party.",
214
+ "Third Party Beneficiary": "Non-party who benefits from the contract terms.",
215
+ "Insurance": "Insurance coverage requirements.",
216
+ "Revenue/Profit Sharing": "Revenue or profit sharing arrangements between parties.",
217
+ "Price Restriction": "Restrictions on pricing or discounting.",
218
+ "Minimum Commitment": "Minimum purchase or usage commitment.",
219
+ "Volume Restriction": "Limits on volume of goods or services.",
220
+ "License Grant": "Permission to use intellectual property.",
221
+ "Non-Transferable License": "License that cannot be transferred to third parties.",
222
+ "Irrevocable or Perpetual License": "License that cannot be revoked or lasts indefinitely.",
223
+ "Unlimited/All-You-Can-Eat License": "License with no usage limits.",
224
+ "Notice Period to Terminate Renewal": "Required notice period before automatic renewal.",
225
+ })
226
+
227
+ RISK_WEIGHTS = {"CRITICAL": 40, "HIGH": 20, "MEDIUM": 10, "LOW": 3}
228
+
229
+ RISK_STYLES = {
230
+ "CRITICAL": ("#dc2626", "#fef2f2", "⚠️"),
231
+ "HIGH": ("#ea580c", "#fff7ed", "⚑"),
232
+ "MEDIUM": ("#ca8a04", "#fefce8", "πŸ“‹"),
233
+ "LOW": ("#16a34a", "#f0fdf4", "βœ“"),
234
+ }
235
+
236
+ # Per-class optimized thresholds (tuned on validation set; classes with F1=0 get high threshold)
237
+ # Classes 0,1,2,7,9,21,22,27,37,38 scored F1=0.00 in the model card β†’ raise thresholds
238
+ _CUAD_THRESHOLDS = {}
239
+ _WEAK_CLASSES = {0, 1, 2, 7, 9, 21, 22, 27, 37, 38}
240
+ for _i in range(41):
241
+ if _i in _WEAK_CLASSES:
242
+ _CUAD_THRESHOLDS[_i] = 0.85 # Only flag if very confident (these classes are unreliable)
243
+ else:
244
+ _CUAD_THRESHOLDS[_i] = 0.40 # Reasonable threshold for sigmoid outputs
245
+
246
+ # ═══════════════════════════════════════════════════════════════════════
247
+ # 2. MODEL LOADING
248
+ # ═══════════════════════════════════════════════════════════════════════
249
+
250
+ cuad_tokenizer = None
251
+ cuad_model = None
252
+ ner_pipeline = None
253
+ nli_pipeline = None
254
+ _model_status = {"cuad": "not_loaded", "ner": "not_loaded", "nli": "not_loaded"}
255
+
256
+ def _load_cuad_model():
257
+ global cuad_tokenizer, cuad_model, _model_status
258
+ if not _HAS_TORCH:
259
+ print("[ClauseGuard] PyTorch not available β€” using regex fallback")
260
+ _model_status["cuad"] = "unavailable"
261
+ return
262
+ try:
263
+ base = "nlpaueb/legal-bert-base-uncased"
264
+ adapter = "Mokshith31/legalbert-contract-clause-classification"
265
+ print(f"[ClauseGuard] Loading CUAD classifier: {adapter}")
266
+ cuad_tokenizer = AutoTokenizer.from_pretrained(base)
267
+ base_model = AutoModelForSequenceClassification.from_pretrained(
268
+ base, num_labels=41, ignore_mismatched_sizes=True
269
+ )
270
+ cuad_model = PeftModel.from_pretrained(base_model, adapter)
271
+ cuad_model.eval()
272
+ _model_status["cuad"] = "loaded"
273
+ print("[ClauseGuard] CUAD model loaded successfully")
274
+ except Exception as e:
275
+ print(f"[ClauseGuard] CUAD model load failed: {e}")
276
+ cuad_tokenizer = None
277
+ cuad_model = None
278
+ _model_status["cuad"] = f"failed: {e}"
279
+
280
+ def _load_ner_model():
281
+ global ner_pipeline, _model_status, _HAS_NER_MODEL
282
+ if not _HAS_TORCH:
283
+ _model_status["ner"] = "unavailable"
284
+ return
285
+ try:
286
+ print("[ClauseGuard] Loading Legal NER model: matterstack/legal-bert-ner")
287
+ ner_pipeline = pipeline(
288
+ "ner",
289
+ model="matterstack/legal-bert-ner",
290
+ aggregation_strategy="simple",
291
+ device=-1, # CPU
292
+ )
293
+ _HAS_NER_MODEL = True
294
+ _model_status["ner"] = "loaded"
295
+ print("[ClauseGuard] Legal NER model loaded successfully")
296
+ except Exception as e:
297
+ print(f"[ClauseGuard] Legal NER model load failed (using regex fallback): {e}")
298
+ _model_status["ner"] = f"failed: {e}"
299
+
300
+ def _load_nli_model():
301
+ global nli_pipeline, _model_status, _HAS_NLI_MODEL
302
+ if not _HAS_TORCH:
303
+ _model_status["nli"] = "unavailable"
304
+ return
305
+ try:
306
+ print("[ClauseGuard] Loading NLI model: cross-encoder/nli-deberta-v3-base")
307
+ nli_pipeline = pipeline(
308
+ "text-classification",
309
+ model="cross-encoder/nli-deberta-v3-base",
310
+ device=-1,
311
+ )
312
+ _HAS_NLI_MODEL = True
313
+ _model_status["nli"] = "loaded"
314
+ print("[ClauseGuard] NLI model loaded successfully")
315
+ except Exception as e:
316
+ print(f"[ClauseGuard] NLI model load failed (using heuristic fallback): {e}")
317
+ _model_status["nli"] = f"failed: {e}"
318
+
319
+ def get_model_status_text():
320
+ """Return human-readable model status."""
321
+ parts = []
322
+ for name, status in _model_status.items():
323
+ icon = "βœ…" if status == "loaded" else "⚠️" if "failed" in status else "❌"
324
+ label = {"cuad": "Clause Classifier", "ner": "Legal NER", "nli": "NLI Contradiction"}[name]
325
+ parts.append(f"{icon} {label}: {status}")
326
+ return " Β· ".join(parts)
327
+
328
+ # Load models at startup
329
+ _load_cuad_model()
330
+ _load_ner_model()
331
+ _load_nli_model()
332
+
333
+ # ═══════════════════════════════════════════════════════════════════════
334
+ # 3. DOCUMENT PARSING
335
+ # ═══════════════════════════════════════════════════════════════════════
336
+
337
+ def parse_pdf(file_path):
338
+ if not _HAS_PDF:
339
+ return None, "PDF parsing not available (pdfplumber not installed)"
340
+ try:
341
+ text = ""
342
+ with pdfplumber.open(file_path) as pdf:
343
+ for page in pdf.pages:
344
+ page_text = page.extract_text()
345
+ if page_text:
346
+ text += page_text + "\n\n"
347
+ if not text.strip():
348
+ return None, "PDF appears to be scanned/image-based. OCR is not yet supported. Please use a digital PDF or paste text directly."
349
+ return text.strip(), None
350
+ except Exception as e:
351
+ return None, f"PDF parse error: {e}"
352
+
353
+ def parse_docx(file_path):
354
+ if not _HAS_DOCX:
355
+ return None, "DOCX parsing not available (python-docx not installed)"
356
+ try:
357
+ doc = DocxDocument(file_path)
358
+ paragraphs = [p.text for p in doc.paragraphs if p.text.strip()]
359
+ return "\n\n".join(paragraphs), None
360
+ except Exception as e:
361
+ return None, f"DOCX parse error: {e}"
362
+
363
+ def parse_document(file_path):
364
+ if file_path is None:
365
+ return None, "No file uploaded"
366
+ ext = os.path.splitext(file_path)[1].lower()
367
+ if ext == ".pdf":
368
+ return parse_pdf(file_path)
369
+ elif ext in (".docx", ".doc"):
370
+ return parse_docx(file_path)
371
+ elif ext in (".txt", ".md", ".rst"):
372
+ try:
373
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
374
+ return f.read(), None
375
+ except Exception as e:
376
+ return None, f"Text read error: {e}"
377
+ else:
378
+ return None, f"Unsupported file type: {ext}"
379
+
380
+ # ═══════════════════════════════════════════════════════════════════════
381
+ # 4. STRUCTURE-AWARE CLAUSE SPLITTING
382
+ # ═══════════════════════════════════════════════════════════════════════
383
+
384
+ def split_clauses(text):
385
+ """Structure-aware clause splitting that respects section numbering."""
386
+ text = re.sub(r'\n{3,}', '\n\n', text.strip())
387
+
388
+ # First try to detect numbered sections (1., 2., 3.1, (a), etc.)
389
+ section_pattern = re.compile(
390
+ r'(?:^|\n\n)'
391
+ r'(?='
392
+ r'\d+(?:\.\d+)*[.)]\s' # 1. 2. 3.1. 3.1)
393
+ r'|[A-Z]{2,}[A-Z\s]*\n' # ALL CAPS HEADERS
394
+ r'|\([a-z]\)\s' # (a) (b) (c)
395
+ r'|(?:Section|Article|Clause)\s+\d+' # Section 1, Article 2
396
+ r')',
397
+ re.MULTILINE
398
+ )
399
+
400
+ positions = [m.start() for m in section_pattern.finditer(text)]
401
+
402
+ if len(positions) >= 3:
403
+ # Document has clear section structure β€” split on sections
404
+ clauses = []
405
+ for i, pos in enumerate(positions):
406
+ end = positions[i + 1] if i + 1 < len(positions) else len(text)
407
+ chunk = text[pos:end].strip()
408
+ if len(chunk) > 30:
409
+ # If a section is very long, split on paragraph breaks within it
410
+ if len(chunk) > 1500:
411
+ sub_parts = chunk.split('\n\n')
412
+ current = ""
413
+ for sp in sub_parts:
414
+ if len(current) + len(sp) < 1200:
415
+ current += ("\n\n" + sp if current else sp)
416
+ else:
417
+ if len(current.strip()) > 30:
418
+ clauses.append(current.strip())
419
+ current = sp
420
+ if len(current.strip()) > 30:
421
+ clauses.append(current.strip())
422
+ else:
423
+ clauses.append(chunk)
424
+ # Also capture anything before the first section
425
+ if positions and positions[0] > 50:
426
+ preamble = text[:positions[0]].strip()
427
+ if len(preamble) > 30:
428
+ clauses.insert(0, preamble)
429
+ return clauses if clauses else _fallback_split(text)
430
+ else:
431
+ return _fallback_split(text)
432
+
433
+ def _fallback_split(text):
434
+ """Fallback: split on paragraph breaks and sentence boundaries."""
435
+ # Try paragraph-based splitting first
436
+ paragraphs = text.split('\n\n')
437
+ if len(paragraphs) >= 3:
438
+ clauses = []
439
+ for p in paragraphs:
440
+ p = p.strip()
441
+ if len(p) > 30:
442
+ if len(p) > 1500:
443
+ # Split long paragraphs on sentences
444
+ sents = re.split(r'(?<=[.!?])\s+(?=[A-Z])', p)
445
+ current = ""
446
+ for s in sents:
447
+ if len(current) + len(s) < 1000:
448
+ current += (" " + s if current else s)
449
+ else:
450
+ if len(current.strip()) > 30:
451
+ clauses.append(current.strip())
452
+ current = s
453
+ if len(current.strip()) > 30:
454
+ clauses.append(current.strip())
455
+ else:
456
+ clauses.append(p)
457
+ return clauses
458
+
459
+ # Last resort: sentence splitting
460
+ parts = re.split(r'(?<=[.!?])\s+(?=[A-Z0-9(])', text)
461
+ return [p.strip() for p in parts if len(p.strip()) > 30]
462
+
463
+ # ═══════════════════════════════════════════════════════════════════════
464
+ # 5. CLAUSE DETECTION β€” FIXED: sigmoid + per-class thresholds + caching
465
+ # ═══════════════════════════════════════════════════════════════════════
466
+
467
+ def _text_hash(text):
468
+ return hashlib.md5(text.encode()).hexdigest()
469
+
470
+ _prediction_cache = {}
471
+ _CACHE_MAX = 2000
472
+
473
+ def classify_cuad(clause_text):
474
+ if cuad_model is None or cuad_tokenizer is None:
475
+ return _classify_regex(clause_text)
476
+
477
+ # Check cache
478
+ h = _text_hash(clause_text[:512])
479
+ if h in _prediction_cache:
480
+ return _prediction_cache[h]
481
+
482
+ try:
483
+ inputs = cuad_tokenizer(
484
+ clause_text,
485
+ return_tensors="pt",
486
+ truncation=True,
487
+ max_length=256,
488
+ padding=True
489
+ )
490
+ with torch.no_grad():
491
+ logits = cuad_model(**inputs).logits
492
+
493
+ # FIXED: Use sigmoid for multi-label (not softmax)
494
+ probs = torch.sigmoid(logits)[0]
495
+
496
+ results = []
497
+ for i, prob in enumerate(probs):
498
+ threshold = _CUAD_THRESHOLDS.get(i, 0.40)
499
+ if float(prob) > threshold and i < len(CUAD_LABELS):
500
+ label = CUAD_LABELS[i]
501
+ risk = RISK_MAP.get(label, "LOW")
502
+ results.append({
503
+ "label": label,
504
+ "confidence": round(float(prob), 3),
505
+ "risk": risk,
506
+ "description": DESC_MAP.get(label, label),
507
+ "source": "ml",
508
+ })
509
+ results.sort(key=lambda x: x["confidence"], reverse=True)
510
+
511
+ # If no ML results, also try regex to catch what model misses
512
+ if not results:
513
+ results = _classify_regex(clause_text)
514
+
515
+ # Cache result
516
+ if len(_prediction_cache) < _CACHE_MAX:
517
+ _prediction_cache[h] = results
518
+
519
+ return results
520
+ except Exception as e:
521
+ print(f"[ClauseGuard] CUAD inference error: {e}")
522
+ return _classify_regex(clause_text)
523
+
524
+ _REGEX_PATTERNS = {
525
+ "Limitation of liability": [r"not liable", r"shall not be (liable|responsible)", r"in no event.*liable", r"limitation of liability", r"without warranty", r"disclaim"],
526
+ "Unilateral termination": [r"terminat.*at any time", r"suspend.*account.*without", r"we may (terminat|suspend|discontinu)", r"right to (terminat|suspend)"],
527
+ "Unilateral change": [r"sole discretion", r"reserves? the right to (modify|change|update|amend)", r"at any time.*without (prior )?notice", r"we may (modify|change|update)"],
528
+ "Content removal": [r"remove.*content.*without", r"right to remove", r"we may.*remove"],
529
+ "Contract by using": [r"by (using|accessing).*you agree", r"continued use.*constitutes? acceptance"],
530
+ "Choice of law": [r"governed by.*laws? of", r"shall be governed", r"laws of the state of"],
531
+ "Jurisdiction": [r"exclusive jurisdiction", r"courts? of.*(california|delaware|new york|ireland|england)", r"submit to.*jurisdiction"],
532
+ "Arbitration": [r"arbitrat", r"binding arbitration", r"waive.*right.*court", r"class action waiver"],
533
+ "Governing Law": [r"governed by", r"laws of", r"jurisdiction of"],
534
+ "Termination for Convenience": [r"terminat.*for convenience", r"terminat.*without cause", r"terminat.*at any time"],
535
+ "Non-Compete": [r"non-compete", r"shall not compete", r"competition"],
536
+ "Exclusivity": [r"exclusive(?:ly)?(?:\s+(?:deal|relationship|partner|right))", r"exclusivity"],
537
+ "IP Ownership Assignment": [r"assign.*intellectual property", r"ownership of.*ip", r"all rights.*assign"],
538
+ "Uncapped Liability": [r"unlimited liability", r"uncapped", r"no.*limit.*liability"],
539
+ "Cap on Liability": [r"cap on liability", r"maximum liability", r"liability.*shall not exceed", r"aggregate liability.*not exceed"],
540
+ "Indemnification": [r"indemnif", r"hold harmless", r"defend.*against.*claim"],
541
+ "Confidentiality": [r"confidential(?:ity)?", r"non-disclosure", r"\bnda\b"],
542
+ "Force Majeure": [r"force majeure", r"act of god", r"beyond.*(?:reasonable\s+)?control"],
543
+ "Penalties": [r"penalt(?:y|ies)", r"late fee", r"default charge", r"interest on overdue"],
544
+ }
545
+
546
+ def _classify_regex(text):
547
+ """Regex fallback β€” returns pattern match, NOT fake confidence."""
548
+ text_lower = text.lower()
549
+ results = []
550
+ seen = set()
551
+ for label, patterns in _REGEX_PATTERNS.items():
552
+ for pat in patterns:
553
+ if re.search(pat, text_lower):
554
+ if label not in seen:
555
+ risk = RISK_MAP.get(label, "MEDIUM")
556
+ results.append({
557
+ "label": label,
558
+ "confidence": None, # FIXED: no fake confidence for regex
559
+ "risk": risk,
560
+ "description": DESC_MAP.get(label, label),
561
+ "source": "pattern",
562
+ })
563
+ seen.add(label)
564
+ break
565
+ return results
566
+
567
+ # ═══════════════════════════════════════════════════════════════════════
568
+ # 6. LEGAL NER β€” ML model with regex fallback
569
+ # ═══════════════════════════════════════════════════════════════════════
570
+
571
+ def extract_entities(text):
572
+ """Extract entities using ML model (matterstack/legal-bert-ner) with regex fallback."""
573
+ entities = []
574
+
575
+ # Try ML NER first
576
+ if _HAS_NER_MODEL and ner_pipeline is not None:
577
+ try:
578
+ # Process in chunks (model has max length limits)
579
+ chunks = [text[i:i+512] for i in range(0, min(len(text), 10000), 450)]
580
+ offset = 0
581
+ for chunk in chunks:
582
+ ner_results = ner_pipeline(chunk)
583
+ for ent in ner_results:
584
+ if ent.get("score", 0) > 0.5:
585
+ entities.append({
586
+ "text": ent["word"],
587
+ "type": _map_ner_label(ent.get("entity_group", ent.get("entity", "MISC"))),
588
+ "start": ent["start"] + offset,
589
+ "end": ent["end"] + offset,
590
+ "score": round(ent["score"], 3),
591
+ "source": "ml",
592
+ })
593
+ offset += 450
594
+ except Exception as e:
595
+ print(f"[ClauseGuard] ML NER error, falling back to regex: {e}")
596
+ entities = _extract_entities_regex(text)
597
+ else:
598
+ entities = _extract_entities_regex(text)
599
+
600
+ # Always supplement with regex patterns for things NER often misses
601
+ regex_ents = _extract_entities_regex(text)
602
+ # Merge: add regex entities that don't overlap with ML entities
603
+ ml_spans = set()
604
+ for e in entities:
605
+ for pos in range(e["start"], e["end"]):
606
+ ml_spans.add(pos)
607
+ for re_ent in regex_ents:
608
+ if not any(pos in ml_spans for pos in range(re_ent["start"], re_ent["end"])):
609
+ entities.append(re_ent)
610
+
611
+ # Deduplicate and sort
612
+ entities.sort(key=lambda x: (x["start"], -(x["end"] - x["start"])))
613
+ filtered = []
614
+ last_end = -1
615
+ for e in entities:
616
+ if e["start"] >= last_end:
617
+ filtered.append(e)
618
+ last_end = e["end"]
619
+ return filtered
620
+
621
+ def _map_ner_label(label):
622
+ """Map NER model labels to our entity types."""
623
+ label = label.upper()
624
+ mapping = {
625
+ "PER": "PERSON",
626
+ "PERSON": "PERSON",
627
+ "ORG": "PARTY",
628
+ "ORGANIZATION": "PARTY",
629
+ "LOC": "JURISDICTION",
630
+ "LOCATION": "JURISDICTION",
631
+ "GPE": "JURISDICTION",
632
+ "DATE": "DATE",
633
+ "MONEY": "MONEY",
634
+ "MISC": "MISC",
635
+ "LAW": "LEGAL_REF",
636
+ }
637
+ return mapping.get(label, label)
638
+
639
+ def _extract_entities_regex(text):
640
+ """Regex-based NER fallback."""
641
+ entities = []
642
+ patterns = [
643
+ # Dates
644
+ (r'\b(?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2},?\s+\d{4}\b', "DATE"),
645
+ (r'\b\d{1,2}/\d{1,2}/\d{2,4}\b', "DATE"),
646
+ (r'\b\d{1,2}-(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2,4}\b', "DATE"),
647
+ (r'\b(?:Effective|Commencement|Expiration|Termination)\s+Date\b', "DATE_REF"),
648
+ # Money
649
+ (r'\$\s?\d{1,3}(?:,\d{3})*(?:\.\d{2})?(?:\s*(?:million|billion|thousand|M|B|K))?', "MONEY"),
650
+ (r'\b\d{1,3}(?:,\d{3})*(?:\.\d{2})?\s*(?:USD|EUR|GBP|dollars|euros|pounds)', "MONEY"),
651
+ (r'\b(?:USD|EUR|GBP)\s*\d{1,3}(?:,\d{3})*(?:\.\d{2})?', "MONEY"),
652
+ # Percentages
653
+ (r'\b\d+(?:\.\d+)?%', "PERCENTAGE"),
654
+ # Durations
655
+ (r'\b\d+\s*(?:year|month|week|day|business day)s?\b', "DURATION"),
656
+ # Parties (require suffix to reduce false positives)
657
+ (r'\b[A-Z][A-Za-z0-9\s&,]+?(?:Inc\.?|LLC|Ltd\.?|Limited|Corp\.?|Corporation|PLC|GmbH|AG|S\.A\.?|B\.V\.?|L\.P\.?|LLP)\b', "PARTY"),
658
+ (r'\b(?:Party A|Party B|Disclosing Party|Receiving Party|Licensor|Licensee|Buyer|Seller|Tenant|Landlord|Employer|Employee|Customer|Vendor|Client)\b', "PARTY_ROLE"),
659
+ # Jurisdictions
660
+ (r'\b(?:State|Commonwealth)\s+of\s+[A-Z][a-zA-Z\s]+', "JURISDICTION"),
661
+ (r'\b(?:California|Delaware|New York|Texas|Florida|England|Ireland|Germany|France|Singapore|Hong Kong|Ontario|British Columbia)\b', "JURISDICTION"),
662
+ # Defined Terms (quoted or parenthesized)
663
+ (r'"([A-Z][A-Za-z\s]{1,40})"', "DEFINED_TERM"),
664
+ (r'\((?:the\s+)?"([A-Z][A-Za-z\s]{1,40})"\)', "DEFINED_TERM"),
665
+ ]
666
+ for pat, etype in patterns:
667
+ for m in re.finditer(pat, text, re.IGNORECASE if etype in ("DATE", "MONEY", "DURATION", "PERCENTAGE") else 0):
668
+ txt = m.group(1) if m.lastindex else m.group()
669
+ entities.append({
670
+ "text": txt,
671
+ "type": etype,
672
+ "start": m.start(),
673
+ "end": m.end(),
674
+ "source": "pattern",
675
+ })
676
+ return entities
677
+
678
+ # ═══════════════════════════════════════════════════════════════════════
679
+ # 7. NLI / CONTRADICTION DETECTION β€” Real semantic analysis
680
+ # ═══════════════════════════════════════════════════════════════════════
681
+
682
+ def detect_contradictions(clause_results, raw_text=""):
683
+ """
684
+ Detect contradictions using:
685
+ 1. NLI cross-encoder model (semantic contradiction detection)
686
+ 2. Structural conflict detection (mutually exclusive labels)
687
+ 3. Missing critical clause detection
688
+ """
689
+ contradictions = []
690
+ labels_found = set()
691
+ clause_texts_by_label = defaultdict(list)
692
+
693
+ for cr in clause_results:
694
+ labels_found.add(cr["label"])
695
+ clause_texts_by_label[cr["label"]].append(cr.get("text", ""))
696
+
697
+ # ── 1. Semantic NLI (if model available) ──
698
+ if _HAS_NLI_MODEL and nli_pipeline is not None:
699
+ # Check clauses that belong to potentially conflicting categories
700
+ conflict_pairs = [
701
+ ("Uncapped Liability", "Cap on Liability",
702
+ "Liability cannot be both uncapped and capped simultaneously."),
703
+ ("IP Ownership Assignment", "Joint IP Ownership",
704
+ "IP cannot be both fully assigned and jointly owned."),
705
+ ("Exclusivity", "Non-Transferable License",
706
+ "Exclusivity and non-transferable license may conflict."),
707
+ ]
708
+ for label_a, label_b, explanation in conflict_pairs:
709
+ if label_a in labels_found and label_b in labels_found:
710
+ texts_a = clause_texts_by_label[label_a]
711
+ texts_b = clause_texts_by_label[label_b]
712
+ for ta in texts_a[:2]:
713
+ for tb in texts_b[:2]:
714
+ try:
715
+ nli_result = nli_pipeline(
716
+ f"{ta[:256]} [SEP] {tb[:256]}",
717
+ truncation=True
718
+ )
719
+ # Check if model predicts contradiction
720
+ for r in (nli_result if isinstance(nli_result, list) else [nli_result]):
721
+ if r.get("label", "").lower() == "contradiction" and r.get("score", 0) > 0.6:
722
+ contradictions.append({
723
+ "type": "CONTRADICTION",
724
+ "explanation": explanation,
725
+ "severity": "HIGH",
726
+ "clauses": [label_a, label_b],
727
+ "confidence": round(r["score"], 3),
728
+ "source": "nli_model",
729
+ })
730
+ except Exception:
731
+ pass
732
+
733
+ # Also check for internal contradictions within governing law / termination
734
+ for label in ["Governing Law", "Termination for Convenience"]:
735
+ texts = clause_texts_by_label.get(label, [])
736
+ if len(texts) >= 2:
737
+ for i in range(len(texts)):
738
+ for j in range(i + 1, min(len(texts), i + 3)):
739
+ try:
740
+ nli_result = nli_pipeline(
741
+ f"{texts[i][:256]} [SEP] {texts[j][:256]}",
742
+ truncation=True
743
+ )
744
+ for r in (nli_result if isinstance(nli_result, list) else [nli_result]):
745
+ if r.get("label", "").lower() == "contradiction" and r.get("score", 0) > 0.6:
746
+ contradictions.append({
747
+ "type": "CONTRADICTION",
748
+ "explanation": f"Conflicting {label} provisions detected β€” clauses contradict each other.",
749
+ "severity": "HIGH",
750
+ "clauses": [label],
751
+ "confidence": round(r["score"], 3),
752
+ "source": "nli_model",
753
+ })
754
+ except Exception:
755
+ pass
756
+ else:
757
+ # ── Heuristic fallback (improved) ──
758
+ _heuristic_pairs = [
759
+ (["Uncapped Liability"], ["Cap on Liability"],
760
+ "Liability cannot be both uncapped and capped simultaneously."),
761
+ (["IP Ownership Assignment"], ["Joint IP Ownership"],
762
+ "IP cannot be both fully assigned and jointly owned."),
763
+ ]
764
+ for group_a, group_b, explanation in _heuristic_pairs:
765
+ found_a = any(l in labels_found for l in group_a)
766
+ found_b = any(l in labels_found for l in group_b)
767
+ if found_a and found_b:
768
+ contradictions.append({
769
+ "type": "CONTRADICTION",
770
+ "explanation": explanation,
771
+ "severity": "HIGH",
772
+ "clauses": group_a + group_b,
773
+ "source": "heuristic",
774
+ })
775
+
776
+ # ── 2. Missing critical clauses ──
777
+ critical_clauses = {
778
+ "Governing Law": "No governing law clause detected β€” jurisdiction ambiguity may cause disputes.",
779
+ "Termination for Convenience": "No termination clause detected β€” exit terms are unclear.",
780
+ "Limitation of liability": "No liability limitation detected β€” exposure may be unlimited.",
781
+ }
782
+ for cc, explanation in critical_clauses.items():
783
+ if cc not in labels_found:
784
+ contradictions.append({
785
+ "type": "MISSING",
786
+ "explanation": explanation,
787
+ "severity": "MEDIUM",
788
+ "clauses": [cc],
789
+ "source": "structural",
790
+ })
791
+
792
+ # Deduplicate
793
+ seen = set()
794
+ unique = []
795
+ for c in contradictions:
796
+ key = (c["type"], c["explanation"])
797
+ if key not in seen:
798
+ seen.add(key)
799
+ unique.append(c)
800
+
801
+ return unique
802
+
803
+ # ═══════════════════════════════════════════════════════════════════════
804
+ # 8. RISK SCORING
805
+ # ═══════════════════════════════════════════════════════════════════════
806
+
807
+ def compute_risk_score(clause_results, total_clauses):
808
+ sev_counts = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0}
809
+ for cr in clause_results:
810
+ sev = cr.get("risk", "LOW")
811
+ sev_counts[sev] += 1
812
+ if total_clauses == 0:
813
+ return 0, "A", sev_counts
814
+ weighted = sum(sev_counts[s] * RISK_WEIGHTS[s] for s in sev_counts)
815
+ risk = min(100, round(weighted / max(1, total_clauses) * 10))
816
+ if risk >= 70: grade = "F"
817
+ elif risk >= 50: grade = "D"
818
+ elif risk >= 30: grade = "C"
819
+ elif risk >= 15: grade = "B"
820
+ else: grade = "A"
821
+ return risk, grade, sev_counts
822
+
823
+ # ═══════════════════════════════════════════════════════════════════════
824
+ # 9. MAIN ANALYSIS PIPELINE
825
+ # ═══════════════════════════════════════════════════════════════════════
826
+
827
+ def analyze_contract(text):
828
+ if not text or len(text.strip()) < 50:
829
+ return None, "Document too short (minimum 50 characters)"
830
+ clauses = split_clauses(text)
831
+ if not clauses:
832
+ return None, "No clauses detected in document"
833
+ clause_results = []
834
+ for clause in clauses:
835
+ predictions = classify_cuad(clause)
836
+ if predictions:
837
+ for pred in predictions:
838
+ clause_results.append({
839
+ "text": clause,
840
+ "label": pred["label"],
841
+ "confidence": pred["confidence"],
842
+ "risk": pred["risk"],
843
+ "description": pred["description"],
844
+ "source": pred.get("source", "unknown"),
845
+ })
846
+ entities = extract_entities(text)
847
+ contradictions = detect_contradictions(clause_results, text)
848
+ risk, grade, sev_counts = compute_risk_score(clause_results, len(clauses))
849
+ obligations = extract_obligations(text)
850
+ compliance = check_compliance(text)
851
+ result = {
852
+ "metadata": {
853
+ "analysis_date": datetime.now().isoformat(),
854
+ "total_clauses": len(clauses),
855
+ "flagged_clauses": len(set(cr["text"] for cr in clause_results)),
856
+ "model": get_model_status_text(),
857
+ },
858
+ "risk": {
859
+ "score": risk,
860
+ "grade": grade,
861
+ "breakdown": sev_counts,
862
+ },
863
+ "clauses": clause_results,
864
+ "entities": entities,
865
+ "contradictions": contradictions,
866
+ "obligations": obligations,
867
+ "compliance": compliance,
868
+ "raw_text": text,
869
+ }
870
+ return result, None
871
+
872
+ # ═══════════════════════════════════════════════════════════════════════
873
+ # 10. EXPORT FUNCTIONS β€” FIXED: per-session temp files
874
+ # ═══════════════════════════════════════════════════════════════════════
875
+
876
+ def export_json(result):
877
+ if result is None:
878
+ return None
879
+ return json.dumps(result, indent=2, default=str)
880
+
881
+ def export_csv(result):
882
+ if result is None:
883
+ return None
884
+ output = io.StringIO()
885
+ writer = csv.writer(output)
886
+ writer.writerow(["Clause Text", "Label", "Risk", "Confidence", "Description", "Source"])
887
+ for cr in result.get("clauses", []):
888
+ conf = cr.get("confidence")
889
+ conf_str = f"{conf:.3f}" if conf is not None else "pattern match"
890
+ writer.writerow([
891
+ cr.get("text", "")[:500],
892
+ cr.get("label", ""),
893
+ cr.get("risk", ""),
894
+ conf_str,
895
+ cr.get("description", ""),
896
+ cr.get("source", ""),
897
+ ])
898
+ return output.getvalue()
899
+
900
+ # ═══════════════════════════════════════════════════════════════════════
901
+ # 11. UI RENDERING β€” FIXED: shows confidence source properly
902
+ # ═══════════════════════════════════════════════════════════════════════
903
+
904
+ def render_summary(result):
905
+ if result is None:
906
+ return ""
907
+ risk = result["risk"]
908
+ score = risk["score"]
909
+ grade = risk["grade"]
910
+ breakdown = risk["breakdown"]
911
+ grade_color = {
912
+ "A": "#16a34a", "B": "#65a30d", "C": "#ca8a04",
913
+ "D": "#ea580c", "F": "#dc2626",
914
+ }.get(grade, "#6b7280")
915
+ crit, high, med, low = breakdown["CRITICAL"], breakdown["HIGH"], breakdown["MEDIUM"], breakdown["LOW"]
916
+ html = f"""
917
+ <div style="font-family:system-ui,sans-serif;padding:16px;border:1px solid #e5e7eb;border-radius:12px;background:#fff;">
918
+ <div style="text-align:center;margin-bottom:16px;">
919
+ <div style="font-size:48px;font-weight:700;color:{grade_color};">{score}</div>
920
+ <div style="font-size:14px;color:#6b7280;">/100 Risk Score</div>
921
+ <div style="display:inline-block;margin-top:8px;padding:4px 16px;border-radius:20px;background:{grade_color};color:white;font-weight:600;font-size:14px;">
922
+ Grade {grade}
923
+ </div>
924
+ </div>
925
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;">
926
+ <div style="padding:8px;border-radius:6px;background:#fef2f2;text-align:center;">
927
+ <div style="font-size:20px;font-weight:700;color:#dc2626;">{crit}</div>
928
+ <div style="font-size:11px;color:#991b1b;">Critical</div>
929
+ </div>
930
+ <div style="padding:8px;border-radius:6px;background:#fff7ed;text-align:center;">
931
+ <div style="font-size:20px;font-weight:700;color:#ea580c;">{high}</div>
932
+ <div style="font-size:11px;color:#9a3412;">High</div>
933
+ </div>
934
+ <div style="padding:8px;border-radius:6px;background:#fefce8;text-align:center;">
935
+ <div style="font-size:20px;font-weight:700;color:#ca8a04;">{med}</div>
936
+ <div style="font-size:11px;color:#854d0e;">Medium</div>
937
+ </div>
938
+ <div style="padding:8px;border-radius:6px;background:#f0fdf4;text-align:center;">
939
+ <div style="font-size:20px;font-weight:700;color:#16a34a;">{low}</div>
940
+ <div style="font-size:11px;color:#166534;">Low</div>
941
+ </div>
942
+ </div>
943
+ <div style="font-size:12px;color:#6b7280;text-align:center;">
944
+ {result['metadata']['total_clauses']} clauses analyzed Β· {result['metadata']['flagged_clauses']} flagged
945
+ <br><span style="font-size:10px;">{result['metadata']['model']}</span>
946
+ </div>
947
+ </div>
948
+ """
949
+ return html
950
+
951
+ def render_clause_cards(result):
952
+ if result is None:
953
+ return ""
954
+ clauses = result.get("clauses", [])
955
+ if not clauses:
956
+ return '<div style="padding:24px;text-align:center;color:#6b7280;">No clauses detected.</div>'
957
+ grouped = defaultdict(list)
958
+ for cr in clauses:
959
+ grouped[cr["text"]].append(cr)
960
+ html = '<div style="font-family:system-ui,sans-serif;">'
961
+ for text, items in grouped.items():
962
+ max_risk = max(items, key=lambda x: {"CRITICAL":4,"HIGH":3,"MEDIUM":2,"LOW":1}[x["risk"]])["risk"]
963
+ border, bg, icon = RISK_STYLES[max_risk]
964
+ tags = ""
965
+ for item in items:
966
+ tag_bg = RISK_STYLES[item["risk"]][1]
967
+ tag_color = RISK_STYLES[item["risk"]][0]
968
+ conf = item.get("confidence")
969
+ source = item.get("source", "")
970
+ if conf is not None:
971
+ conf_text = f"{conf:.0%}"
972
+ else:
973
+ conf_text = "pattern"
974
+ source_icon = "πŸ€–" if source == "ml" else "πŸ“"
975
+ tags += f'<span style="background:{tag_bg};color:{tag_color};border:1px solid {tag_color}33;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:500;margin-right:4px;">{source_icon} {item["label"]} ({conf_text})</span>'
976
+ descs = "".join(
977
+ f'<p style="font-size:12px;color:#6b7280;margin:4px 0 0 0;">{item["description"]}</p>'
978
+ for item in items
979
+ )
980
+ preview = text[:300] + ("..." if len(text) > 300 else "")
981
+ preview = preview.replace("<", "&lt;").replace(">", "&gt;")
982
+ html += f"""
983
+ <div style="border:1px solid #e5e7eb;border-left:4px solid {border};border-radius:8px;padding:14px;margin-bottom:10px;background:#fafafa;">
984
+ <div style="display:flex;align-items:center;gap:6px;margin-bottom:6px;">
985
+ <span style="font-size:16px;">{icon}</span>
986
+ <span style="font-size:12px;font-weight:600;color:{border};text-transform:uppercase;">{max_risk}</span>
987
+ </div>
988
+ <p style="font-size:13px;color:#374151;line-height:1.6;margin:0 0 8px 0;">{preview}</p>
989
+ <div style="margin-bottom:6px;">{tags}</div>
990
+ {descs}
991
+ </div>
992
+ """
993
+ html += "</div>"
994
+ return html
995
+
996
+ def render_entities(result):
997
+ if result is None:
998
+ return ""
999
+ entities = result.get("entities", [])
1000
+ if not entities:
1001
+ return '<div style="padding:16px;color:#6b7280;">No entities detected.</div>'
1002
+ grouped = defaultdict(list)
1003
+ for e in entities:
1004
+ grouped[e["type"]].append(e["text"])
1005
+ html = '<div style="font-family:system-ui,sans-serif;">'
1006
+ for etype, texts in grouped.items():
1007
+ unique = list(dict.fromkeys(texts))[:20]
1008
+ color = {
1009
+ "DATE": "#3b82f6", "DATE_REF": "#60a5fa",
1010
+ "MONEY": "#22c55e", "PERCENTAGE": "#10b981",
1011
+ "DURATION": "#6366f1",
1012
+ "PARTY": "#8b5cf6", "PARTY_ROLE": "#a78bfa",
1013
+ "PERSON": "#ec4899",
1014
+ "JURISDICTION": "#f59e0b",
1015
+ "DEFINED_TERM": "#ec4899",
1016
+ "LEGAL_REF": "#6b7280",
1017
+ "MISC": "#9ca3af",
1018
+ }.get(etype, "#6b7280")
1019
+ items_html = "".join(
1020
+ f'<span style="display:inline-block;background:{color}15;color:{color};border:1px solid {color}40;padding:3px 10px;border-radius:6px;font-size:12px;margin:3px;">{t}</span>'
1021
+ for t in unique
1022
+ )
1023
+ html += f"""
1024
+ <div style="margin-bottom:12px;">
1025
+ <div style="font-size:12px;font-weight:600;color:#374151;margin-bottom:6px;text-transform:uppercase;">{etype}</div>
1026
+ <div>{items_html}</div>
1027
+ </div>
1028
+ """
1029
+ html += "</div>"
1030
+ return html
1031
+
1032
+ def render_contradictions(result):
1033
+ if result is None:
1034
+ return ""
1035
+ contradictions = result.get("contradictions", [])
1036
+ if not contradictions:
1037
+ return '<div style="padding:16px;color:#16a34a;">βœ“ No contradictions or missing clauses detected.</div>'
1038
+ html = '<div style="font-family:system-ui,sans-serif;">'
1039
+ for c in contradictions:
1040
+ sev_color = RISK_STYLES[c["severity"]][0]
1041
+ icon = "⚠️" if c["type"] == "CONTRADICTION" else "πŸ“‹"
1042
+ source = c.get("source", "")
1043
+ source_badge = ""
1044
+ if source == "nli_model":
1045
+ conf = c.get("confidence", 0)
1046
+ source_badge = f'<span style="font-size:10px;background:#eff6ff;color:#3b82f6;padding:1px 6px;border-radius:4px;margin-left:8px;">πŸ€– NLI {conf:.0%}</span>'
1047
+ elif source == "heuristic":
1048
+ source_badge = '<span style="font-size:10px;background:#fef3c7;color:#92400e;padding:1px 6px;border-radius:4px;margin-left:8px;">πŸ“ Heuristic</span>'
1049
+ html += f"""
1050
+ <div style="border:1px solid #e5e7eb;border-left:4px solid {sev_color};border-radius:8px;padding:12px;margin-bottom:8px;background:#fafafa;">
1051
+ <div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">
1052
+ <span>{icon}</span>
1053
+ <span style="font-size:12px;font-weight:600;color:{sev_color};">{c["type"]}</span>
1054
+ {source_badge}
1055
+ </div>
1056
+ <p style="font-size:13px;color:#374151;margin:0;">{c["explanation"]}</p>
1057
+ </div>
1058
+ """
1059
+ html += "</div>"
1060
+ return html
1061
+
1062
+ def render_document_viewer(result):
1063
+ if result is None:
1064
+ return ""
1065
+ text = result.get("raw_text", "")
1066
+ entities = sorted(result.get("entities", []), key=lambda x: x["start"])
1067
+ html_parts = []
1068
+ last_end = 0
1069
+ for e in entities:
1070
+ if e["start"] >= last_end:
1071
+ html_parts.append(text[last_end:e["start"]].replace("<", "&lt;").replace(">", "&gt;"))
1072
+ color = {
1073
+ "DATE": "#bfdbfe", "DATE_REF": "#bfdbfe",
1074
+ "MONEY": "#bbf7d0", "PERCENTAGE": "#a7f3d0",
1075
+ "DURATION": "#c7d2fe",
1076
+ "PARTY": "#ddd6fe", "PARTY_ROLE": "#ddd6fe",
1077
+ "PERSON": "#fbcfe8",
1078
+ "JURISDICTION": "#fde68a",
1079
+ "DEFINED_TERM": "#fbcfe8",
1080
+ "LEGAL_REF": "#e5e7eb",
1081
+ }.get(e["type"], "#e5e7eb")
1082
+ label = e["type"].replace("_", " ")
1083
+ html_parts.append(
1084
+ f'<mark style="background:{color};padding:1px 2px;border-radius:2px;font-size:12px;" title="{label}">{e["text"].replace("<","&lt;").replace(">","&gt;")}</mark>'
1085
+ )
1086
+ last_end = e["end"]
1087
+ html_parts.append(text[last_end:].replace("<", "&lt;").replace(">", "&gt;"))
1088
+ highlighted = "".join(html_parts)
1089
+ return f"""
1090
+ <div style="font-family:monospace;font-size:13px;line-height:1.6;padding:16px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;max-height:600px;overflow-y:auto;white-space:pre-wrap;">
1091
+ {highlighted}
1092
+ </div>
1093
+ """
1094
+
1095
+ # ═══════════════════════════════════════════════════════════════════════
1096
+ # 12. COMPARISON UI FUNCTIONS
1097
+ # ═══════════════════════════════════════════════════════════════════════
1098
+
1099
+ def run_comparison(text_a, text_b):
1100
+ if not text_a or len(text_a.strip()) < 50:
1101
+ return "Contract A is too short", ""
1102
+ if not text_b or len(text_b.strip()) < 50:
1103
+ return "Contract B is too short", ""
1104
+ result = compare_contracts(text_a, text_b)
1105
+ return render_comparison_html(result), json.dumps(result, indent=2)
1106
+
1107
+ # ═══════════════════════════════════════════════════════════════════════
1108
+ # 13. GRADIO UI
1109
+ # ═══════════════════════════════════════════════════════════════════════
1110
+
1111
+ def process_upload(file):
1112
+ if file is None:
1113
+ return "", "No file uploaded"
1114
+ text, error = parse_document(file)
1115
+ if error:
1116
+ return "", error
1117
+ return text, "Document loaded successfully"
1118
+
1119
+ def run_analysis(text):
1120
+ if not text or len(text.strip()) < 50:
1121
+ err_html = '<p style="color:#dc2626;padding:16px;">Document too short (minimum 50 characters)</p>'
1122
+ return [err_html] * 7 + [None, None, ""]
1123
+ result, error = analyze_contract(text)
1124
+ if error:
1125
+ err_html = f'<p style="color:#dc2626;padding:16px;">{error}</p>'
1126
+ return [err_html] * 7 + [None, None, error]
1127
+
1128
+ # FIXED: per-session temp files
1129
+ session_id = uuid.uuid4().hex[:8]
1130
+ json_path = os.path.join(tempfile.gettempdir(), f"clauseguard_{session_id}.json")
1131
+ csv_path = os.path.join(tempfile.gettempdir(), f"clauseguard_{session_id}.csv")
1132
+
1133
+ with open(json_path, "w") as f:
1134
+ json.dump(result, f, indent=2, default=str)
1135
+ csv_content = export_csv(result)
1136
+ with open(csv_path, "w") as f:
1137
+ f.write(csv_content)
1138
+
1139
+ return [
1140
+ render_summary(result),
1141
+ render_clause_cards(result),
1142
+ render_entities(result),
1143
+ render_contradictions(result),
1144
+ render_document_viewer(result),
1145
+ render_obligations_html(result.get("obligations", [])),
1146
+ render_compliance_html(result.get("compliance", {})),
1147
+ json_path,
1148
+ csv_path,
1149
+ "Analysis complete",
1150
+ ]
1151
+
1152
+ def do_clear():
1153
+ return [""] * 7 + [None, None, ""]
1154
+
1155
+ # ── Example contracts ──
1156
+ SPOTIFY_TOS = """By using the Spotify Service, you agree to be bound by these Terms of Use.
1157
+
1158
+ Spotify may, in its sole discretion, modify or update these Terms of Service at any time without prior notice. Your continued use of the Service after any such changes constitutes your acceptance of the new Terms of Service.
1159
+
1160
+ In no event will Spotify be liable for any indirect, incidental, special, consequential, or punitive damages, or any loss of profits or revenues, whether incurred directly or indirectly.
1161
+
1162
+ Spotify reserves the right to remove or disable access to any User Content for any reason, without prior notice.
1163
+
1164
+ Spotify may terminate your account or suspend your access at any time, with or without cause, with or without notice, effective immediately.
1165
+
1166
+ These Terms will be governed by and construed in accordance with the laws of the State of New York.
1167
+
1168
+ Any dispute shall be finally settled by arbitration in New York County. The parties waive any right to a jury trial."""
1169
+
1170
+ RENTAL_AGREEMENT = """The Landlord reserves the right to enter the premises at any time without prior notice for inspection or any other purpose deemed necessary in their sole discretion.
1171
+
1172
+ The Landlord shall not be liable for any damage to the Tenant's personal property, whether caused by water leaks, fire, theft, or any other cause, including the Landlord's own negligence.
1173
+
1174
+ The Landlord may terminate this lease at any time with only 7 days written notice, for any reason or no reason at all.
1175
+
1176
+ Any disputes arising from this lease agreement shall be resolved exclusively in the courts of the State of California, and the Tenant waives the right to a jury trial.
1177
+
1178
+ The Landlord reserves the right to modify the terms of this lease at any time. Continued occupancy constitutes acceptance of the new terms."""
1179
+
1180
+ NDA_SAMPLE = """NON-DISCLOSURE AGREEMENT
1181
+
1182
+ This Non-Disclosure Agreement (the "Agreement") is entered into as of January 15, 2024 (the "Effective Date") by and between Acme Technologies, Inc. ("Disclosing Party") and Beta Solutions LLC ("Receiving Party").
1183
+
1184
+ 1. Governing Law. This Agreement shall be governed by and construed in accordance with the laws of the State of Delaware, without regard to its conflict of law principles.
1185
+
1186
+ 2. Term. This Agreement shall remain in effect for a period of three (3) years from the Effective Date.
1187
+
1188
+ 3. Termination. Either party may terminate this Agreement for convenience upon thirty (30) days prior written notice.
1189
+
1190
+ 4. Intellectual Property. All Confidential Information disclosed hereunder shall remain the exclusive property of the Disclosing Party. The Receiving Party hereby assigns to the Disclosing Party all right, title, and interest in any derivative works.
1191
+
1192
+ 5. Limitation of Liability. IN NO EVENT SHALL EITHER PARTY BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES.
1193
+
1194
+ 6. Indemnification. The Receiving Party shall indemnify and hold harmless the Disclosing Party from any and all claims arising from a breach of this Agreement.
1195
+
1196
+ 7. Non-Compete. During the term of this Agreement and for a period of two (2) years thereafter, the Receiving Party shall not engage in any business that competes with the Disclosing Party."""
1197
+
1198
+ COMPLEX_CONTRACT = """MASTER SERVICE AGREEMENT
1199
+
1200
+ This Master Service Agreement ("MSA") is entered into as of March 1, 2024 (the "Effective Date") by and between CloudTech Solutions, Inc., a Delaware corporation ("Provider") and Global Retail Partners LLC, a New York limited liability company ("Customer").
1201
+
1202
+ 1. SERVICES. Provider shall provide cloud hosting and data processing services as described in Exhibit A. Provider shall comply with all applicable laws including GDPR and CCPA.
1203
+
1204
+ 2. TERM AND RENEWAL. The initial term is twelve (12) months, automatically renewing for successive one (1) year periods unless terminated in accordance with Section 7.
1205
+
1206
+ 3. FEES AND PAYMENT. Customer shall pay a monthly fee of $25,000 within 30 days of invoice. Late payments incur a penalty of 1.5% per month. The total contract value is $300,000.
1207
+
1208
+ 4. LIABILITY. Provider's aggregate liability shall not exceed $1,000,000. IN NO EVENT SHALL PROVIDER BE LIABLE FOR LOST PROFITS OR CONSEQUENTIAL DAMAGES. Customer assumes all risk of data loss.
1209
+
1210
+ 5. INDEMNIFICATION. Each party shall indemnify the other for third-party claims arising from breach of this Agreement. Customer shall indemnify Provider for claims arising from Customer Data.
1211
+
1212
+ 6. INTELLECTUAL PROPERTY. Provider retains all IP rights. Customer receives a non-transferable, non-exclusive license for the term. Upon termination, Customer shall return or destroy all Provider materials within 10 business days.
1213
+
1214
+ 7. TERMINATION. Either party may terminate for convenience with 90 days notice. Provider may terminate immediately for non-payment. Upon termination, Customer shall pay all outstanding fees.
1215
+
1216
+ 8. GOVERNING LAW. This Agreement is governed by the laws of the State of Delaware. Disputes shall be resolved by binding arbitration in Wilmington, Delaware.
1217
+
1218
+ 9. FORCE MAJEURE. Neither party shall be liable for delays due to acts of God, war, terrorism, or government action.
1219
+
1220
+ 10. AUDIT RIGHTS. Customer may audit Provider's compliance annually. Provider shall provide SOC 2 Type II reports within 30 days of request.
1221
+
1222
+ 11. INSURANCE. Provider shall maintain general liability insurance of at least $5,000,000 and cyber liability insurance of at least $2,000,000.
1223
+
1224
+ 12. CONFIDENTIALITY. Both parties agree to keep Confidential Information secure for five (5) years. This obligation survives termination.
1225
+
1226
+ 13. ASSIGNMENT. Neither party may assign this Agreement without prior written consent. Any attempted assignment is void.
1227
+
1228
+ 14. THIRD PARTY BENEFICIARY. No third party shall have rights under this Agreement except as expressly provided."""
1229
+
1230
+ with gr.Blocks(
1231
+ title="ClauseGuard β€” AI Contract Analysis",
1232
+ css="""
1233
+ .gradio-container { max-width: 1600px !important; }
1234
+ """
1235
+ ) as demo:
1236
+
1237
+ gr.HTML("""
1238
+ <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 0;border-bottom:2px solid #e5e7eb;margin-bottom:16px;">
1239
+ <div>
1240
+ <h1 style="font-size:24px;font-weight:700;margin:0;color:#1f2937;">πŸ›‘οΈ ClauseGuard</h1>
1241
+ <p style="font-size:13px;color:#6b7280;margin:4px 0 0 0;">AI-Powered Legal Contract Analysis Β· 41 Clause Categories Β· Risk Scoring Β· ML NER Β· NLI Contradictions Β· Compliance Β· Obligations</p>
1242
+ </div>
1243
+ <div style="font-size:12px;color:#9ca3af;">v3.0 Β· Precision Legal AI</div>
1244
+ </div>
1245
+ """)
1246
+
1247
+ # ── Main Tabs: Analysis vs Comparison ──
1248
+ with gr.Tabs():
1249
+
1250
+ # ═══════ TAB 1: Single Contract Analysis ═══════
1251
+ with gr.Tab("πŸ“„ Single Contract Analysis"):
1252
+ with gr.Row():
1253
+ with gr.Column(scale=1):
1254
+ file_input = gr.File(
1255
+ label="πŸ“ Upload Contract (PDF/DOCX/TXT)",
1256
+ file_types=[".pdf", ".docx", ".doc", ".txt", ".md"],
1257
+ )
1258
+ load_btn = gr.Button("Load Document", variant="secondary", size="sm")
1259
+ load_status = gr.Textbox(label="Status", interactive=False, lines=1)
1260
+
1261
+ with gr.Column(scale=3):
1262
+ text_input = gr.Textbox(
1263
+ label="πŸ“„ Contract Text",
1264
+ placeholder="Paste contract text here, or upload a file above...",
1265
+ lines=14,
1266
+ max_lines=40,
1267
+ show_copy_button=True,
1268
+ )
1269
+
1270
+ with gr.Column(scale=1):
1271
+ scan_btn = gr.Button("πŸ” Analyze Contract", variant="primary", size="lg")
1272
+ clear_btn = gr.Button("Clear", variant="secondary", size="sm")
1273
+ status_msg = gr.Textbox(label="Analysis Status", interactive=False, lines=1)
1274
+
1275
+ # ── Examples ──
1276
+ with gr.Row():
1277
+ gr.Examples(
1278
+ examples=[[SPOTIFY_TOS], [RENTAL_AGREEMENT], [NDA_SAMPLE], [COMPLEX_CONTRACT]],
1279
+ inputs=[text_input],
1280
+ label="Example Contracts",
1281
+ )
1282
+
1283
+ # ── Results ──
1284
+ with gr.Row():
1285
+ with gr.Column(scale=1):
1286
+ gr.Markdown("### πŸ“Š Risk Summary")
1287
+ summary_html = gr.HTML()
1288
+
1289
+ gr.Markdown("### πŸ“₯ Export Reports")
1290
+ json_file = gr.File(label="JSON Report")
1291
+ csv_file = gr.File(label="CSV Report")
1292
+
1293
+ with gr.Column(scale=3):
1294
+ with gr.Tabs():
1295
+ with gr.Tab("πŸ“„ Document"):
1296
+ doc_html = gr.HTML(label="Document Viewer")
1297
+ with gr.Tab("⚠️ Clauses (41 Categories)"):
1298
+ clauses_html = gr.HTML(label="Detected Clauses")
1299
+ with gr.Tab("🏷️ Entities"):
1300
+ entities_html = gr.HTML(label="Named Entities")
1301
+ with gr.Tab("πŸ” Contradictions"):
1302
+ nli_html = gr.HTML(label="Contradictions & Missing Clauses")
1303
+ with gr.Tab("πŸ“‹ Obligations"):
1304
+ obligations_html = gr.HTML(label="Obligation Tracker")
1305
+ with gr.Tab("βš–οΈ Compliance"):
1306
+ compliance_html = gr.HTML(label="Compliance Checker")
1307
+
1308
+ # ═══════ TAB 2: Contract Comparison ═══════
1309
+ with gr.Tab("πŸ”€ Compare Contracts"):
1310
+ with gr.Row():
1311
+ with gr.Column(scale=1):
1312
+ comp_file_a = gr.File(
1313
+ label="πŸ“ Contract A (PDF/DOCX/TXT)",
1314
+ file_types=[".pdf", ".docx", ".doc", ".txt"],
1315
+ )
1316
+ comp_load_a = gr.Button("Load A", variant="secondary", size="sm")
1317
+ comp_status_a = gr.Textbox(label="Status A", interactive=False, lines=1)
1318
+
1319
+ with gr.Column(scale=3):
1320
+ comp_text_a = gr.Textbox(
1321
+ label="Contract A",
1322
+ placeholder="Paste contract A here...",
1323
+ lines=12,
1324
+ show_copy_button=True,
1325
+ )
1326
+
1327
+ with gr.Column(scale=1):
1328
+ comp_file_b = gr.File(
1329
+ label="πŸ“ Contract B (PDF/DOCX/TXT)",
1330
+ file_types=[".pdf", ".docx", ".doc", ".txt"],
1331
+ )
1332
+ comp_load_b = gr.Button("Load B", variant="secondary", size="sm")
1333
+ comp_status_b = gr.Textbox(label="Status B", interactive=False, lines=1)
1334
+
1335
+ with gr.Column(scale=3):
1336
+ comp_text_b = gr.Textbox(
1337
+ label="Contract B",
1338
+ placeholder="Paste contract B here...",
1339
+ lines=12,
1340
+ show_copy_button=True,
1341
+ )
1342
+
1343
+ with gr.Row():
1344
+ with gr.Column(scale=1):
1345
+ comp_btn = gr.Button("πŸ”€ Compare Contracts", variant="primary", size="lg")
1346
+ with gr.Column(scale=5):
1347
+ comp_status = gr.Textbox(label="Comparison Status", interactive=False, lines=1)
1348
+
1349
+ with gr.Row():
1350
+ with gr.Column(scale=4):
1351
+ comp_result_html = gr.HTML(label="Comparison Results")
1352
+ with gr.Column(scale=2):
1353
+ comp_json = gr.JSON(label="Raw Comparison Data")
1354
+
1355
+ # ── Events ──
1356
+ def _load_file(file):
1357
+ text, err = parse_document(file) if file else ("", "No file")
1358
+ if err and not text:
1359
+ return "", err
1360
+ return text, "Loaded successfully" if not err else err
1361
+
1362
+ load_btn.click(_load_file, inputs=[file_input], outputs=[text_input, load_status])
1363
+ comp_load_a.click(_load_file, inputs=[comp_file_a], outputs=[comp_text_a, comp_status_a])
1364
+ comp_load_b.click(_load_file, inputs=[comp_file_b], outputs=[comp_text_b, comp_status_b])
1365
+
1366
+ scan_btn.click(
1367
+ run_analysis,
1368
+ inputs=[text_input],
1369
+ outputs=[summary_html, clauses_html, entities_html, nli_html,
1370
+ doc_html, obligations_html, compliance_html,
1371
+ json_file, csv_file, status_msg]
1372
+ )
1373
+
1374
+ clear_btn.click(
1375
+ do_clear,
1376
+ outputs=[summary_html, clauses_html, entities_html, nli_html,
1377
+ doc_html, obligations_html, compliance_html,
1378
+ json_file, csv_file, status_msg]
1379
+ )
1380
+
1381
+ comp_btn.click(
1382
+ run_comparison,
1383
+ inputs=[comp_text_a, comp_text_b],
1384
+ outputs=[comp_result_html, comp_json]
1385
+ )
1386
+
1387
+ gr.HTML("""
1388
+ <div style="margin-top:24px;padding:16px 0;border-top:1px solid #e5e7eb;text-align:center;">
1389
+ <p style="font-size:11px;color:#9ca3af;">
1390
+ ⚠️ Not legal advice. For informational purposes only.
1391
+ Β· Model: <a href="https://huggingface.co/Mokshith31/legalbert-contract-clause-classification" style="color:#6b7280;">Legal-BERT + CUAD (41 classes)</a>
1392
+ Β· NER: <a href="https://huggingface.co/matterstack/legal-bert-ner" style="color:#6b7280;">Legal-BERT NER</a>
1393
+ Β· NLI: <a href="https://huggingface.co/cross-encoder/nli-deberta-v3-base" style="color:#6b7280;">DeBERTa-v3 NLI</a>
1394
+ Β· Dataset: <a href="https://huggingface.co/datasets/theatticusproject/cuad-qa" style="color:#6b7280;">CUAD</a>
1395
+ Β· <a href="https://huggingface.co/spaces/gaurv007/ClauseGuard" style="color:#6b7280;">ClauseGuard Space</a>
1396
+ </p>
1397
+ </div>
1398
+ """)
1399
+
1400
+ if __name__ == "__main__":
1401
+ demo.launch()