File size: 13,907 Bytes
e696558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e0514
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e696558
 
 
 
 
 
 
 
 
 
 
 
 
c6e0514
 
 
e696558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e0514
 
 
 
 
e696558
 
 
 
 
 
c6e0514
 
 
e696558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
"""
ClauseGuard β€” Contract Comparison Engine v3.0
═════════════════════════════════════════════
FIXED in v3.0:
  β€’ Semantic similarity using sentence embeddings (when available)
  β€’ Better clause type detection with legal taxonomy
  β€’ Improved diff visualization
  β€’ Fallback to SequenceMatcher when embeddings unavailable
"""

import re
from difflib import SequenceMatcher
from collections import defaultdict

# Try to load sentence-transformers for semantic comparison
_HAS_EMBEDDINGS = False
_embedder = None

try:
    from sentence_transformers import SentenceTransformer, util
    _HAS_EMBEDDINGS = True
except ImportError:
    pass


def _load_embedder():
    global _embedder
    if _HAS_EMBEDDINGS and _embedder is None:
        try:
            _embedder = SentenceTransformer("all-MiniLM-L6-v2")
            print("[ClauseGuard] Sentence embeddings loaded for comparison")
        except Exception as e:
            print(f"[ClauseGuard] Embeddings not available: {e}")


def _normalize_clause(text):
    """Normalize clause text for comparison."""
    text = text.lower()
    text = re.sub(r'[^a-z0-9\s]', ' ', text)
    text = re.sub(r'\s+', ' ', text).strip()
    return text


def _clause_similarity(a, b):
    """Compute similarity using semantic embeddings or string matching."""
    if _embedder is not None:
        try:
            emb_a = _embedder.encode(a[:512], convert_to_tensor=True)
            emb_b = _embedder.encode(b[:512], convert_to_tensor=True)
            sim = util.cos_sim(emb_a, emb_b).item()
            return max(0, min(1, sim))
        except Exception:
            pass
    # Fallback to string matching
    return SequenceMatcher(None, _normalize_clause(a), _normalize_clause(b)).ratio()


def _extract_clause_type(clause_text):
    """Clause type detection with legal taxonomy."""
    text_lower = clause_text.lower()
    type_keywords = {
        "governing law": ["govern", "law of", "jurisdiction of", "applicable law"],
        "termination": ["terminat", "cancel", "expir"],
        "indemnification": ["indemnif", "hold harmless", "defend and indemnify"],
        "confidentiality": ["confidential", "non-disclosure", "nda", "proprietary"],
        "liability": ["liability", "liable", "damages", "limitation of"],
        "payment": ["payment", "fee", "price", "compensat", "invoice", "remit"],
        "intellectual property": ["intellectual property", "ip rights", "copyright", "patent", "trademark"],
        "warranty": ["warrant", "guarantee", "representation"],
        "force majeure": ["force majeure", "act of god", "beyond control"],
        "arbitration": ["arbitrat", "mediation", "dispute resolution"],
        "assignment": ["assign", "transfer of rights"],
        "non-compete": ["non-compete", "not compete", "competition"],
        "renewal": ["renew", "extend", "automatic renewal"],
        "effective date": ["effective date", "commencement"],
        "insurance": ["insurance", "coverage", "policy of insurance"],
        "audit": ["audit", "inspection", "examination of records"],
        "data protection": ["data protection", "privacy", "personal data", "gdpr", "ccpa"],
        "notice": ["notice", "notification", "written notice"],
    }
    for ctype, keywords in type_keywords.items():
        if any(kw in text_lower for kw in keywords):
            return ctype
    return "general"


def compare_contracts(text_a, text_b, clauses_a=None, clauses_b=None):
    """Compare two contracts with semantic similarity."""
    if not text_a or not text_b:
        return {"error": "Both contracts required"}

    # Try to load embedder
    _load_embedder()

    # Split into clauses if not provided
    if clauses_a is None:
        clauses_a = _split_clauses(text_a)
    if clauses_b is None:
        clauses_b = _split_clauses(text_b)

    # Fix 9: Detect contract types and flag cross-domain comparisons
    _CONTRACT_TYPE_KEYWORDS = {
        "employment": ["employee", "employer", "salary", "compensation", "benefits", "vacation", "severance", "at-will"],
        "lease": ["landlord", "tenant", "rent", "premises", "lease", "occupancy", "security deposit", "eviction"],
        "service": ["service provider", "customer", "SLA", "deliverables", "statement of work", "SOW"],
        "nda": ["confidential", "non-disclosure", "disclosing party", "receiving party"],
        "saas": ["subscription", "SaaS", "cloud", "uptime", "API", "data processing"],
        "purchase": ["buyer", "seller", "purchase order", "goods", "shipment", "delivery"],
    }

    def _detect_contract_type(text):
        text_lower = text.lower()
        scores = {}
        for ctype, keywords in _CONTRACT_TYPE_KEYWORDS.items():
            scores[ctype] = sum(1 for kw in keywords if kw.lower() in text_lower)
        best = max(scores, key=scores.get)
        return best if scores[best] >= 2 else "general"

    type_a = _detect_contract_type(text_a)
    type_b = _detect_contract_type(text_b)
    is_cross_domain = type_a != type_b and type_a != "general" and type_b != "general"

    # Build clause type maps
    type_map_a = defaultdict(list)
    type_map_b = defaultdict(list)
    for c in clauses_a:
        type_map_a[_extract_clause_type(c)].append(c)
    for c in clauses_b:
        type_map_b[_extract_clause_type(c)].append(c)

    # Find matches
    matched_a = set()
    matched_b = set()
    modified = []

    # Fix 10: Raise thresholds to reject false "modified" matches
    SIMILARITY_THRESHOLD = 0.75   # was 0.70 β€” too many false matches
    MODIFIED_THRESHOLD = 0.55     # was 0.40 β€” "Good Reason" β‰  "Force Majeure"

    for i, ca in enumerate(clauses_a):
        best_sim = 0
        best_j = -1
        for j, cb in enumerate(clauses_b):
            if j in matched_b:
                continue
            sim = _clause_similarity(ca, cb)
            if sim > best_sim:
                best_sim = sim
                best_j = j

        if best_sim >= SIMILARITY_THRESHOLD:
            matched_a.add(i)
            matched_b.add(best_j)
            if best_sim < 0.95:
                modified.append({
                    "type": "modified",
                    "similarity": round(best_sim, 3),
                    "clause_a": ca[:200],
                    "clause_b": clauses_b[best_j][:200],
                    "clause_type": _extract_clause_type(ca),
                })
        elif best_sim >= MODIFIED_THRESHOLD:
            matched_a.add(i)
            if best_j >= 0:
                matched_b.add(best_j)
            modified.append({
                "type": "partial",
                "similarity": round(best_sim, 3),
                "clause_a": ca[:200],
                "clause_b": clauses_b[best_j][:200] if best_j >= 0 else "",
                "clause_type": _extract_clause_type(ca),
            })

    removed = [clauses_a[i] for i in range(len(clauses_a)) if i not in matched_a]
    added = [clauses_b[j] for j in range(len(clauses_b)) if j not in matched_b]

    # Compute alignment score
    total_pairs = max(len(clauses_a), len(clauses_b))
    if total_pairs > 0:
        alignment = len(matched_a) / total_pairs
    else:
        alignment = 0.0

    # Risk delta: compare risk keywords with context
    risk_keywords = ["unlimited", "unilateral", "waive", "arbitration", "indemnif",
                     "not liable", "no warranty", "sole discretion", "terminate",
                     "non-compete", "liquidated damages", "uncapped"]
    risk_a = sum(1 for kw in risk_keywords if kw in text_a.lower())
    risk_b = sum(1 for kw in risk_keywords if kw in text_b.lower())

    if risk_a > risk_b + 2:
        risk_delta = "Contract A is significantly riskier"
        risk_winner = "B"
    elif risk_b > risk_a + 2:
        risk_delta = "Contract B is significantly riskier"
        risk_winner = "A"
    elif risk_a > risk_b:
        risk_delta = "Contract A is slightly riskier"
        risk_winner = "B"
    elif risk_b > risk_a:
        risk_delta = "Contract B is slightly riskier"
        risk_winner = "A"
    else:
        risk_delta = "Similar risk profiles"
        risk_winner = "tie"

    # Fix 9: Cross-domain warning
    if is_cross_domain:
        risk_delta = f"Cross-domain comparison ({type_a} vs {type_b}) β€” risk delta not meaningful across different contract types"
        risk_winner = "cross-domain"

    comparison_method = "semantic (sentence embeddings)" if _embedder is not None else "lexical (string matching)"

    return {
        "alignment_score": round(alignment, 3),
        "contract_a_clauses": len(clauses_a),
        "contract_b_clauses": len(clauses_b),
        "contract_a_type": type_a,
        "contract_b_type": type_b,
        "is_cross_domain": is_cross_domain,
        "added_clauses": [{"text": c[:200], "type": _extract_clause_type(c)} for c in added[:50]],
        "removed_clauses": [{"text": c[:200], "type": _extract_clause_type(c)} for c in removed[:50]],
        "modified_clauses": modified[:50],
        "risk_delta": risk_delta,
        "risk_winner": risk_winner,
        "comparison_method": comparison_method,
        "type_map_a": {k: len(v) for k, v in type_map_a.items()},
        "type_map_b": {k: len(v) for k, v in type_map_b.items()},
    }


def _split_clauses(text):
    """Split text into clauses."""
    text = re.sub(r'\n{3,}', '\n\n', text.strip())
    # Try section-based splitting first
    section_splits = re.split(
        r'(?:\n\n)(?=\d+[.)]\s|\([a-z]\)\s|(?:Section|Article|Clause)\s+\d+)',
        text
    )
    if len(section_splits) >= 3:
        return [p.strip() for p in section_splits if len(p.strip()) > 30]
    # Fallback to paragraph/sentence splitting
    parts = re.split(
        r'(?<=[.!?])\s+(?=[A-Z0-9(])|(?:\n\n)',
        text
    )
    return [p.strip() for p in parts if len(p.strip()) > 30]


def render_comparison_html(result):
    """Render comparison results as HTML for Gradio."""
    if "error" in result:
        return f'<p style="color:#dc2626;">{result["error"]}</p>'

    method = result.get("comparison_method", "unknown")
    method_badge = f'<div style="font-size:10px;color:#6b7280;text-align:center;margin-bottom:12px;">Comparison method: {method}</div>'

    html = f'''
    <div style="font-family:system-ui,sans-serif;">
      {method_badge}
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px;">
        <div style="padding:12px;border-radius:8px;background:#eff6ff;border:1px solid #bfdbfe;text-align:center;">
          <div style="font-size:24px;font-weight:700;color:#1d4ed8;">{result["contract_a_clauses"]}</div>
          <div style="font-size:12px;color:#3b82f6;">Clauses in Contract A</div>
        </div>
        <div style="padding:12px;border-radius:8px;background:#fefce8;border:1px solid #fde68a;text-align:center;">
          <div style="font-size:24px;font-weight:700;color:#a16207;">{result["contract_b_clauses"]}</div>
          <div style="font-size:12px;color:#ca8a04;">Clauses in Contract B</div>
        </div>
      </div>

      <div style="padding:12px;border-radius:8px;background:#f9fafb;border:1px solid #e5e7eb;margin-bottom:16px;text-align:center;">
        <div style="font-size:28px;font-weight:700;color:#374151;">{result["alignment_score"]*100:.1f}%</div>
        <div style="font-size:12px;color:#6b7280;">Alignment Score</div>
      </div>

      <div style="padding:12px;border-radius:8px;background:{
          "#fef2f2" if result["risk_winner"] != "tie" else "#f0fdf4"
      };border:1px solid {
          "#fecaca" if result["risk_winner"] != "tie" else "#bbf7d0"
      };margin-bottom:16px;text-align:center;">
        <span style="font-size:14px;font-weight:600;color:{
            "#dc2626" if result["risk_winner"] != "tie" else "#16a34a"
        };">βš–οΈ {result["risk_delta"]}</span>
      </div>
    '''

    # Modified clauses
    if result["modified_clauses"]:
        html += '<div style="margin-bottom:16px;"><h3 style="font-size:14px;color:#374151;margin-bottom:8px;">πŸ“ Modified Clauses</h3>'
        for m in result["modified_clauses"][:20]:
            html += f'''
            <div style="border:1px solid #e5e7eb;border-radius:6px;padding:10px;margin-bottom:8px;">
              <div style="font-size:11px;color:#6b7280;margin-bottom:4px;">{m["clause_type"].upper()} Β· Similarity: {m["similarity"]*100:.0f}%</div>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                <div style="background:#fef2f2;padding:6px;border-radius:4px;font-size:12px;color:#991b1b;">{m["clause_a"][:150]}...</div>
                <div style="background:#f0fdf4;padding:6px;border-radius:4px;font-size:12px;color:#166534;">{m["clause_b"][:150]}...</div>
              </div>
            </div>
            '''
        html += '</div>'

    # Added clauses
    if result["added_clauses"]:
        html += '<div style="margin-bottom:16px;"><h3 style="font-size:14px;color:#374151;margin-bottom:8px;">βž• Added in Contract B</h3>'
        for a in result["added_clauses"][:15]:
            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>'
        html += '</div>'

    # Removed clauses
    if result["removed_clauses"]:
        html += '<div style="margin-bottom:16px;"><h3 style="font-size:14px;color:#374151;margin-bottom:8px;">βž– Removed from Contract A</h3>'
        for r in result["removed_clauses"][:15]:
            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>'
        html += '</div>'

    html += '</div>'
    return html