gaurv007 commited on
Commit
ef9dc08
·
verified ·
1 Parent(s): 76700f0

fix: upload actual compare.py content with all v4.1 fixes

Browse files
Files changed (1) hide show
  1. compare.py +333 -1
compare.py CHANGED
@@ -1 +1,333 @@
1
- file:/app/compare.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ClauseGuard — Contract Comparison Engine v3.1
3
+ ═════════════════════════════════════════════
4
+ FIXED in v3.1:
5
+ • PERF: Pre-compute all embeddings once, use matrix multiplication (was O(n²) per-pair encoding)
6
+ • FIX: Shared SentenceTransformer singleton (no duplicate model loading)
7
+ • FIX: Raised similarity thresholds to reduce false matches
8
+ """
9
+
10
+ import re
11
+ from difflib import SequenceMatcher
12
+ from collections import defaultdict
13
+ import numpy as np
14
+
15
+ # Try to load sentence-transformers for semantic comparison
16
+ _HAS_EMBEDDINGS = False
17
+ _embedder = None
18
+
19
+ try:
20
+ from sentence_transformers import SentenceTransformer
21
+ _HAS_EMBEDDINGS = True
22
+ except ImportError:
23
+ pass
24
+
25
+
26
+ def _load_embedder():
27
+ """Load shared SentenceTransformer singleton."""
28
+ global _embedder
29
+ if _HAS_EMBEDDINGS and _embedder is None:
30
+ try:
31
+ _embedder = SentenceTransformer("all-MiniLM-L6-v2")
32
+ print("[ClauseGuard] Sentence embeddings loaded for comparison")
33
+ except Exception as e:
34
+ print(f"[ClauseGuard] Embeddings not available: {e}")
35
+
36
+
37
+ def _normalize_clause(text):
38
+ """Normalize clause text for comparison."""
39
+ text = text.lower()
40
+ text = re.sub(r'[^a-z0-9\s]', ' ', text)
41
+ text = re.sub(r'\s+', ' ', text).strip()
42
+ return text
43
+
44
+
45
+ def _compute_similarity_matrix(clauses_a, clauses_b):
46
+ """
47
+ FIX v3.1: Compute similarity matrix using pre-computed embeddings + matrix multiply.
48
+ Was: O(n²) individual encode() calls per pair.
49
+ Now: O(n+m) encode calls + O(n*m) dot product (fast numpy).
50
+ """
51
+ if _embedder is not None:
52
+ try:
53
+ # Encode all clauses at once (batched)
54
+ texts_a = [c[:512] for c in clauses_a]
55
+ texts_b = [c[:512] for c in clauses_b]
56
+ emb_a = _embedder.encode(texts_a, normalize_embeddings=True, batch_size=32, show_progress_bar=False)
57
+ emb_b = _embedder.encode(texts_b, normalize_embeddings=True, batch_size=32, show_progress_bar=False)
58
+ # Cosine similarity via dot product (embeddings are L2-normalized)
59
+ sim_matrix = np.dot(emb_a, emb_b.T)
60
+ return sim_matrix, "semantic"
61
+ except Exception:
62
+ pass
63
+
64
+ # Fallback: string matching (still compute matrix)
65
+ n, m = len(clauses_a), len(clauses_b)
66
+ sim_matrix = np.zeros((n, m))
67
+ for i in range(n):
68
+ norm_a = _normalize_clause(clauses_a[i])
69
+ for j in range(m):
70
+ norm_b = _normalize_clause(clauses_b[j])
71
+ sim_matrix[i, j] = SequenceMatcher(None, norm_a, norm_b).ratio()
72
+ return sim_matrix, "lexical"
73
+
74
+
75
+ def _extract_clause_type(clause_text):
76
+ """Clause type detection with legal taxonomy."""
77
+ text_lower = clause_text.lower()
78
+ type_keywords = {
79
+ "governing law": ["govern", "law of", "jurisdiction of", "applicable law"],
80
+ "termination": ["terminat", "cancel", "expir"],
81
+ "indemnification": ["indemnif", "hold harmless", "defend and indemnify"],
82
+ "confidentiality": ["confidential", "non-disclosure", "nda", "proprietary"],
83
+ "liability": ["liability", "liable", "damages", "limitation of"],
84
+ "payment": ["payment", "fee", "price", "compensat", "invoice", "remit"],
85
+ "intellectual property": ["intellectual property", "ip rights", "copyright", "patent", "trademark"],
86
+ "warranty": ["warrant", "guarantee", "representation"],
87
+ "force majeure": ["force majeure", "act of god", "beyond control"],
88
+ "arbitration": ["arbitrat", "mediation", "dispute resolution"],
89
+ "assignment": ["assign", "transfer of rights"],
90
+ "non-compete": ["non-compete", "not compete", "competition"],
91
+ "renewal": ["renew", "extend", "automatic renewal"],
92
+ "effective date": ["effective date", "commencement"],
93
+ "insurance": ["insurance", "coverage", "policy of insurance"],
94
+ "audit": ["audit", "inspection", "examination of records"],
95
+ "data protection": ["data protection", "privacy", "personal data", "gdpr", "ccpa"],
96
+ "notice": ["notice", "notification", "written notice"],
97
+ }
98
+ for ctype, keywords in type_keywords.items():
99
+ if any(kw in text_lower for kw in keywords):
100
+ return ctype
101
+ return "general"
102
+
103
+
104
+ def compare_contracts(text_a, text_b, clauses_a=None, clauses_b=None):
105
+ """Compare two contracts with semantic similarity."""
106
+ if not text_a or not text_b:
107
+ return {"error": "Both contracts required"}
108
+
109
+ _load_embedder()
110
+
111
+ if clauses_a is None:
112
+ clauses_a = _split_clauses(text_a)
113
+ if clauses_b is None:
114
+ clauses_b = _split_clauses(text_b)
115
+
116
+ # Detect contract types and flag cross-domain comparisons
117
+ _CONTRACT_TYPE_KEYWORDS = {
118
+ "employment": ["employee", "employer", "salary", "compensation", "benefits", "vacation", "severance", "at-will"],
119
+ "lease": ["landlord", "tenant", "rent", "premises", "lease", "occupancy", "security deposit", "eviction"],
120
+ "service": ["service provider", "customer", "SLA", "deliverables", "statement of work", "SOW"],
121
+ "nda": ["confidential", "non-disclosure", "disclosing party", "receiving party"],
122
+ "saas": ["subscription", "SaaS", "cloud", "uptime", "API", "data processing"],
123
+ "purchase": ["buyer", "seller", "purchase order", "goods", "shipment", "delivery"],
124
+ }
125
+
126
+ def _detect_contract_type(text):
127
+ text_lower = text.lower()
128
+ scores = {}
129
+ for ctype, keywords in _CONTRACT_TYPE_KEYWORDS.items():
130
+ scores[ctype] = sum(1 for kw in keywords if kw.lower() in text_lower)
131
+ best = max(scores, key=scores.get)
132
+ return best if scores[best] >= 2 else "general"
133
+
134
+ type_a = _detect_contract_type(text_a)
135
+ type_b = _detect_contract_type(text_b)
136
+ is_cross_domain = type_a != type_b and type_a != "general" and type_b != "general"
137
+
138
+ # Build clause type maps
139
+ type_map_a = defaultdict(list)
140
+ type_map_b = defaultdict(list)
141
+ for c in clauses_a:
142
+ type_map_a[_extract_clause_type(c)].append(c)
143
+ for c in clauses_b:
144
+ type_map_b[_extract_clause_type(c)].append(c)
145
+
146
+ # FIX v3.1: Compute similarity matrix once (O(n+m) encoding + O(n*m) dot product)
147
+ if clauses_a and clauses_b:
148
+ sim_matrix, method_type = _compute_similarity_matrix(clauses_a, clauses_b)
149
+ else:
150
+ sim_matrix = np.zeros((0, 0))
151
+ method_type = "none"
152
+
153
+ # Find matches using the pre-computed matrix
154
+ matched_a = set()
155
+ matched_b = set()
156
+ modified = []
157
+
158
+ SIMILARITY_THRESHOLD = 0.75
159
+ MODIFIED_THRESHOLD = 0.55
160
+
161
+ for i in range(len(clauses_a)):
162
+ if len(clauses_b) == 0:
163
+ break
164
+ # Find best match for clause i in A
165
+ row = sim_matrix[i]
166
+ # Mask already-matched B clauses
167
+ available = np.ones(len(clauses_b), dtype=bool)
168
+ for j in matched_b:
169
+ available[j] = False
170
+ if not available.any():
171
+ break
172
+ masked_row = np.where(available, row, -1.0)
173
+ best_j = int(np.argmax(masked_row))
174
+ best_sim = masked_row[best_j]
175
+
176
+ if best_sim >= SIMILARITY_THRESHOLD:
177
+ matched_a.add(i)
178
+ matched_b.add(best_j)
179
+ if best_sim < 0.95:
180
+ modified.append({
181
+ "type": "modified",
182
+ "similarity": round(float(best_sim), 3),
183
+ "clause_a": clauses_a[i][:200],
184
+ "clause_b": clauses_b[best_j][:200],
185
+ "clause_type": _extract_clause_type(clauses_a[i]),
186
+ })
187
+ elif best_sim >= MODIFIED_THRESHOLD:
188
+ matched_a.add(i)
189
+ matched_b.add(best_j)
190
+ modified.append({
191
+ "type": "partial",
192
+ "similarity": round(float(best_sim), 3),
193
+ "clause_a": clauses_a[i][:200],
194
+ "clause_b": clauses_b[best_j][:200],
195
+ "clause_type": _extract_clause_type(clauses_a[i]),
196
+ })
197
+
198
+ removed = [clauses_a[i] for i in range(len(clauses_a)) if i not in matched_a]
199
+ added = [clauses_b[j] for j in range(len(clauses_b)) if j not in matched_b]
200
+
201
+ # Compute alignment score
202
+ total_pairs = max(len(clauses_a), len(clauses_b))
203
+ alignment = len(matched_a) / total_pairs if total_pairs > 0 else 0.0
204
+
205
+ # Risk delta
206
+ risk_keywords = ["unlimited", "unilateral", "waive", "arbitration", "indemnif",
207
+ "not liable", "no warranty", "sole discretion", "terminate",
208
+ "non-compete", "liquidated damages", "uncapped"]
209
+ risk_a = sum(1 for kw in risk_keywords if kw in text_a.lower())
210
+ risk_b = sum(1 for kw in risk_keywords if kw in text_b.lower())
211
+
212
+ if risk_a > risk_b + 2:
213
+ risk_delta = "Contract A is significantly riskier"
214
+ risk_winner = "B"
215
+ elif risk_b > risk_a + 2:
216
+ risk_delta = "Contract B is significantly riskier"
217
+ risk_winner = "A"
218
+ elif risk_a > risk_b:
219
+ risk_delta = "Contract A is slightly riskier"
220
+ risk_winner = "B"
221
+ elif risk_b > risk_a:
222
+ risk_delta = "Contract B is slightly riskier"
223
+ risk_winner = "A"
224
+ else:
225
+ risk_delta = "Similar risk profiles"
226
+ risk_winner = "tie"
227
+
228
+ if is_cross_domain:
229
+ risk_delta = f"Cross-domain comparison ({type_a} vs {type_b}) — risk delta not meaningful across different contract types"
230
+ risk_winner = "cross-domain"
231
+
232
+ comparison_method = f"semantic (sentence embeddings)" if method_type == "semantic" else "lexical (string matching)"
233
+
234
+ return {
235
+ "alignment_score": round(alignment, 3),
236
+ "contract_a_clauses": len(clauses_a),
237
+ "contract_b_clauses": len(clauses_b),
238
+ "contract_a_type": type_a,
239
+ "contract_b_type": type_b,
240
+ "is_cross_domain": is_cross_domain,
241
+ "added_clauses": [{"text": c[:200], "type": _extract_clause_type(c)} for c in added[:50]],
242
+ "removed_clauses": [{"text": c[:200], "type": _extract_clause_type(c)} for c in removed[:50]],
243
+ "modified_clauses": modified[:50],
244
+ "risk_delta": risk_delta,
245
+ "risk_winner": risk_winner,
246
+ "comparison_method": comparison_method,
247
+ "type_map_a": {k: len(v) for k, v in type_map_a.items()},
248
+ "type_map_b": {k: len(v) for k, v in type_map_b.items()},
249
+ }
250
+
251
+
252
+ def _split_clauses(text):
253
+ """Split text into clauses."""
254
+ text = re.sub(r'\n{3,}', '\n\n', text.strip())
255
+ section_splits = re.split(
256
+ r'(?:\n\n)(?=\d+[.)]\s|\([a-z]\)\s|(?:Section|Article|Clause)\s+\d+)',
257
+ text
258
+ )
259
+ if len(section_splits) >= 3:
260
+ return [p.strip() for p in section_splits if len(p.strip()) > 30]
261
+ parts = re.split(
262
+ r'(?<=[.!?])\s+(?=[A-Z0-9(])|(?:\n\n)',
263
+ text
264
+ )
265
+ return [p.strip() for p in parts if len(p.strip()) > 30]
266
+
267
+
268
+ def render_comparison_html(result):
269
+ """Render comparison results as HTML for Gradio."""
270
+ if "error" in result:
271
+ return f'<p style="color:#dc2626;">{result["error"]}</p>'
272
+
273
+ method = result.get("comparison_method", "unknown")
274
+ method_badge = f'<div style="font-size:10px;color:#6b7280;text-align:center;margin-bottom:12px;">Comparison method: {method}</div>'
275
+
276
+ html = f'''
277
+ <div style="font-family:system-ui,sans-serif;">
278
+ {method_badge}
279
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px;">
280
+ <div style="padding:12px;border-radius:8px;background:#eff6ff;border:1px solid #bfdbfe;text-align:center;">
281
+ <div style="font-size:24px;font-weight:700;color:#1d4ed8;">{result["contract_a_clauses"]}</div>
282
+ <div style="font-size:12px;color:#3b82f6;">Clauses in Contract A</div>
283
+ </div>
284
+ <div style="padding:12px;border-radius:8px;background:#fefce8;border:1px solid #fde68a;text-align:center;">
285
+ <div style="font-size:24px;font-weight:700;color:#a16207;">{result["contract_b_clauses"]}</div>
286
+ <div style="font-size:12px;color:#ca8a04;">Clauses in Contract B</div>
287
+ </div>
288
+ </div>
289
+
290
+ <div style="padding:12px;border-radius:8px;background:#f9fafb;border:1px solid #e5e7eb;margin-bottom:16px;text-align:center;">
291
+ <div style="font-size:28px;font-weight:700;color:#374151;">{result["alignment_score"]*100:.1f}%</div>
292
+ <div style="font-size:12px;color:#6b7280;">Alignment Score</div>
293
+ </div>
294
+
295
+ <div style="padding:12px;border-radius:8px;background:{
296
+ "#fef2f2" if result["risk_winner"] != "tie" else "#f0fdf4"
297
+ };border:1px solid {
298
+ "#fecaca" if result["risk_winner"] != "tie" else "#bbf7d0"
299
+ };margin-bottom:16px;text-align:center;">
300
+ <span style="font-size:14px;font-weight:600;color:{
301
+ "#dc2626" if result["risk_winner"] != "tie" else "#16a34a"
302
+ };">⚖️ {result["risk_delta"]}</span>
303
+ </div>
304
+ '''
305
+
306
+ if result["modified_clauses"]:
307
+ html += '<div style="margin-bottom:16px;"><h3 style="font-size:14px;color:#374151;margin-bottom:8px;">📝 Modified Clauses</h3>'
308
+ for m in result["modified_clauses"][:20]:
309
+ html += f'''
310
+ <div style="border:1px solid #e5e7eb;border-radius:6px;padding:10px;margin-bottom:8px;">
311
+ <div style="font-size:11px;color:#6b7280;margin-bottom:4px;">{m["clause_type"].upper()} · Similarity: {m["similarity"]*100:.0f}%</div>
312
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
313
+ <div style="background:#fef2f2;padding:6px;border-radius:4px;font-size:12px;color:#991b1b;">{m["clause_a"][:150]}...</div>
314
+ <div style="background:#f0fdf4;padding:6px;border-radius:4px;font-size:12px;color:#166534;">{m["clause_b"][:150]}...</div>
315
+ </div>
316
+ </div>
317
+ '''
318
+ html += '</div>'
319
+
320
+ if result["added_clauses"]:
321
+ html += '<div style="margin-bottom:16px;"><h3 style="font-size:14px;color:#374151;margin-bottom:8px;">➕ Added in Contract B</h3>'
322
+ for a in result["added_clauses"][:15]:
323
+ html += f'<div style="background:#f0fdf4;padding:8px;border-radius:4px;font-size:12px;color:#166534;margin-bottom:4px;border-left:3px solid #22c55e;"><b>{a["type"].upper()}</b> · {a["text"][:150]}...</div>'
324
+ html += '</div>'
325
+
326
+ if result["removed_clauses"]:
327
+ html += '<div style="margin-bottom:16px;"><h3 style="font-size:14px;color:#374151;margin-bottom:8px;">➖ Removed from Contract A</h3>'
328
+ for r in result["removed_clauses"][:15]:
329
+ html += f'<div style="background:#fef2f2;padding:8px;border-radius:4px;font-size:12px;color:#991b1b;margin-bottom:4px;border-left:3px solid #ef4444;"><b>{r["type"].upper()}</b> · {r["text"][:150]}...</div>'
330
+ html += '</div>'
331
+
332
+ html += '</div>'
333
+ return html