Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,18 +3,17 @@ import json
|
|
| 3 |
import math
|
| 4 |
import re
|
| 5 |
import io
|
| 6 |
-
import asyncio
|
| 7 |
from typing import List, Dict, Tuple, Optional, Any
|
| 8 |
|
| 9 |
import torch
|
| 10 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 11 |
from pypdf import PdfReader
|
| 12 |
import docx
|
| 13 |
import spacy
|
| 14 |
import gradio as gr
|
| 15 |
|
| 16 |
# -----------------------------
|
| 17 |
-
# Model: IBM Granite 3.2 2B Instruct
|
| 18 |
# -----------------------------
|
| 19 |
MODEL_ID = "ibm-granite/granite-3.2-2b-instruct"
|
| 20 |
|
|
@@ -36,7 +35,7 @@ if DEVICE != "cuda":
|
|
| 36 |
nlp = spacy.load("en_core_web_sm")
|
| 37 |
|
| 38 |
# -----------------------------
|
| 39 |
-
#
|
| 40 |
# -----------------------------
|
| 41 |
def build_chat_prompt(system_prompt: str, user_prompt: str) -> str:
|
| 42 |
messages = []
|
|
@@ -46,7 +45,6 @@ def build_chat_prompt(system_prompt: str, user_prompt: str) -> str:
|
|
| 46 |
try:
|
| 47 |
return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 48 |
except Exception:
|
| 49 |
-
# Fallback: simple concatenation
|
| 50 |
sys = f"[SYSTEM]\n{system_prompt}\n" if system_prompt else ""
|
| 51 |
usr = f"[USER]\n{user_prompt}\n[ASSISTANT]\n"
|
| 52 |
return sys + usr
|
|
@@ -54,13 +52,7 @@ def build_chat_prompt(system_prompt: str, user_prompt: str) -> str:
|
|
| 54 |
# -----------------------------
|
| 55 |
# LLM generation
|
| 56 |
# -----------------------------
|
| 57 |
-
def llm_generate(
|
| 58 |
-
system_prompt: str,
|
| 59 |
-
user_prompt: str,
|
| 60 |
-
max_new_tokens: int = 512,
|
| 61 |
-
temperature: float = 0.3,
|
| 62 |
-
top_p: float = 0.9
|
| 63 |
-
) -> str:
|
| 64 |
prompt = build_chat_prompt(system_prompt, user_prompt)
|
| 65 |
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 66 |
with torch.inference_mode():
|
|
@@ -73,10 +65,8 @@ def llm_generate(
|
|
| 73 |
pad_token_id=tokenizer.eos_token_id
|
| 74 |
)
|
| 75 |
full_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 76 |
-
# Try to extract only assistant part if chat template used
|
| 77 |
if "[ASSISTANT]" in full_text:
|
| 78 |
return full_text.split("[ASSISTANT]")[-1].strip()
|
| 79 |
-
# Otherwise, remove the prompt prefix
|
| 80 |
if full_text.startswith(prompt):
|
| 81 |
return full_text[len(prompt):].strip()
|
| 82 |
return full_text.strip()
|
|
@@ -95,7 +85,6 @@ def load_text_from_pdf(file_obj) -> str:
|
|
| 95 |
return "\n".join(pages).strip()
|
| 96 |
|
| 97 |
def load_text_from_docx(file_obj) -> str:
|
| 98 |
-
# file_obj is a temporary file-like object; need to read into BytesIO for python-docx
|
| 99 |
data = file_obj.read()
|
| 100 |
file_obj.seek(0)
|
| 101 |
f = io.BytesIO(data)
|
|
@@ -123,7 +112,6 @@ def load_document(file: Optional[gr.File]) -> str:
|
|
| 123 |
elif name.endswith(".txt"):
|
| 124 |
return load_text_from_txt(file)
|
| 125 |
else:
|
| 126 |
-
# Try all in order
|
| 127 |
try:
|
| 128 |
return load_text_from_pdf(file)
|
| 129 |
except Exception:
|
|
@@ -149,13 +137,10 @@ CLAUSE_SPLIT_REGEX = re.compile(
|
|
| 149 |
def split_into_clauses(text: str, min_len: int = 40) -> List[str]:
|
| 150 |
if not text:
|
| 151 |
return []
|
| 152 |
-
# First try structured numbering/bullets
|
| 153 |
parts = re.split(CLAUSE_SPLIT_REGEX, text)
|
| 154 |
-
# Fallback: sentence-like splits if too few
|
| 155 |
if len(parts) < 2:
|
| 156 |
parts = re.split(r"(?<=[.;])\s+\n?\s*", text)
|
| 157 |
clauses = [p.strip() for p in parts if len(p.strip()) >= min_len]
|
| 158 |
-
# Deduplicate near-identical snippets
|
| 159 |
seen = set()
|
| 160 |
unique = []
|
| 161 |
for c in clauses:
|
|
@@ -166,15 +151,15 @@ def split_into_clauses(text: str, min_len: int = 40) -> List[str]:
|
|
| 166 |
return unique
|
| 167 |
|
| 168 |
# -----------------------------
|
| 169 |
-
#
|
| 170 |
# -----------------------------
|
| 171 |
def simplify_clause(clause: str) -> str:
|
| 172 |
-
system = "You are a legal assistant that rewrites clauses into plain
|
| 173 |
-
user = f"Rewrite
|
| 174 |
return llm_generate(system, user, max_new_tokens=400)
|
| 175 |
|
| 176 |
# -----------------------------
|
| 177 |
-
#
|
| 178 |
# -----------------------------
|
| 179 |
def ner_entities(text: str) -> Dict[str, List[str]]:
|
| 180 |
if not text:
|
|
@@ -183,18 +168,16 @@ def ner_entities(text: str) -> Dict[str, List[str]]:
|
|
| 183 |
out: Dict[str, List[str]] = {}
|
| 184 |
for ent in doc.ents:
|
| 185 |
out.setdefault(ent.label_, []).append(ent.text)
|
| 186 |
-
|
| 187 |
-
out = {k: sorted(set(v)) for k, v in out.items()}
|
| 188 |
-
return out
|
| 189 |
|
| 190 |
# -----------------------------
|
| 191 |
-
#
|
| 192 |
# -----------------------------
|
| 193 |
def extract_clauses(text: str) -> List[str]:
|
| 194 |
return split_into_clauses(text)
|
| 195 |
|
| 196 |
# -----------------------------
|
| 197 |
-
#
|
| 198 |
# -----------------------------
|
| 199 |
DOC_TYPES = [
|
| 200 |
"Non-Disclosure Agreement (NDA)",
|
|
@@ -208,215 +191,21 @@ DOC_TYPES = [
|
|
| 208 |
]
|
| 209 |
|
| 210 |
def classify_document(text: str) -> str:
|
| 211 |
-
system = "You are a legal document classifier.
|
| 212 |
labels = "\n".join(f"- {t}" for t in DOC_TYPES)
|
| 213 |
-
user = f"Classify the
|
| 214 |
resp = llm_generate(system, user, max_new_tokens=200)
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
if scores[best] == 0.0:
|
| 220 |
-
lower = text.lower()
|
| 221 |
-
if "confidential" in lower or "non-disclosure" in lower or "nda" in lower:
|
| 222 |
-
best = "Non-Disclosure Agreement (NDA)"
|
| 223 |
-
elif "lease" in lower or "tenant" in lower or "landlord" in lower:
|
| 224 |
-
best = "Lease Agreement"
|
| 225 |
-
elif "employment" in lower or "employee" in lower or "employer" in lower:
|
| 226 |
-
best = "Employment Contract"
|
| 227 |
-
elif "services" in lower or "service" in lower or "statement of work" in lower:
|
| 228 |
-
best = "Service Agreement"
|
| 229 |
-
return best
|
| 230 |
|
| 231 |
# -----------------------------
|
| 232 |
-
#
|
| 233 |
-
# -----------------------------
|
| 234 |
-
def negotiation_coach(clause: str) -> Tuple[str, List[Dict[str, Any]]]:
|
| 235 |
-
system = "You are an AI negotiation coach for contracts."
|
| 236 |
-
user = (
|
| 237 |
-
"Given the clause below, propose 3 alternative versions ranked by expected acceptance rate. "
|
| 238 |
-
"Provide JSON with fields: alternatives: [ {rank, acceptance_rate_percent, title, clause_text, rationale} ]. "
|
| 239 |
-
"Rank 1 is highest acceptance rate. Keep acceptance_rate_percent as integer. "
|
| 240 |
-
f"\n\nClause:\n{clause}"
|
| 241 |
-
)
|
| 242 |
-
resp = llm_generate(system, user, max_new_tokens=700)
|
| 243 |
-
# Try to extract JSON
|
| 244 |
-
data = None
|
| 245 |
-
try:
|
| 246 |
-
json_str = re.search(r"\{[\s\S]*\}", resp).group(0)
|
| 247 |
-
data = json.loads(json_str)
|
| 248 |
-
except Exception:
|
| 249 |
-
# Try to reconstruct minimal structure
|
| 250 |
-
data = {"alternatives": []}
|
| 251 |
-
# heuristic extraction
|
| 252 |
-
alts = re.split(r"\n\s*\d+[.)]\s*", resp)
|
| 253 |
-
for i, chunk in enumerate(alts[1:4], start=1):
|
| 254 |
-
data["alternatives"].append({
|
| 255 |
-
"rank": i,
|
| 256 |
-
"acceptance_rate_percent": max(50, 90 - (i-1)*10),
|
| 257 |
-
"title": f"Alternative {i}",
|
| 258 |
-
"clause_text": chunk.strip()[:800],
|
| 259 |
-
"rationale": "Heuristic parse from model response."
|
| 260 |
-
})
|
| 261 |
-
pretty = json.dumps(data, indent=2)
|
| 262 |
-
return pretty, data.get("alternatives", [])
|
| 263 |
-
|
| 264 |
-
# -----------------------------
|
| 265 |
-
# Feature: Future Risk Predictor (1–5+ years timeline)
|
| 266 |
-
# -----------------------------
|
| 267 |
-
def future_risk_predictor(clause: str) -> Tuple[str, List[Dict[str, Any]]]:
|
| 268 |
-
system = "You analyze contractual clauses and forecast future risks over time."
|
| 269 |
-
user = (
|
| 270 |
-
"Analyze the clause and forecast risks over the next 1 to 5 years. "
|
| 271 |
-
"Return strict JSON: {timeline: [ {year: int, risk_score_0_100: int, key_risks: [str], mitigation: [str]} ]}. "
|
| 272 |
-
"risk_score_0_100 is an integer. Keep the list length between 5 and 6."
|
| 273 |
-
f"\n\nClause:\n{clause}"
|
| 274 |
-
)
|
| 275 |
-
resp = llm_generate(system, user, max_new_tokens=700)
|
| 276 |
-
data = None
|
| 277 |
-
try:
|
| 278 |
-
json_str = re.search(r"\{[\s\S]*\}", resp).group(0)
|
| 279 |
-
data = json.loads(json_str)
|
| 280 |
-
except Exception:
|
| 281 |
-
data = {"timeline": []}
|
| 282 |
-
for y in range(1, 6):
|
| 283 |
-
data["timeline"].append({
|
| 284 |
-
"year": y,
|
| 285 |
-
"risk_score_0_100": min(95, 40 + y*8),
|
| 286 |
-
"key_risks": ["Heuristic timeline due to JSON parse fallback."],
|
| 287 |
-
"mitigation": ["Seek legal review", "Adjust clause terms", "Add notice/cure period"]
|
| 288 |
-
})
|
| 289 |
-
pretty = json.dumps(data, indent=2)
|
| 290 |
-
return pretty, data["timeline"]
|
| 291 |
-
|
| 292 |
-
# -----------------------------
|
| 293 |
-
# Feature: Fairness Balance Meter (power distribution)
|
| 294 |
-
# -----------------------------
|
| 295 |
-
def fairness_balance_meter(clause: str) -> Tuple[str, int, str]:
|
| 296 |
-
system = "You evaluate which party a clause favors on a 0-100 scale (0=Party A heavily favored, 50=balanced, 100=Party B heavily favored)."
|
| 297 |
-
user = (
|
| 298 |
-
"Return strict JSON: {score_0_100: int, rationale: str, notes: [str]}. "
|
| 299 |
-
"Do not include anything else."
|
| 300 |
-
f"\n\nClause:\n{clause}"
|
| 301 |
-
)
|
| 302 |
-
resp = llm_generate(system, user, max_new_tokens=400)
|
| 303 |
-
try:
|
| 304 |
-
data = json.loads(re.search(r"\{[\s\S]*\}", resp).group(0))
|
| 305 |
-
score = int(data.get("score_0_100", 50))
|
| 306 |
-
rationale = data.get("rationale", "")
|
| 307 |
-
except Exception:
|
| 308 |
-
score, rationale = 50, "Fallback balanced score due to JSON parse."
|
| 309 |
-
data = {"score_0_100": score, "rationale": rationale, "notes": []}
|
| 310 |
-
pretty = json.dumps(data, indent=2)
|
| 311 |
-
return pretty, score, rationale
|
| 312 |
-
|
| 313 |
-
# -----------------------------
|
| 314 |
-
# Feature: Clause Battle Arena (head-to-head)
|
| 315 |
-
# -----------------------------
|
| 316 |
-
def clause_battle_arena(text_a: str, text_b: str) -> Tuple[str, str]:
|
| 317 |
-
system = "You compare two contract drafts across objective criteria and declare an overall winner."
|
| 318 |
-
user = (
|
| 319 |
-
"Compare Document A vs Document B across: Liability, Termination, IP, Payment, Confidentiality, Governing Law. "
|
| 320 |
-
"Return JSON: {rounds: [ {category, winner: 'A'|'B'|'Draw', rationale} ], overall_winner: 'A'|'B'|'Draw', summary: str}.\n"
|
| 321 |
-
f"Document A:\n{text_a[:4000]}\n\nDocument B:\n{text_b[:4000]}"
|
| 322 |
-
)
|
| 323 |
-
resp = llm_generate(system, user, max_new_tokens=900)
|
| 324 |
-
try:
|
| 325 |
-
data = json.loads(re.search(r"\{[\s\S]*\}", resp).group(0))
|
| 326 |
-
except Exception:
|
| 327 |
-
data = {
|
| 328 |
-
"rounds": [
|
| 329 |
-
{"category": "Liability", "winner": "Draw", "rationale": "Fallback"},
|
| 330 |
-
{"category": "Termination", "winner": "Draw", "rationale": "Fallback"},
|
| 331 |
-
{"category": "IP", "winner": "Draw", "rationale": "Fallback"},
|
| 332 |
-
{"category": "Payment", "winner": "Draw", "rationale": "Fallback"},
|
| 333 |
-
{"category": "Confidentiality", "winner": "Draw", "rationale": "Fallback"},
|
| 334 |
-
{"category": "Governing Law", "winner": "Draw", "rationale": "Fallback"},
|
| 335 |
-
],
|
| 336 |
-
"overall_winner": "Draw",
|
| 337 |
-
"summary": "JSON parse fallback."
|
| 338 |
-
}
|
| 339 |
-
pretty = json.dumps(data, indent=2)
|
| 340 |
-
rounds_md = "\n".join([f"- {r['category']}: {r['winner']} — {r.get('rationale','')}" for r in data.get("rounds", [])])
|
| 341 |
-
md = f"Overall Winner: {data.get('overall_winner','Draw')}\n\nRounds:\n{rounds_md}\n\nSummary:\n{data.get('summary','')}"
|
| 342 |
-
return pretty, md
|
| 343 |
-
|
| 344 |
-
# -----------------------------
|
| 345 |
-
# Feature: Sensitive Data Sniffer
|
| 346 |
-
# -----------------------------
|
| 347 |
-
PII_REGEXES = {
|
| 348 |
-
"Email": r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}",
|
| 349 |
-
"Phone": r"\+?\d[\d\-\s]{7,}\d",
|
| 350 |
-
"SSN (US)": r"\b\d{3}-\d{2}-\d{4}\b",
|
| 351 |
-
"Credit Card": r"\b(?:\d[ -]*?){13,16}\b",
|
| 352 |
-
}
|
| 353 |
-
|
| 354 |
-
def sensitive_data_sniffer(text: str) -> Tuple[str, Dict[str, List[str]]]:
|
| 355 |
-
# LLM-based identification of privacy traps plus regex PII
|
| 356 |
-
system = "You find hidden privacy traps in legal text and list personal data categories being shared or processed."
|
| 357 |
-
user = (
|
| 358 |
-
"Return strict JSON: {data_categories: [str], sharing_parties: [str], processing_purposes: [str], risks: [str], recommendations: [str]}.\n"
|
| 359 |
-
f"Text:\n{text[:6000]}"
|
| 360 |
-
)
|
| 361 |
-
resp = llm_generate(system, user, max_new_tokens=700)
|
| 362 |
-
data = None
|
| 363 |
-
try:
|
| 364 |
-
data = json.loads(re.search(r"\{[\s\S]*\}", resp).group(0))
|
| 365 |
-
except Exception:
|
| 366 |
-
data = {
|
| 367 |
-
"data_categories": ["Name", "Email"],
|
| 368 |
-
"sharing_parties": ["Service Provider"],
|
| 369 |
-
"processing_purposes": ["Service delivery"],
|
| 370 |
-
"risks": ["Potential over-collection"],
|
| 371 |
-
"recommendations": ["Narrow purpose", "Limit retention"]
|
| 372 |
-
}
|
| 373 |
-
# Regex-based PII findings
|
| 374 |
-
regex_hits: Dict[str, List[str]] = {}
|
| 375 |
-
for label, pattern in PII_REGEXES.items():
|
| 376 |
-
hits = re.findall(pattern, text or "", flags=re.IGNORECASE)
|
| 377 |
-
if hits:
|
| 378 |
-
regex_hits[label] = sorted(set([h.strip() for h in hits]))
|
| 379 |
-
pretty = json.dumps({"llm": data, "regex_hits": regex_hits}, indent=2)
|
| 380 |
-
return pretty, regex_hits
|
| 381 |
-
|
| 382 |
-
# -----------------------------
|
| 383 |
-
# Feature: Litigation Risk Radar
|
| 384 |
-
# -----------------------------
|
| 385 |
-
def litigation_risk_radar(text: str) -> Tuple[str, str]:
|
| 386 |
-
clauses = split_into_clauses(text)
|
| 387 |
-
sample = "\n\n".join(clauses[:8]) if clauses else text[:4000]
|
| 388 |
-
system = "You identify clauses most likely to trigger disputes or litigation and provide sample dispute scenarios."
|
| 389 |
-
user = (
|
| 390 |
-
"Analyze the clauses and return JSON: {hotspots: [ {clause_excerpt, risk_level: 'Low'|'Medium'|'High', why, sample_dispute_scenario} ]}.\n"
|
| 391 |
-
f"Clauses:\n{sample}"
|
| 392 |
-
)
|
| 393 |
-
resp = llm_generate(system, user, max_new_tokens=900)
|
| 394 |
-
try:
|
| 395 |
-
data = json.loads(re.search(r"\{[\s\S]*\}", resp).group(0))
|
| 396 |
-
except Exception:
|
| 397 |
-
data = {
|
| 398 |
-
"hotspots": [
|
| 399 |
-
{
|
| 400 |
-
"clause_excerpt": (clauses[0][:280] if clauses else text[:280]),
|
| 401 |
-
"risk_level": "Medium",
|
| 402 |
-
"why": "Ambiguous obligations.",
|
| 403 |
-
"sample_dispute_scenario": "Party A alleges non-performance due to unclear milestones."
|
| 404 |
-
}
|
| 405 |
-
]
|
| 406 |
-
}
|
| 407 |
-
pretty = json.dumps(data, indent=2)
|
| 408 |
-
md = "\n".join([
|
| 409 |
-
f"- [{h.get('risk_level','Medium')}] {h.get('clause_excerpt','')}\n Why: {h.get('why','')}\n Scenario: {h.get('sample_dispute_scenario','')}"
|
| 410 |
-
for h in data.get("hotspots", [])
|
| 411 |
-
])
|
| 412 |
-
return pretty, md
|
| 413 |
-
|
| 414 |
-
# -----------------------------
|
| 415 |
-
# Glue: Input handling (upload or paste)
|
| 416 |
# -----------------------------
|
| 417 |
def get_text_from_inputs(file: Optional[gr.File], text: str) -> str:
|
| 418 |
file_text = load_document(file) if file else ""
|
| 419 |
final = (text or "").strip()
|
| 420 |
if len(file_text) > len(final):
|
| 421 |
return file_text
|
| 422 |
-
|
|
|
|
| 3 |
import math
|
| 4 |
import re
|
| 5 |
import io
|
|
|
|
| 6 |
from typing import List, Dict, Tuple, Optional, Any
|
| 7 |
|
| 8 |
import torch
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
from pypdf import PdfReader
|
| 11 |
import docx
|
| 12 |
import spacy
|
| 13 |
import gradio as gr
|
| 14 |
|
| 15 |
# -----------------------------
|
| 16 |
+
# Model: IBM Granite 3.2 2B Instruct (you can swap this for a local HF model)
|
| 17 |
# -----------------------------
|
| 18 |
MODEL_ID = "ibm-granite/granite-3.2-2b-instruct"
|
| 19 |
|
|
|
|
| 35 |
nlp = spacy.load("en_core_web_sm")
|
| 36 |
|
| 37 |
# -----------------------------
|
| 38 |
+
# Chat templating helper
|
| 39 |
# -----------------------------
|
| 40 |
def build_chat_prompt(system_prompt: str, user_prompt: str) -> str:
|
| 41 |
messages = []
|
|
|
|
| 45 |
try:
|
| 46 |
return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 47 |
except Exception:
|
|
|
|
| 48 |
sys = f"[SYSTEM]\n{system_prompt}\n" if system_prompt else ""
|
| 49 |
usr = f"[USER]\n{user_prompt}\n[ASSISTANT]\n"
|
| 50 |
return sys + usr
|
|
|
|
| 52 |
# -----------------------------
|
| 53 |
# LLM generation
|
| 54 |
# -----------------------------
|
| 55 |
+
def llm_generate(system_prompt: str, user_prompt: str, max_new_tokens: int = 512, temperature: float = 0.3, top_p: float = 0.9) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
prompt = build_chat_prompt(system_prompt, user_prompt)
|
| 57 |
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 58 |
with torch.inference_mode():
|
|
|
|
| 65 |
pad_token_id=tokenizer.eos_token_id
|
| 66 |
)
|
| 67 |
full_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
|
|
|
| 68 |
if "[ASSISTANT]" in full_text:
|
| 69 |
return full_text.split("[ASSISTANT]")[-1].strip()
|
|
|
|
| 70 |
if full_text.startswith(prompt):
|
| 71 |
return full_text[len(prompt):].strip()
|
| 72 |
return full_text.strip()
|
|
|
|
| 85 |
return "\n".join(pages).strip()
|
| 86 |
|
| 87 |
def load_text_from_docx(file_obj) -> str:
|
|
|
|
| 88 |
data = file_obj.read()
|
| 89 |
file_obj.seek(0)
|
| 90 |
f = io.BytesIO(data)
|
|
|
|
| 112 |
elif name.endswith(".txt"):
|
| 113 |
return load_text_from_txt(file)
|
| 114 |
else:
|
|
|
|
| 115 |
try:
|
| 116 |
return load_text_from_pdf(file)
|
| 117 |
except Exception:
|
|
|
|
| 137 |
def split_into_clauses(text: str, min_len: int = 40) -> List[str]:
|
| 138 |
if not text:
|
| 139 |
return []
|
|
|
|
| 140 |
parts = re.split(CLAUSE_SPLIT_REGEX, text)
|
|
|
|
| 141 |
if len(parts) < 2:
|
| 142 |
parts = re.split(r"(?<=[.;])\s+\n?\s*", text)
|
| 143 |
clauses = [p.strip() for p in parts if len(p.strip()) >= min_len]
|
|
|
|
| 144 |
seen = set()
|
| 145 |
unique = []
|
| 146 |
for c in clauses:
|
|
|
|
| 151 |
return unique
|
| 152 |
|
| 153 |
# -----------------------------
|
| 154 |
+
# Simplify clause
|
| 155 |
# -----------------------------
|
| 156 |
def simplify_clause(clause: str) -> str:
|
| 157 |
+
system = "You are a legal assistant that rewrites clauses into plain English while preserving legal meaning."
|
| 158 |
+
user = f"Rewrite this clause in plain English:\n\n{clause}"
|
| 159 |
return llm_generate(system, user, max_new_tokens=400)
|
| 160 |
|
| 161 |
# -----------------------------
|
| 162 |
+
# Named Entity Recognition
|
| 163 |
# -----------------------------
|
| 164 |
def ner_entities(text: str) -> Dict[str, List[str]]:
|
| 165 |
if not text:
|
|
|
|
| 168 |
out: Dict[str, List[str]] = {}
|
| 169 |
for ent in doc.ents:
|
| 170 |
out.setdefault(ent.label_, []).append(ent.text)
|
| 171 |
+
return {k: sorted(set(v)) for k, v in out.items()}
|
|
|
|
|
|
|
| 172 |
|
| 173 |
# -----------------------------
|
| 174 |
+
# Clause extraction
|
| 175 |
# -----------------------------
|
| 176 |
def extract_clauses(text: str) -> List[str]:
|
| 177 |
return split_into_clauses(text)
|
| 178 |
|
| 179 |
# -----------------------------
|
| 180 |
+
# Document classification
|
| 181 |
# -----------------------------
|
| 182 |
DOC_TYPES = [
|
| 183 |
"Non-Disclosure Agreement (NDA)",
|
|
|
|
| 191 |
]
|
| 192 |
|
| 193 |
def classify_document(text: str) -> str:
|
| 194 |
+
system = "You are a legal document classifier."
|
| 195 |
labels = "\n".join(f"- {t}" for t in DOC_TYPES)
|
| 196 |
+
user = f"Classify the document into one of these types:\n{labels}\n\nDocument:\n{text[:5000]}"
|
| 197 |
resp = llm_generate(system, user, max_new_tokens=200)
|
| 198 |
+
for t in DOC_TYPES:
|
| 199 |
+
if t.lower() in resp.lower():
|
| 200 |
+
return t
|
| 201 |
+
return "Unclassified"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
# -----------------------------
|
| 204 |
+
# Input Handling
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
# -----------------------------
|
| 206 |
def get_text_from_inputs(file: Optional[gr.File], text: str) -> str:
|
| 207 |
file_text = load_document(file) if file else ""
|
| 208 |
final = (text or "").strip()
|
| 209 |
if len(file_text) > len(final):
|
| 210 |
return file_text
|
| 211 |
+
return final
|