Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,37 +1,322 @@
|
|
| 1 |
"""
|
| 2 |
-
ClauseGuard β
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
import
|
| 7 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
-
# ββ
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
|
|
|
| 14 |
try:
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
"
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
}
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
"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"],
|
| 36 |
"Unilateral termination": [r"terminat.*at any time", r"suspend.*account.*without", r"we may (terminat|suspend|discontinu)", r"right to (terminat|suspend)"],
|
| 37 |
"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)"],
|
|
@@ -40,115 +325,498 @@ PATTERNS = {
|
|
| 40 |
"Choice of law": [r"governed by.*laws? of", r"shall be governed", r"laws of the state of"],
|
| 41 |
"Jurisdiction": [r"exclusive jurisdiction", r"courts? of.*(california|delaware|new york|ireland|england)", r"submit to.*jurisdiction"],
|
| 42 |
"Arbitration": [r"arbitrat", r"binding arbitration", r"waive.*right.*court", r"class action waiver"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
}
|
| 44 |
|
| 45 |
-
def
|
| 46 |
-
"""Classify using the trained Legal-BERT model."""
|
| 47 |
-
if not ml_pipeline:
|
| 48 |
-
return classify_regex(text)
|
| 49 |
-
try:
|
| 50 |
-
preds = ml_pipeline(text, truncation=True, max_length=512)
|
| 51 |
-
results = []
|
| 52 |
-
for p in preds[0] if isinstance(preds[0], list) else preds:
|
| 53 |
-
if p["score"] > 0.5 and p["label"] in LABELS:
|
| 54 |
-
sev, desc = LABELS[p["label"]]
|
| 55 |
-
results.append({"name": p["label"], "severity": sev, "desc": desc, "confidence": round(p["score"], 2)})
|
| 56 |
-
return results
|
| 57 |
-
except Exception:
|
| 58 |
-
return classify_regex(text)
|
| 59 |
-
|
| 60 |
-
def classify_regex(text):
|
| 61 |
-
"""Fallback regex classifier."""
|
| 62 |
-
results = []
|
| 63 |
text_lower = text.lower()
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
break
|
| 70 |
return results
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
if not text or len(text.strip()) < 50:
|
| 79 |
-
return
|
| 80 |
|
| 81 |
clauses = split_clauses(text)
|
| 82 |
if not clauses:
|
| 83 |
-
return
|
| 84 |
-
|
| 85 |
-
flagged = []
|
| 86 |
-
sev_counts = {"HIGH": 0, "MEDIUM": 0, "LOW": 0}
|
| 87 |
|
|
|
|
|
|
|
| 88 |
for clause in clauses:
|
| 89 |
-
|
| 90 |
-
if
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
#
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
</div>
|
| 114 |
-
<span style="font-size:13px;font-weight:500;padding:2px 10px;border-radius:4px;{
|
| 115 |
-
'background:#fef2f2;color:#b91c1c;' if grade in ('F','D') else
|
| 116 |
-
'background:#fffbeb;color:#a16207;' if grade == 'C' else
|
| 117 |
-
'background:#f0fdf4;color:#15803d;'
|
| 118 |
-
}">Grade {grade}</span>
|
| 119 |
</div>
|
| 120 |
-
|
| 121 |
-
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
for item in flagged:
|
| 127 |
-
max_sev = max(item["hits"], key=lambda h: {"HIGH":3,"MEDIUM":2,"LOW":1}[h["severity"]])["severity"]
|
| 128 |
-
border = {"HIGH":"#fca5a5","MEDIUM":"#fcd34d","LOW":"#93c5fd"}[max_sev]
|
| 129 |
-
|
| 130 |
-
tags = ""
|
| 131 |
-
for h in item["hits"]:
|
| 132 |
-
ts = {"HIGH":"background:#fef2f2;color:#b91c1c;border:1px solid #fecaca;",
|
| 133 |
-
"MEDIUM":"background:#fffbeb;color:#a16207;border:1px solid #fde68a;",
|
| 134 |
-
"LOW":"background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;"}[h["severity"]]
|
| 135 |
-
conf = f' ({h["confidence"]})' if h.get("confidence") and ml_pipeline else ""
|
| 136 |
-
tags += f'<span style="{ts}font-size:11px;font-weight:500;padding:1px 8px;border-radius:3px;margin-right:4px;">{h["name"]}{conf}</span>'
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
|
|
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
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.
|
| 154 |
|
|
@@ -160,39 +828,140 @@ Spotify may terminate your account or suspend your access at any time, with or w
|
|
| 160 |
|
| 161 |
These Terms will be governed by and construed in accordance with the laws of the State of New York.
|
| 162 |
|
| 163 |
-
Any dispute shall be finally settled by arbitration in New York County."""
|
| 164 |
|
| 165 |
-
|
| 166 |
|
| 167 |
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.
|
| 168 |
|
| 169 |
The Landlord may terminate this lease at any time with only 7 days written notice, for any reason or no reason at all.
|
| 170 |
|
| 171 |
-
Any disputes arising from this lease agreement shall be resolved exclusively in the courts of the
|
| 172 |
|
| 173 |
The Landlord reserves the right to modify the terms of this lease at any time. Continued occupancy constitutes acceptance of the new terms."""
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
with
|
| 178 |
-
gr.HTML('<div style="font-family:system-ui,sans-serif;padding:16px 0;"><h1 style="font-size:20px;font-weight:600;margin:0;">ClauseGuard</h1><p style="font-size:13px;color:#a1a1aa;margin-top:2px;">Paste a Terms of Service, contract, or lease. Get a risk breakdown.</p></div>')
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
with gr.Row():
|
| 181 |
with gr.Column(scale=1):
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
with gr.Column(scale=1):
|
| 189 |
-
|
| 190 |
-
|
|
|
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
if __name__ == "__main__":
|
| 198 |
demo.launch()
|
|
|
|
| 1 |
"""
|
| 2 |
+
ClauseGuard β World's Best Legal Contract Analysis Tool
|
| 3 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
+
Features:
|
| 5 |
+
β’ 41 CUAD clause categories via fine-tuned Legal-BERT
|
| 6 |
+
β’ 4-tier risk scoring (Critical / High / Medium / Low)
|
| 7 |
+
β’ Legal NER: parties, dates, monetary values, jurisdictions, defined terms
|
| 8 |
+
β’ NLI contradiction & missing-clause detection
|
| 9 |
+
β’ PDF / DOCX / TXT parsing
|
| 10 |
+
β’ Professional 3-panel Gradio UI
|
| 11 |
+
β’ JSON & CSV export
|
| 12 |
+
|
| 13 |
+
Models:
|
| 14 |
+
β’ Clause classifier: Mokshith31/legalbert-contract-clause-classification
|
| 15 |
+
(LoRA adapter on nlpaueb/legal-bert-base-uncased, 41 CUAD classes)
|
| 16 |
"""
|
| 17 |
|
| 18 |
+
import os
|
| 19 |
import re
|
| 20 |
+
import json
|
| 21 |
+
import csv
|
| 22 |
+
import io
|
| 23 |
+
import textwrap
|
| 24 |
+
from collections import defaultdict
|
| 25 |
+
from datetime import datetime
|
| 26 |
+
|
| 27 |
+
import gradio as gr
|
| 28 |
import numpy as np
|
| 29 |
|
| 30 |
+
# ββ Document parsers (soft-fail) ββββββββββββββββββββββββββββββββββββ
|
| 31 |
+
try:
|
| 32 |
+
import pdfplumber
|
| 33 |
+
_HAS_PDF = True
|
| 34 |
+
except Exception:
|
| 35 |
+
_HAS_PDF = False
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
from docx import Document as DocxDocument
|
| 39 |
+
_HAS_DOCX = True
|
| 40 |
+
except Exception:
|
| 41 |
+
_HAS_DOCX = False
|
| 42 |
|
| 43 |
+
# ββ PyTorch / Transformers (soft-fail) ββββββββββββββββββββββββββββββββ
|
| 44 |
try:
|
| 45 |
+
import torch
|
| 46 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 47 |
+
from peft import PeftModel
|
| 48 |
+
_HAS_TORCH = True
|
| 49 |
+
except Exception:
|
| 50 |
+
_HAS_TORCH = False
|
| 51 |
+
|
| 52 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 53 |
+
# 1. CONFIGURATION
|
| 54 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 55 |
+
|
| 56 |
+
CUAD_LABELS = [
|
| 57 |
+
"Document Name", "Parties", "Agreement Date", "Effective Date",
|
| 58 |
+
"Expiration Date", "Renewal Term", "Governing Law", "Most Favored Nation",
|
| 59 |
+
"Non-Compete", "Exclusivity", "No-Solicit of Customers",
|
| 60 |
+
"No-Solicit of Employees", "Non-Disparagement",
|
| 61 |
+
"Termination for Convenience", "ROFR/ROFO/ROFN", "Change of Control",
|
| 62 |
+
"Anti-Assignment", "Revenue/Profit Sharing", "Price Restriction",
|
| 63 |
+
"Minimum Commitment", "Volume Restriction", "IP Ownership Assignment",
|
| 64 |
+
"Joint IP Ownership", "License Grant", "Non-Transferable License",
|
| 65 |
+
"Affiliate License-Licensor", "Affiliate License-Licensee",
|
| 66 |
+
"Unlimited/All-You-Can-Eat License", "Irrevocable or Perpetual License",
|
| 67 |
+
"Source Code Escrow", "Post-Termination Services", "Audit Rights",
|
| 68 |
+
"Uncapped Liability", "Cap on Liability", "Liquidated Damages",
|
| 69 |
+
"Warranty Duration", "Insurance", "Covenant Not to Sue",
|
| 70 |
+
"Third Party Beneficiary", "Other"
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
# Original 8 unfair-clause labels (backward-compat + consumer contracts)
|
| 74 |
+
_UNFAIR_LABELS = [
|
| 75 |
+
"Limitation of liability", "Unilateral termination", "Unilateral change",
|
| 76 |
+
"Content removal", "Contract by using", "Choice of law",
|
| 77 |
+
"Jurisdiction", "Arbitration"
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
_ALL_LABELS = CUAD_LABELS + _UNFAIR_LABELS
|
| 81 |
+
|
| 82 |
+
RISK_MAP = {
|
| 83 |
+
# Critical
|
| 84 |
+
"Uncapped Liability": "CRITICAL",
|
| 85 |
+
"Arbitration": "CRITICAL",
|
| 86 |
+
"IP Ownership Assignment": "CRITICAL",
|
| 87 |
+
"Termination for Convenience": "CRITICAL",
|
| 88 |
+
"Limitation of liability": "CRITICAL",
|
| 89 |
+
"Unilateral termination": "CRITICAL",
|
| 90 |
+
# High
|
| 91 |
+
"Non-Compete": "HIGH",
|
| 92 |
+
"Exclusivity": "HIGH",
|
| 93 |
+
"Change of Control": "HIGH",
|
| 94 |
+
"No-Solicit of Customers": "HIGH",
|
| 95 |
+
"No-Solicit of Employees": "HIGH",
|
| 96 |
+
"Unilateral change": "HIGH",
|
| 97 |
+
"Content removal": "HIGH",
|
| 98 |
+
"Liquidated Damages": "HIGH",
|
| 99 |
+
"Anti-Assignment": "HIGH",
|
| 100 |
+
# Medium
|
| 101 |
+
"Governing Law": "MEDIUM",
|
| 102 |
+
"Jurisdiction": "MEDIUM",
|
| 103 |
+
"Choice of law": "MEDIUM",
|
| 104 |
+
"Price Restriction": "MEDIUM",
|
| 105 |
+
"Minimum Commitment": "MEDIUM",
|
| 106 |
+
"Volume Restriction": "MEDIUM",
|
| 107 |
+
"Non-Disparagement": "MEDIUM",
|
| 108 |
+
"Most Favored Nation": "MEDIUM",
|
| 109 |
+
"Revenue/Profit Sharing": "MEDIUM",
|
| 110 |
+
# Low
|
| 111 |
+
"Document Name": "LOW",
|
| 112 |
+
"Parties": "LOW",
|
| 113 |
+
"Agreement Date": "LOW",
|
| 114 |
+
"Effective Date": "LOW",
|
| 115 |
+
"Expiration Date": "LOW",
|
| 116 |
+
"Renewal Term": "LOW",
|
| 117 |
+
"Joint IP Ownership": "LOW",
|
| 118 |
+
"License Grant": "LOW",
|
| 119 |
+
"Non-Transferable License": "LOW",
|
| 120 |
+
"Affiliate License-Licensor": "LOW",
|
| 121 |
+
"Affiliate License-Licensee": "LOW",
|
| 122 |
+
"Unlimited/All-You-Can-Eat License": "LOW",
|
| 123 |
+
"Irrevocable or Perpetual License": "LOW",
|
| 124 |
+
"Source Code Escrow": "LOW",
|
| 125 |
+
"Post-Termination Services": "LOW",
|
| 126 |
+
"Audit Rights": "LOW",
|
| 127 |
+
"Cap on Liability": "LOW",
|
| 128 |
+
"Warranty Duration": "LOW",
|
| 129 |
+
"Insurance": "LOW",
|
| 130 |
+
"Covenant Not to Sue": "LOW",
|
| 131 |
+
"Third Party Beneficiary": "LOW",
|
| 132 |
+
"Other": "LOW",
|
| 133 |
+
"ROFR/ROFO/ROFN": "LOW",
|
| 134 |
+
"Contract by using": "LOW",
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
DESC_MAP = {label: label.replace("_", " ") for label in _ALL_LABELS}
|
| 138 |
+
DESC_MAP.update({
|
| 139 |
+
"Limitation of liability": "Company limits or excludes liability for losses, data breaches, or service failures.",
|
| 140 |
+
"Unilateral termination": "Company can terminate your account at any time without reason.",
|
| 141 |
+
"Unilateral change": "Company can change terms at any time without your consent.",
|
| 142 |
+
"Content removal": "Company can delete your content without notice or justification.",
|
| 143 |
+
"Contract by using": "You are bound to the contract simply by using the service.",
|
| 144 |
+
"Choice of law": "Governing law may differ from your country, reducing your legal protections.",
|
| 145 |
+
"Jurisdiction": "Disputes must be resolved in a jurisdiction that may disadvantage you.",
|
| 146 |
+
"Arbitration": "Forces disputes to arbitration instead of court. You waive your right to sue.",
|
| 147 |
+
"Uncapped Liability": "No financial limit on damages the party may be liable for.",
|
| 148 |
+
"Cap on Liability": "Maximum financial liability is explicitly capped.",
|
| 149 |
+
"Non-Compete": "Restrictions on competing with the counter-party.",
|
| 150 |
+
"Exclusivity": "Obligation to deal exclusively with one party.",
|
| 151 |
+
"IP Ownership Assignment": "Intellectual property rights are transferred entirely.",
|
| 152 |
+
"Termination for Convenience": "Either party may terminate without cause or notice.",
|
| 153 |
+
"Governing Law": "Specifies which jurisdiction's laws apply.",
|
| 154 |
+
"Non-Disparagement": "Agreement not to speak negatively about the other party.",
|
| 155 |
+
"ROFR/ROFO/ROFN": "Right of First Refusal / Offer / Negotiation clause.",
|
| 156 |
+
"Change of Control": "Provisions triggered by ownership or control changes.",
|
| 157 |
+
"Anti-Assignment": "Restrictions on transferring contract rights to third parties.",
|
| 158 |
+
"Liquidated Damages": "Pre-determined damages amount for breach of contract.",
|
| 159 |
+
"Source Code Escrow": "Third-party holds source code for release under defined conditions.",
|
| 160 |
+
"Post-Termination Services": "Services to be provided after the contract ends.",
|
| 161 |
+
"Audit Rights": "Right to inspect records or verify compliance.",
|
| 162 |
+
"Warranty Duration": "Length of time warranties remain in effect.",
|
| 163 |
+
"Covenant Not to Sue": "Agreement not to bring legal action against a party.",
|
| 164 |
+
"Third Party Beneficiary": "Non-party who benefits from the contract terms.",
|
| 165 |
+
})
|
| 166 |
+
|
| 167 |
+
# Risk weights for scoring
|
| 168 |
+
RISK_WEIGHTS = {"CRITICAL": 40, "HIGH": 20, "MEDIUM": 10, "LOW": 3}
|
| 169 |
+
|
| 170 |
+
# Color / badge styles
|
| 171 |
+
RISK_STYLES = {
|
| 172 |
+
"CRITICAL": ("#dc2626", "#fef2f2", "β οΈ"),
|
| 173 |
+
"HIGH": ("#ea580c", "#fff7ed", "β‘"),
|
| 174 |
+
"MEDIUM": ("#ca8a04", "#fefce8", "π"),
|
| 175 |
+
"LOW": ("#16a34a", "#f0fdf4", "β"),
|
| 176 |
}
|
| 177 |
|
| 178 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 179 |
+
# 2. MODEL LOADING
|
| 180 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 181 |
+
|
| 182 |
+
cuad_tokenizer = None
|
| 183 |
+
cuad_model = None
|
| 184 |
+
|
| 185 |
+
def _load_cuad_model():
|
| 186 |
+
global cuad_tokenizer, cuad_model
|
| 187 |
+
if not _HAS_TORCH:
|
| 188 |
+
print("[ClauseGuard] PyTorch not available β using regex fallback")
|
| 189 |
+
return
|
| 190 |
+
try:
|
| 191 |
+
base = "nlpaueb/legal-bert-base-uncased"
|
| 192 |
+
adapter = "Mokshith31/legalbert-contract-clause-classification"
|
| 193 |
+
|
| 194 |
+
print(f"[ClauseGuard] Loading CUAD classifier: {adapter}")
|
| 195 |
+
cuad_tokenizer = AutoTokenizer.from_pretrained(base)
|
| 196 |
+
base_model = AutoModelForSequenceClassification.from_pretrained(
|
| 197 |
+
base, num_labels=41, ignore_mismatched_sizes=True
|
| 198 |
+
)
|
| 199 |
+
cuad_model = PeftModel.from_pretrained(base_model, adapter)
|
| 200 |
+
cuad_model.eval()
|
| 201 |
+
print("[ClauseGuard] CUAD model loaded successfully")
|
| 202 |
+
except Exception as e:
|
| 203 |
+
print(f"[ClauseGuard] CUAD model load failed: {e}")
|
| 204 |
+
cuad_tokenizer = None
|
| 205 |
+
cuad_model = None
|
| 206 |
+
|
| 207 |
+
_load_cuad_model()
|
| 208 |
+
|
| 209 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 210 |
+
# 3. DOCUMENT PARSING
|
| 211 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 212 |
+
|
| 213 |
+
def parse_pdf(file_path):
|
| 214 |
+
if not _HAS_PDF:
|
| 215 |
+
return None, "PDF parsing not available (pdfplumber not installed)"
|
| 216 |
+
try:
|
| 217 |
+
text = ""
|
| 218 |
+
with pdfplumber.open(file_path) as pdf:
|
| 219 |
+
for page in pdf.pages:
|
| 220 |
+
page_text = page.extract_text()
|
| 221 |
+
if page_text:
|
| 222 |
+
text += page_text + "\n\n"
|
| 223 |
+
return text.strip(), None
|
| 224 |
+
except Exception as e:
|
| 225 |
+
return None, f"PDF parse error: {e}"
|
| 226 |
+
|
| 227 |
+
def parse_docx(file_path):
|
| 228 |
+
if not _HAS_DOCX:
|
| 229 |
+
return None, "DOCX parsing not available (python-docx not installed)"
|
| 230 |
+
try:
|
| 231 |
+
doc = DocxDocument(file_path)
|
| 232 |
+
paragraphs = [p.text for p in doc.paragraphs if p.text.strip()]
|
| 233 |
+
return "\n\n".join(paragraphs), None
|
| 234 |
+
except Exception as e:
|
| 235 |
+
return None, f"DOCX parse error: {e}"
|
| 236 |
+
|
| 237 |
+
def parse_document(file_path):
|
| 238 |
+
if file_path is None:
|
| 239 |
+
return None, "No file uploaded"
|
| 240 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 241 |
+
if ext == ".pdf":
|
| 242 |
+
return parse_pdf(file_path)
|
| 243 |
+
elif ext in (".docx", ".doc"):
|
| 244 |
+
return parse_docx(file_path)
|
| 245 |
+
elif ext in (".txt", ".md", ".rst"):
|
| 246 |
+
try:
|
| 247 |
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 248 |
+
return f.read(), None
|
| 249 |
+
except Exception as e:
|
| 250 |
+
return None, f"Text read error: {e}"
|
| 251 |
+
else:
|
| 252 |
+
return None, f"Unsupported file type: {ext}"
|
| 253 |
+
|
| 254 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 255 |
+
# 4. CLAUSE DETECTION
|
| 256 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 257 |
+
|
| 258 |
+
def split_clauses(text):
|
| 259 |
+
"""Split contract text into individual clauses."""
|
| 260 |
+
text = re.sub(r'\n{3,}', '\n\n', text.strip())
|
| 261 |
+
parts = re.split(
|
| 262 |
+
r'(?<=[.!?])\s+(?=[A-Z0-9(])|(?:\n\n)(?=\d+[.)]\s|\([a-z]\)\s|[A-Z][A-Z\s]{2,})',
|
| 263 |
+
text
|
| 264 |
+
)
|
| 265 |
+
clauses = []
|
| 266 |
+
for p in parts:
|
| 267 |
+
p = p.strip()
|
| 268 |
+
if len(p) > 30:
|
| 269 |
+
clauses.append(p)
|
| 270 |
+
return clauses
|
| 271 |
+
|
| 272 |
+
def classify_cuad(clause_text):
|
| 273 |
+
"""Classify a single clause using the CUAD model."""
|
| 274 |
+
if cuad_model is None or cuad_tokenizer is None:
|
| 275 |
+
return _classify_regex(clause_text)
|
| 276 |
+
|
| 277 |
+
try:
|
| 278 |
+
inputs = cuad_tokenizer(
|
| 279 |
+
clause_text,
|
| 280 |
+
return_tensors="pt",
|
| 281 |
+
truncation=True,
|
| 282 |
+
max_length=256,
|
| 283 |
+
padding=True
|
| 284 |
+
)
|
| 285 |
+
with torch.no_grad():
|
| 286 |
+
logits = cuad_model(**inputs).logits
|
| 287 |
+
probs = torch.softmax(logits, dim=-1)[0]
|
| 288 |
+
|
| 289 |
+
# Multi-label: return all labels above threshold
|
| 290 |
+
threshold = 0.15
|
| 291 |
+
results = []
|
| 292 |
+
for i, prob in enumerate(probs):
|
| 293 |
+
if prob > threshold and i < len(CUAD_LABELS):
|
| 294 |
+
label = CUAD_LABELS[i]
|
| 295 |
+
risk = RISK_MAP.get(label, "LOW")
|
| 296 |
+
results.append({
|
| 297 |
+
"label": label,
|
| 298 |
+
"confidence": round(float(prob), 3),
|
| 299 |
+
"risk": risk,
|
| 300 |
+
"description": DESC_MAP.get(label, label),
|
| 301 |
+
})
|
| 302 |
+
# Sort by confidence descending
|
| 303 |
+
results.sort(key=lambda x: x["confidence"], reverse=True)
|
| 304 |
+
# If no labels above threshold, take top-1
|
| 305 |
+
if not results:
|
| 306 |
+
top_idx = int(probs.argmax())
|
| 307 |
+
label = CUAD_LABELS[top_idx] if top_idx < len(CUAD_LABELS) else "Other"
|
| 308 |
+
results.append({
|
| 309 |
+
"label": label,
|
| 310 |
+
"confidence": round(float(probs[top_idx]), 3),
|
| 311 |
+
"risk": RISK_MAP.get(label, "LOW"),
|
| 312 |
+
"description": DESC_MAP.get(label, label),
|
| 313 |
+
})
|
| 314 |
+
return results
|
| 315 |
+
except Exception as e:
|
| 316 |
+
print(f"[ClauseGuard] CUAD inference error: {e}")
|
| 317 |
+
return _classify_regex(clause_text)
|
| 318 |
+
|
| 319 |
+
_REGEX_PATTERNS = {
|
| 320 |
"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"],
|
| 321 |
"Unilateral termination": [r"terminat.*at any time", r"suspend.*account.*without", r"we may (terminat|suspend|discontinu)", r"right to (terminat|suspend)"],
|
| 322 |
"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)"],
|
|
|
|
| 325 |
"Choice of law": [r"governed by.*laws? of", r"shall be governed", r"laws of the state of"],
|
| 326 |
"Jurisdiction": [r"exclusive jurisdiction", r"courts? of.*(california|delaware|new york|ireland|england)", r"submit to.*jurisdiction"],
|
| 327 |
"Arbitration": [r"arbitrat", r"binding arbitration", r"waive.*right.*court", r"class action waiver"],
|
| 328 |
+
"Governing Law": [r"governed by", r"laws of", r"jurisdiction of"],
|
| 329 |
+
"Termination for Convenience": [r"terminat.*for convenience", r"terminat.*without cause", r"terminat.*at any time"],
|
| 330 |
+
"Non-Compete": [r"non-compete", r"shall not compete", r"competition"],
|
| 331 |
+
"Exclusivity": [r"exclusive", r"exclusivity"],
|
| 332 |
+
"IP Ownership Assignment": [r"assign.*intellectual property", r"ownership of.*ip", r"all rights.*assign"],
|
| 333 |
+
"Uncapped Liability": [r"unlimited liability", r"uncapped", r"no.*limit.*liability"],
|
| 334 |
+
"Cap on Liability": [r"cap on liability", r"maximum liability", r"liability.*shall not exceed"],
|
| 335 |
}
|
| 336 |
|
| 337 |
+
def _classify_regex(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
text_lower = text.lower()
|
| 339 |
+
results = []
|
| 340 |
+
seen = set()
|
| 341 |
+
for label, patterns in _REGEX_PATTERNS.items():
|
| 342 |
+
for pat in patterns:
|
| 343 |
+
if re.search(pat, text_lower):
|
| 344 |
+
if label not in seen:
|
| 345 |
+
risk = RISK_MAP.get(label, "MEDIUM")
|
| 346 |
+
results.append({
|
| 347 |
+
"label": label,
|
| 348 |
+
"confidence": 0.7,
|
| 349 |
+
"risk": risk,
|
| 350 |
+
"description": DESC_MAP.get(label, label),
|
| 351 |
+
})
|
| 352 |
+
seen.add(label)
|
| 353 |
break
|
| 354 |
return results
|
| 355 |
|
| 356 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 357 |
+
# 5. LEGAL NER
|
| 358 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 359 |
+
|
| 360 |
+
def extract_entities(text):
|
| 361 |
+
"""Extract legal entities using regex patterns."""
|
| 362 |
+
entities = []
|
| 363 |
+
|
| 364 |
+
# Dates
|
| 365 |
+
date_patterns = [
|
| 366 |
+
(r'\b(?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2},?\s+\d{4}\b', "DATE"),
|
| 367 |
+
(r'\b\d{1,2}/\d{1,2}/\d{2,4}\b', "DATE"),
|
| 368 |
+
(r'\b\d{1,2}-\d{1,2}-\d{2,4}\b', "DATE"),
|
| 369 |
+
(r'\b(?:Effective|Commencement|Expiration|Termination)\s+Date\b', "DATE_REF"),
|
| 370 |
+
]
|
| 371 |
+
for pat, etype in date_patterns:
|
| 372 |
+
for m in re.finditer(pat, text, re.IGNORECASE):
|
| 373 |
+
entities.append({"text": m.group(), "type": etype, "start": m.start(), "end": m.end()})
|
| 374 |
+
|
| 375 |
+
# Monetary values
|
| 376 |
+
money_patterns = [
|
| 377 |
+
(r'\$\d{1,3}(?:,\d{3})*(?:\.\d{2})?(?:\s*(?:million|billion|thousand|M|B|K))?', "MONEY"),
|
| 378 |
+
(r'\b\d{1,3}(?:,\d{3})*(?:\.\d{2})?\s*(?:USD|EUR|GBP|dollars|euros)', "MONEY"),
|
| 379 |
+
]
|
| 380 |
+
for pat, etype in money_patterns:
|
| 381 |
+
for m in re.finditer(pat, text, re.IGNORECASE):
|
| 382 |
+
entities.append({"text": m.group(), "type": etype, "start": m.start(), "end": m.end()})
|
| 383 |
+
|
| 384 |
+
# Party names
|
| 385 |
+
party_patterns = [
|
| 386 |
+
(r'\b[A-Z][A-Za-z0-9\s&]+(?:Inc\.|LLC|Ltd\.|Limited|Corp\.|Corporation|PLC|GmbH|AG|S\.A\.|B\.V\.)\b', "PARTY"),
|
| 387 |
+
(r'\b(?:Party A|Party B|Licensor|Licensee|Buyer|Seller|Tenant|Landlord|Employer|Employee|Company|Customer)\b', "PARTY_ROLE"),
|
| 388 |
+
]
|
| 389 |
+
for pat, etype in party_patterns:
|
| 390 |
+
for m in re.finditer(pat, text):
|
| 391 |
+
entities.append({"text": m.group(), "type": etype, "start": m.start(), "end": m.end()})
|
| 392 |
+
|
| 393 |
+
# Jurisdictions
|
| 394 |
+
jurisdiction_patterns = [
|
| 395 |
+
(r'\b(?:State|Laws?) of [A-Z][a-zA-Z\s]+', "JURISDICTION"),
|
| 396 |
+
(r'\b(?:California|Delaware|New York|Texas|Florida|England|Ireland|Germany|France|Singapore|Hong Kong)\b', "JURISDICTION"),
|
| 397 |
+
]
|
| 398 |
+
for pat, etype in jurisdiction_patterns:
|
| 399 |
+
for m in re.finditer(pat, text, re.IGNORECASE):
|
| 400 |
+
entities.append({"text": m.group(), "type": etype, "start": m.start(), "end": m.end()})
|
| 401 |
+
|
| 402 |
+
# Defined Terms
|
| 403 |
+
defined_patterns = [
|
| 404 |
+
(r'"([A-Z][A-Z\s]+)"', "DEFINED_TERM"),
|
| 405 |
+
(r'\(([A-Z][A-Z\s]+)\)', "DEFINED_TERM"),
|
| 406 |
+
]
|
| 407 |
+
for pat, etype in defined_patterns:
|
| 408 |
+
for m in re.finditer(pat, text):
|
| 409 |
+
entities.append({"text": m.group(1), "type": etype, "start": m.start(), "end": m.end()})
|
| 410 |
+
|
| 411 |
+
# Deduplicate overlapping
|
| 412 |
+
entities.sort(key=lambda x: (x["start"], -(x["end"] - x["start"])))
|
| 413 |
+
filtered = []
|
| 414 |
+
last_end = -1
|
| 415 |
+
for e in entities:
|
| 416 |
+
if e["start"] >= last_end:
|
| 417 |
+
filtered.append(e)
|
| 418 |
+
last_end = e["end"]
|
| 419 |
+
return filtered
|
| 420 |
+
|
| 421 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 422 |
+
# 6. NLI / CONTRADICTION DETECTION
|
| 423 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 424 |
+
|
| 425 |
+
_CONTRADICTION_PAIRS = [
|
| 426 |
+
(["Uncapped Liability", "unlimited liability"], ["Cap on Liability", "cap on liability"],
|
| 427 |
+
"Liability cannot be both uncapped and capped simultaneously."),
|
| 428 |
+
(["Governing Law"], ["Governing Law"],
|
| 429 |
+
"Multiple governing law provisions detected β verify consistency."),
|
| 430 |
+
(["Termination for Convenience", "terminat.*convenience"], ["Fixed Term", "fixed term"],
|
| 431 |
+
"Contract has both fixed term and termination for convenience β review carefully."),
|
| 432 |
+
(["IP Ownership Assignment", "assign.*ip"], ["Joint IP Ownership", "joint ownership"],
|
| 433 |
+
"IP cannot be both fully assigned and jointly owned."),
|
| 434 |
+
]
|
| 435 |
+
|
| 436 |
+
def detect_contradictions(clause_results):
|
| 437 |
+
"""Detect contradictions and missing critical clauses."""
|
| 438 |
+
contradictions = []
|
| 439 |
+
labels_found = set()
|
| 440 |
+
texts_found = {}
|
| 441 |
+
|
| 442 |
+
for cr in clause_results:
|
| 443 |
+
labels_found.add(cr["label"])
|
| 444 |
+
texts_found[cr["label"]] = cr.get("text", "")
|
| 445 |
+
|
| 446 |
+
# Contradiction pairs
|
| 447 |
+
for group_a, group_b, explanation in _CONTRADICTION_PAIRS:
|
| 448 |
+
found_a = any(l in labels_found for l in group_a)
|
| 449 |
+
found_b = any(l in labels_found for l in group_b)
|
| 450 |
+
if found_a and found_b:
|
| 451 |
+
contradictions.append({
|
| 452 |
+
"type": "CONTRADICTION",
|
| 453 |
+
"explanation": explanation,
|
| 454 |
+
"severity": "HIGH",
|
| 455 |
+
"clauses": list(set(group_a + group_b)),
|
| 456 |
+
})
|
| 457 |
+
|
| 458 |
+
# Missing critical clauses
|
| 459 |
+
critical_clauses = ["Governing Law", "Termination for Convenience", "Limitation of liability", "Arbitration"]
|
| 460 |
+
for cc in critical_clauses:
|
| 461 |
+
if cc not in labels_found:
|
| 462 |
+
contradictions.append({
|
| 463 |
+
"type": "MISSING",
|
| 464 |
+
"explanation": f"Critical clause '{cc}' not detected in the document.",
|
| 465 |
+
"severity": "MEDIUM",
|
| 466 |
+
"clauses": [cc],
|
| 467 |
+
})
|
| 468 |
+
|
| 469 |
+
return contradictions
|
| 470 |
+
|
| 471 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 472 |
+
# 7. RISK SCORING
|
| 473 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 474 |
+
|
| 475 |
+
def compute_risk_score(clause_results, total_clauses):
|
| 476 |
+
sev_counts = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0}
|
| 477 |
+
for cr in clause_results:
|
| 478 |
+
sev = cr.get("risk", "LOW")
|
| 479 |
+
sev_counts[sev] += 1
|
| 480 |
+
|
| 481 |
+
if total_clauses == 0:
|
| 482 |
+
return 0, "A", sev_counts
|
| 483 |
+
|
| 484 |
+
weighted = sum(sev_counts[s] * RISK_WEIGHTS[s] for s in sev_counts)
|
| 485 |
+
risk = min(100, round(weighted / max(1, total_clauses) * 10))
|
| 486 |
+
|
| 487 |
+
if risk >= 70: grade = "F"
|
| 488 |
+
elif risk >= 50: grade = "D"
|
| 489 |
+
elif risk >= 30: grade = "C"
|
| 490 |
+
elif risk >= 15: grade = "B"
|
| 491 |
+
else: grade = "A"
|
| 492 |
+
|
| 493 |
+
return risk, grade, sev_counts
|
| 494 |
|
| 495 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 496 |
+
# 8. MAIN ANALYSIS PIPELINE
|
| 497 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 498 |
+
|
| 499 |
+
def analyze_contract(text):
|
| 500 |
if not text or len(text.strip()) < 50:
|
| 501 |
+
return None, "Document too short (minimum 50 characters)"
|
| 502 |
|
| 503 |
clauses = split_clauses(text)
|
| 504 |
if not clauses:
|
| 505 |
+
return None, "No clauses detected in document"
|
|
|
|
|
|
|
|
|
|
| 506 |
|
| 507 |
+
# Analyze each clause
|
| 508 |
+
clause_results = []
|
| 509 |
for clause in clauses:
|
| 510 |
+
predictions = classify_cuad(clause)
|
| 511 |
+
if predictions:
|
| 512 |
+
for pred in predictions:
|
| 513 |
+
clause_results.append({
|
| 514 |
+
"text": clause,
|
| 515 |
+
"label": pred["label"],
|
| 516 |
+
"confidence": pred["confidence"],
|
| 517 |
+
"risk": pred["risk"],
|
| 518 |
+
"description": pred["description"],
|
| 519 |
+
})
|
| 520 |
+
|
| 521 |
+
# NER
|
| 522 |
+
entities = extract_entities(text)
|
| 523 |
+
|
| 524 |
+
# NLI / contradictions
|
| 525 |
+
contradictions = detect_contradictions(clause_results)
|
| 526 |
+
|
| 527 |
+
# Risk scoring
|
| 528 |
+
risk, grade, sev_counts = compute_risk_score(clause_results, len(clauses))
|
| 529 |
+
|
| 530 |
+
# Build result object
|
| 531 |
+
result = {
|
| 532 |
+
"metadata": {
|
| 533 |
+
"analysis_date": datetime.now().isoformat(),
|
| 534 |
+
"total_clauses": len(clauses),
|
| 535 |
+
"flagged_clauses": len(set(cr["text"] for cr in clause_results)),
|
| 536 |
+
"model": "Legal-BERT + CUAD (41 classes)" if cuad_model else "Regex fallback",
|
| 537 |
+
},
|
| 538 |
+
"risk": {
|
| 539 |
+
"score": risk,
|
| 540 |
+
"grade": grade,
|
| 541 |
+
"breakdown": sev_counts,
|
| 542 |
+
},
|
| 543 |
+
"clauses": clause_results,
|
| 544 |
+
"entities": entities,
|
| 545 |
+
"contradictions": contradictions,
|
| 546 |
+
"raw_text": text,
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
return result, None
|
| 550 |
+
|
| 551 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 552 |
+
# 9. EXPORT FUNCTIONS
|
| 553 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 554 |
+
|
| 555 |
+
def export_json(result):
|
| 556 |
+
if result is None:
|
| 557 |
+
return None
|
| 558 |
+
return json.dumps(result, indent=2, default=str)
|
| 559 |
+
|
| 560 |
+
def export_csv(result):
|
| 561 |
+
if result is None:
|
| 562 |
+
return None
|
| 563 |
+
output = io.StringIO()
|
| 564 |
+
writer = csv.writer(output)
|
| 565 |
+
writer.writerow(["Clause Text", "Label", "Risk", "Confidence", "Description"])
|
| 566 |
+
for cr in result.get("clauses", []):
|
| 567 |
+
writer.writerow([
|
| 568 |
+
cr.get("text", "")[:500],
|
| 569 |
+
cr.get("label", ""),
|
| 570 |
+
cr.get("risk", ""),
|
| 571 |
+
cr.get("confidence", ""),
|
| 572 |
+
cr.get("description", ""),
|
| 573 |
+
])
|
| 574 |
+
return output.getvalue()
|
| 575 |
+
|
| 576 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 577 |
+
# 10. UI RENDERING
|
| 578 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 579 |
+
|
| 580 |
+
def render_summary(result):
|
| 581 |
+
if result is None:
|
| 582 |
+
return ""
|
| 583 |
+
|
| 584 |
+
risk = result["risk"]
|
| 585 |
+
score = risk["score"]
|
| 586 |
+
grade = risk["grade"]
|
| 587 |
+
breakdown = risk["breakdown"]
|
| 588 |
+
|
| 589 |
+
grade_color = {
|
| 590 |
+
"A": "#16a34a", "B": "#65a30d", "C": "#ca8a04",
|
| 591 |
+
"D": "#ea580c", "F": "#dc2626",
|
| 592 |
+
}.get(grade, "#6b7280")
|
| 593 |
+
|
| 594 |
+
crit, high, med, low = breakdown["CRITICAL"], breakdown["HIGH"], breakdown["MEDIUM"], breakdown["LOW"]
|
| 595 |
+
|
| 596 |
+
html = f"""
|
| 597 |
+
<div style="font-family:system-ui,sans-serif;padding:16px;border:1px solid #e5e7eb;border-radius:12px;background:#fff;">
|
| 598 |
+
<div style="text-align:center;margin-bottom:16px;">
|
| 599 |
+
<div style="font-size:48px;font-weight:700;color:{grade_color};">{score}</div>
|
| 600 |
+
<div style="font-size:14px;color:#6b7280;">/100 Risk Score</div>
|
| 601 |
+
<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;">
|
| 602 |
+
Grade {grade}
|
| 603 |
+
</div>
|
| 604 |
+
</div>
|
| 605 |
+
<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;">
|
| 606 |
+
<div style="padding:8px;border-radius:6px;background:#fef2f2;text-align:center;">
|
| 607 |
+
<div style="font-size:20px;font-weight:700;color:#dc2626;">{crit}</div>
|
| 608 |
+
<div style="font-size:11px;color:#991b1b;">Critical</div>
|
| 609 |
+
</div>
|
| 610 |
+
<div style="padding:8px;border-radius:6px;background:#fff7ed;text-align:center;">
|
| 611 |
+
<div style="font-size:20px;font-weight:700;color:#ea580c;">{high}</div>
|
| 612 |
+
<div style="font-size:11px;color:#9a3412;">High</div>
|
| 613 |
+
</div>
|
| 614 |
+
<div style="padding:8px;border-radius:6px;background:#fefce8;text-align:center;">
|
| 615 |
+
<div style="font-size:20px;font-weight:700;color:#ca8a04;">{med}</div>
|
| 616 |
+
<div style="font-size:11px;color:#854d0e;">Medium</div>
|
| 617 |
+
</div>
|
| 618 |
+
<div style="padding:8px;border-radius:6px;background:#f0fdf4;text-align:center;">
|
| 619 |
+
<div style="font-size:20px;font-weight:700;color:#16a34a;">{low}</div>
|
| 620 |
+
<div style="font-size:11px;color:#166534;">Low</div>
|
| 621 |
+
</div>
|
| 622 |
+
</div>
|
| 623 |
+
<div style="font-size:12px;color:#6b7280;text-align:center;">
|
| 624 |
+
{result['metadata']['total_clauses']} clauses analyzed Β· {result['metadata']['flagged_clauses']} flagged
|
| 625 |
+
<br>Engine: {result['metadata']['model']}
|
| 626 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 627 |
</div>
|
| 628 |
+
"""
|
| 629 |
+
return html
|
| 630 |
|
| 631 |
+
def render_clause_cards(result):
|
| 632 |
+
if result is None:
|
| 633 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
|
| 635 |
+
clauses = result.get("clauses", [])
|
| 636 |
+
if not clauses:
|
| 637 |
+
return '<div style="padding:24px;text-align:center;color:#6b7280;">No clauses detected.</div>'
|
| 638 |
+
|
| 639 |
+
# Group by clause text
|
| 640 |
+
grouped = defaultdict(list)
|
| 641 |
+
for cr in clauses:
|
| 642 |
+
grouped[cr["text"]].append(cr)
|
| 643 |
+
|
| 644 |
+
html = '<div style="font-family:system-ui,sans-serif;">'
|
| 645 |
+
for text, items in grouped.items():
|
| 646 |
+
max_risk = max(items, key=lambda x: {"CRITICAL":4,"HIGH":3,"MEDIUM":2,"LOW":1}[x["risk"]])["risk"]
|
| 647 |
+
border, bg, icon = RISK_STYLES[max_risk]
|
| 648 |
+
|
| 649 |
+
tags = ""
|
| 650 |
+
for item in items:
|
| 651 |
+
tag_bg = RISK_STYLES[item["risk"]][1]
|
| 652 |
+
tag_color = RISK_STYLES[item["risk"]][0]
|
| 653 |
+
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;">{item["label"]} ({item["confidence"]})</span>'
|
| 654 |
+
|
| 655 |
+
descs = "".join(
|
| 656 |
+
f'<p style="font-size:12px;color:#6b7280;margin:4px 0 0 0;">{item["description"]}</p>'
|
| 657 |
+
for item in items
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
preview = text[:300] + ("..." if len(text) > 300 else "")
|
| 661 |
+
preview = preview.replace("<", "<").replace(">", ">")
|
| 662 |
+
|
| 663 |
+
html += f"""
|
| 664 |
+
<div style="border:1px solid #e5e7eb;border-left:4px solid {border};border-radius:8px;padding:14px;margin-bottom:10px;background:#fafafa;">
|
| 665 |
+
<div style="display:flex;align-items:center;gap:6px;margin-bottom:6px;">
|
| 666 |
+
<span style="font-size:16px;">{icon}</span>
|
| 667 |
+
<span style="font-size:12px;font-weight:600;color:{border};text-transform:uppercase;">{max_risk}</span>
|
| 668 |
+
</div>
|
| 669 |
+
<p style="font-size:13px;color:#374151;line-height:1.6;margin:0 0 8px 0;">{preview}</p>
|
| 670 |
+
<div style="margin-bottom:6px;">{tags}</div>
|
| 671 |
+
{descs}
|
| 672 |
+
</div>
|
| 673 |
+
"""
|
| 674 |
+
html += "</div>"
|
| 675 |
+
return html
|
| 676 |
+
|
| 677 |
+
def render_entities(result):
|
| 678 |
+
if result is None:
|
| 679 |
+
return ""
|
| 680 |
+
|
| 681 |
+
entities = result.get("entities", [])
|
| 682 |
+
if not entities:
|
| 683 |
+
return '<div style="padding:16px;color:#6b7280;">No entities detected.</div>'
|
| 684 |
+
|
| 685 |
+
# Group by type
|
| 686 |
+
grouped = defaultdict(list)
|
| 687 |
+
for e in entities:
|
| 688 |
+
grouped[e["type"]].append(e["text"])
|
| 689 |
+
|
| 690 |
+
html = '<div style="font-family:system-ui,sans-serif;">'
|
| 691 |
+
for etype, texts in grouped.items():
|
| 692 |
+
unique = list(dict.fromkeys(texts))[:20]
|
| 693 |
+
color = {
|
| 694 |
+
"DATE": "#3b82f6", "DATE_REF": "#60a5fa",
|
| 695 |
+
"MONEY": "#22c55e",
|
| 696 |
+
"PARTY": "#8b5cf6", "PARTY_ROLE": "#a78bfa",
|
| 697 |
+
"JURISDICTION": "#f59e0b",
|
| 698 |
+
"DEFINED_TERM": "#ec4899",
|
| 699 |
+
}.get(etype, "#6b7280")
|
| 700 |
+
|
| 701 |
+
items_html = "".join(
|
| 702 |
+
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>'
|
| 703 |
+
for t in unique
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
html += f"""
|
| 707 |
+
<div style="margin-bottom:12px;">
|
| 708 |
+
<div style="font-size:12px;font-weight:600;color:#374151;margin-bottom:6px;text-transform:uppercase;">{etype}</div>
|
| 709 |
+
<div>{items_html}</div>
|
| 710 |
+
</div>
|
| 711 |
+
"""
|
| 712 |
+
html += "</div>"
|
| 713 |
+
return html
|
| 714 |
+
|
| 715 |
+
def render_contradictions(result):
|
| 716 |
+
if result is None:
|
| 717 |
+
return ""
|
| 718 |
+
|
| 719 |
+
contradictions = result.get("contradictions", [])
|
| 720 |
+
if not contradictions:
|
| 721 |
+
return '<div style="padding:16px;color:#16a34a;">β No contradictions or missing clauses detected.</div>'
|
| 722 |
+
|
| 723 |
+
html = '<div style="font-family:system-ui,sans-serif;">'
|
| 724 |
+
for c in contradictions:
|
| 725 |
+
sev_color = RISK_STYLES[c["severity"]][0]
|
| 726 |
+
icon = "β οΈ" if c["type"] == "CONTRADICTION" else "π"
|
| 727 |
+
html += f"""
|
| 728 |
+
<div style="border:1px solid #e5e7eb;border-left:4px solid {sev_color};border-radius:8px;padding:12px;margin-bottom:8px;background:#fafafa;">
|
| 729 |
+
<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">
|
| 730 |
+
<span>{icon}</span>
|
| 731 |
+
<span style="font-size:12px;font-weight:600;color:{sev_color};">{c["type"]}</span>
|
| 732 |
+
</div>
|
| 733 |
+
<p style="font-size:13px;color:#374151;margin:0;">{c["explanation"]}</p>
|
| 734 |
+
</div>
|
| 735 |
+
"""
|
| 736 |
+
html += "</div>"
|
| 737 |
+
return html
|
| 738 |
+
|
| 739 |
+
def render_document_viewer(result):
|
| 740 |
+
if result is None:
|
| 741 |
+
return ""
|
| 742 |
+
|
| 743 |
+
text = result.get("raw_text", "")
|
| 744 |
+
entities = sorted(result.get("entities", []), key=lambda x: x["start"])
|
| 745 |
+
|
| 746 |
+
html_parts = []
|
| 747 |
+
last_end = 0
|
| 748 |
+
for e in entities:
|
| 749 |
+
if e["start"] >= last_end:
|
| 750 |
+
html_parts.append(text[last_end:e["start"]].replace("<", "<").replace(">", ">"))
|
| 751 |
+
color = {
|
| 752 |
+
"DATE": "#bfdbfe", "DATE_REF": "#bfdbfe",
|
| 753 |
+
"MONEY": "#bbf7d0",
|
| 754 |
+
"PARTY": "#ddd6fe", "PARTY_ROLE": "#ddd6fe",
|
| 755 |
+
"JURISDICTION": "#fde68a",
|
| 756 |
+
"DEFINED_TERM": "#fbcfe8",
|
| 757 |
+
}.get(e["type"], "#e5e7eb")
|
| 758 |
+
label = e["type"].replace("_", " ")
|
| 759 |
+
html_parts.append(
|
| 760 |
+
f'<mark style="background:{color};padding:1px 2px;border-radius:2px;font-size:12px;" title="{label}">{e["text"].replace("<","<").replace(">",">")}</mark>'
|
| 761 |
+
)
|
| 762 |
+
last_end = e["end"]
|
| 763 |
+
|
| 764 |
+
html_parts.append(text[last_end:].replace("<", "<").replace(">", ">"))
|
| 765 |
+
highlighted = "".join(html_parts)
|
| 766 |
+
|
| 767 |
+
return f"""
|
| 768 |
+
<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;">
|
| 769 |
+
{highlighted}
|
| 770 |
+
</div>
|
| 771 |
+
"""
|
| 772 |
|
| 773 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 774 |
+
# 11. GRADIO UI
|
| 775 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 776 |
|
| 777 |
+
def process_upload(file):
|
| 778 |
+
if file is None:
|
| 779 |
+
return "", "No file uploaded"
|
| 780 |
+
text, error = parse_document(file)
|
| 781 |
+
if error:
|
| 782 |
+
return "", error
|
| 783 |
+
return text, "Document loaded successfully"
|
| 784 |
|
| 785 |
+
def run_analysis(text):
|
| 786 |
+
if not text or len(text.strip()) < 50:
|
| 787 |
+
return [""] * 5 + [None, None, "Document too short (minimum 50 characters)"]
|
| 788 |
+
|
| 789 |
+
result, error = analyze_contract(text)
|
| 790 |
+
if error:
|
| 791 |
+
err_html = f'<p style="color:#dc2626;padding:16px;">{error}</p>'
|
| 792 |
+
return [err_html] * 5 + [None, None, error]
|
| 793 |
+
|
| 794 |
+
# Save export files
|
| 795 |
+
json_path = "/tmp/clauseguard_report.json"
|
| 796 |
+
with open(json_path, "w") as f:
|
| 797 |
+
json.dump(result, f, indent=2, default=str)
|
| 798 |
+
|
| 799 |
+
csv_content = export_csv(result)
|
| 800 |
+
csv_path = "/tmp/clauseguard_report.csv"
|
| 801 |
+
with open(csv_path, "w") as f:
|
| 802 |
+
f.write(csv_content)
|
| 803 |
+
|
| 804 |
+
return [
|
| 805 |
+
render_summary(result),
|
| 806 |
+
render_clause_cards(result),
|
| 807 |
+
render_entities(result),
|
| 808 |
+
render_contradictions(result),
|
| 809 |
+
render_document_viewer(result),
|
| 810 |
+
json_path,
|
| 811 |
+
csv_path,
|
| 812 |
+
"Analysis complete",
|
| 813 |
+
]
|
| 814 |
+
|
| 815 |
+
def do_clear():
|
| 816 |
+
return [""] * 5 + [None, None, ""]
|
| 817 |
+
|
| 818 |
+
# ββ Example contracts ββ
|
| 819 |
+
SPOTIFY_TOS = """By using the Spotify Service, you agree to be bound by these Terms of Use.
|
| 820 |
|
| 821 |
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.
|
| 822 |
|
|
|
|
| 828 |
|
| 829 |
These Terms will be governed by and construed in accordance with the laws of the State of New York.
|
| 830 |
|
| 831 |
+
Any dispute shall be finally settled by arbitration in New York County. The parties waive any right to a jury trial."""
|
| 832 |
|
| 833 |
+
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.
|
| 834 |
|
| 835 |
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.
|
| 836 |
|
| 837 |
The Landlord may terminate this lease at any time with only 7 days written notice, for any reason or no reason at all.
|
| 838 |
|
| 839 |
+
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.
|
| 840 |
|
| 841 |
The Landlord reserves the right to modify the terms of this lease at any time. Continued occupancy constitutes acceptance of the new terms."""
|
| 842 |
|
| 843 |
+
NDA_SAMPLE = """NON-DISCLOSURE AGREEMENT
|
| 844 |
+
|
| 845 |
+
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").
|
| 846 |
|
| 847 |
+
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.
|
|
|
|
| 848 |
|
| 849 |
+
2. Term. This Agreement shall remain in effect for a period of three (3) years from the Effective Date.
|
| 850 |
+
|
| 851 |
+
3. Termination. Either party may terminate this Agreement for convenience upon thirty (30) days prior written notice.
|
| 852 |
+
|
| 853 |
+
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.
|
| 854 |
+
|
| 855 |
+
5. Limitation of Liability. IN NO EVENT SHALL EITHER PARTY BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES.
|
| 856 |
+
|
| 857 |
+
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.
|
| 858 |
+
|
| 859 |
+
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."""
|
| 860 |
+
|
| 861 |
+
with gr.Blocks(
|
| 862 |
+
title="ClauseGuard β AI Contract Analysis",
|
| 863 |
+
css="""
|
| 864 |
+
.gradio-container { max-width: 1400px !important; }
|
| 865 |
+
"""
|
| 866 |
+
) as demo:
|
| 867 |
+
|
| 868 |
+
gr.HTML("""
|
| 869 |
+
<div style="display:flex;align-items:center;justify-content:space-between;padding:12px 0;border-bottom:2px solid #e5e7eb;margin-bottom:16px;">
|
| 870 |
+
<div>
|
| 871 |
+
<h1 style="font-size:24px;font-weight:700;margin:0;color:#1f2937;">π‘οΈ ClauseGuard</h1>
|
| 872 |
+
<p style="font-size:13px;color:#6b7280;margin:4px 0 0 0;">AI-Powered Legal Contract Analysis Β· 41 Clause Categories Β· Risk Scoring Β· NER Β· NLI</p>
|
| 873 |
+
</div>
|
| 874 |
+
<div style="font-size:12px;color:#9ca3af;">v2.0 Β· World's Best Legal AI</div>
|
| 875 |
+
</div>
|
| 876 |
+
""")
|
| 877 |
+
|
| 878 |
+
# ββ Upload / Input ββ
|
| 879 |
with gr.Row():
|
| 880 |
with gr.Column(scale=1):
|
| 881 |
+
file_input = gr.File(
|
| 882 |
+
label="π Upload Contract (PDF/DOCX/TXT)",
|
| 883 |
+
file_types=[".pdf", ".docx", ".doc", ".txt", ".md"],
|
| 884 |
+
)
|
| 885 |
+
load_btn = gr.Button("Load Document", variant="secondary", size="sm")
|
| 886 |
+
load_status = gr.Textbox(label="Status", interactive=False, lines=1)
|
| 887 |
+
|
| 888 |
+
with gr.Column(scale=3):
|
| 889 |
+
text_input = gr.Textbox(
|
| 890 |
+
label="π Contract Text",
|
| 891 |
+
placeholder="Paste contract text here, or upload a file above...",
|
| 892 |
+
lines=14,
|
| 893 |
+
max_lines=40,
|
| 894 |
+
show_copy_button=True,
|
| 895 |
+
)
|
| 896 |
|
| 897 |
with gr.Column(scale=1):
|
| 898 |
+
scan_btn = gr.Button("π Analyze Contract", variant="primary", size="lg")
|
| 899 |
+
clear_btn = gr.Button("Clear", variant="secondary", size="sm")
|
| 900 |
+
status_msg = gr.Textbox(label="Analysis Status", interactive=False, lines=1)
|
| 901 |
|
| 902 |
+
# ββ Examples ββ
|
| 903 |
+
with gr.Row():
|
| 904 |
+
gr.Examples(
|
| 905 |
+
examples=[[SPOTIFY_TOS], [RENTAL_AGREEMENT], [NDA_SAMPLE]],
|
| 906 |
+
inputs=[text_input],
|
| 907 |
+
label="Example Contracts",
|
| 908 |
+
)
|
| 909 |
|
| 910 |
+
# ββ Results ββ
|
| 911 |
+
with gr.Row():
|
| 912 |
+
# Left: Summary + Export
|
| 913 |
+
with gr.Column(scale=1):
|
| 914 |
+
gr.Markdown("### π Risk Summary")
|
| 915 |
+
summary_html = gr.HTML()
|
| 916 |
+
|
| 917 |
+
gr.Markdown("### π₯ Export Reports")
|
| 918 |
+
json_file = gr.File(label="JSON Report")
|
| 919 |
+
csv_file = gr.File(label="CSV Report")
|
| 920 |
+
|
| 921 |
+
# Center: Main Content Tabs
|
| 922 |
+
with gr.Column(scale=3):
|
| 923 |
+
with gr.Tabs():
|
| 924 |
+
with gr.Tab("π Document"):
|
| 925 |
+
doc_html = gr.HTML(label="Document Viewer")
|
| 926 |
+
with gr.Tab("β οΈ Clauses (41 Categories)"):
|
| 927 |
+
clauses_html = gr.HTML(label="Detected Clauses")
|
| 928 |
+
with gr.Tab("π·οΈ Entities"):
|
| 929 |
+
entities_html = gr.HTML(label="Named Entities")
|
| 930 |
+
with gr.Tab("π Contradictions"):
|
| 931 |
+
nli_html = gr.HTML(label="Contradictions & Missing Clauses")
|
| 932 |
+
|
| 933 |
+
# ββ Events ββ
|
| 934 |
+
def _load_file(file):
|
| 935 |
+
text, err = parse_document(file) if file else ("", "No file")
|
| 936 |
+
if err and not text:
|
| 937 |
+
return "", err
|
| 938 |
+
return text, "Loaded successfully" if not err else err
|
| 939 |
+
|
| 940 |
+
load_btn.click(_load_file, inputs=[file_input], outputs=[text_input, load_status])
|
| 941 |
+
|
| 942 |
+
scan_btn.click(
|
| 943 |
+
run_analysis,
|
| 944 |
+
inputs=[text_input],
|
| 945 |
+
outputs=[summary_html, clauses_html, entities_html, nli_html,
|
| 946 |
+
doc_html, json_file, csv_file, status_msg]
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
clear_btn.click(
|
| 950 |
+
do_clear,
|
| 951 |
+
outputs=[summary_html, clauses_html, entities_html, nli_html,
|
| 952 |
+
doc_html, json_file, csv_file, status_msg]
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
gr.HTML("""
|
| 956 |
+
<div style="margin-top:24px;padding:16px 0;border-top:1px solid #e5e7eb;text-align:center;">
|
| 957 |
+
<p style="font-size:11px;color:#9ca3af;">
|
| 958 |
+
β οΈ Not legal advice. For informational purposes only.
|
| 959 |
+
Β· Model: <a href="https://huggingface.co/Mokshith31/legalbert-contract-clause-classification" style="color:#6b7280;">Legal-BERT + CUAD</a>
|
| 960 |
+
Β· Dataset: <a href="https://huggingface.co/datasets/theatticusproject/cuad-qa" style="color:#6b7280;">CUAD</a>
|
| 961 |
+
Β· <a href="https://huggingface.co/spaces/gaurv007/ClauseGuard" style="color:#6b7280;">ClauseGuard Space</a>
|
| 962 |
+
</p>
|
| 963 |
+
</div>
|
| 964 |
+
""")
|
| 965 |
|
| 966 |
if __name__ == "__main__":
|
| 967 |
demo.launch()
|