gaurv007 commited on
Commit
1a6e4a8
·
verified ·
1 Parent(s): b3fb853

fix(compare.py): v3.1 — O(n²)→O(n+m) similarity via matrix multiplication

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