Spaces:
Running
Running
File size: 14,744 Bytes
96ffb5c a072c5c 96ffb5c a072c5c d8a8338 a072c5c d8a8338 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c d8a8338 a072c5c 96ffb5c d8a8338 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c d8a8338 a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c d8a8338 96ffb5c d8a8338 96ffb5c a072c5c d8a8338 a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c d8a8338 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c a072c5c 96ffb5c | 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 320 321 322 323 | # DEPENDENCIES
import re
import os
from typing import List
from typing import Dict
from typing import Tuple
from pathlib import Path
class ContractValidator:
"""
Validate if document is a legal contract
"""
# File constraints
MIN_CONTRACT_LENGTH = 500
MAX_CONTRACT_LENGTH = 500000 # 500KB text
# Strong indicators of legal contracts (keyword: weight)
STRONG_INDICATORS = {'agreement' : 3,
'contract' : 3,
'party' : 2,
'parties' : 2,
'whereas' : 5,
'hereinafter' : 5,
'witnesseth' : 5,
'indemnification' : 4,
'liability' : 3,
'confidentiality' : 3,
'termination' : 3,
'governing law' : 4,
'jurisdiction' : 3,
'warranty' : 3,
'representation' : 3,
'covenant' : 4,
'clause' : 3,
'section' : 2,
'article' : 2,
'hereby' : 3,
'undersigned' : 4,
'executed' : 3,
'consideration' : 4,
'effective date' : 3,
'in witness whereof' : 5,
'binding' : 3,
'enforceable' : 3,
'obligations' : 2,
'employment' : 3,
'employee' : 2,
'employer' : 2,
'probation' : 3,
'salary' : 2,
'compensation' : 3,
'non-compete' : 4,
'non-solicit' : 4,
'remuneration' : 3,
'indemnity' : 3,
'intellectual property' : 4,
'confidential' : 2,
'proprietary' : 2,
'post-termination' : 3,
'agrees to' : 2,
'shall not' : 2,
'agrees and accepts' : 3,
'subject to' : 1,
'in accordance with' : 2,
}
# Anti-patterns (things that indicate NOT a contract)
ANTI_PATTERNS = {'case law' : 5,
'plaintiff' : 5,
'defendant' : 5,
'supreme court' : 5,
'appellate court' : 5,
'court held' : 5,
'legal opinion' : 4,
'court of appeals' : 5,
'trial court' : 5,
'article written by' : 4,
'blog post' : 5,
'this article' : 3,
'author:' : 3,
'published in' : 3,
'journal of' : 3,
'abstract:' : 4,
'introduction:' : 3,
'conclusion:' : 3,
'table of contents' : 4,
'bibliography' : 4,
'references:' : 3,
'chapter' : 2,
'section i.' : 2,
'section ii.' : 2,
}
@staticmethod
def is_valid_contract(text: str, min_length: int = None) -> Tuple[bool, str, str]:
"""
Comprehensive contract validation with relaxed thresholds
Arguments:
----------
text { str } : Document text to validate
min_length { int } : Minimum length override (optional)
Returns:
--------
{ tuple } : (is_valid, validation_type, message) tuple
"""
min_length = min_length or ContractValidator.MIN_CONTRACT_LENGTH
text_lower = text.lower().strip()
# Length Validation
if (len(text_lower) < min_length):
return (False, "too_short", f"Text too short ({len(text_lower)} chars, minimum {min_length}). This is likely a snippet, not a full contract.")
if (len(text_lower) > ContractValidator.MAX_CONTRACT_LENGTH):
return (False, "too_long", f"Text too long ({len(text_lower)} chars, maximum {ContractValidator.MAX_CONTRACT_LENGTH}). This may be a contract bundle or combined document.")
# Anti-pattern Check (Prevent False Positives)
anti_score = 0
found_anti_patterns = list()
for pattern, weight in ContractValidator.ANTI_PATTERNS.items():
if pattern in text_lower:
anti_score += weight
found_anti_patterns.append(pattern)
# More strict anti-pattern check
if (anti_score >= 10): # Reduced from 15
return (False, "not_contract", f"The provided document does not appear to be a legal contract. Please upload a valid contract for analysis.")
# Positive Indicator Scoring
score = 0
found_indicators = list()
for indicator, weight in ContractValidator.STRONG_INDICATORS.items():
if indicator in text_lower:
score += weight
found_indicators.append(indicator)
# Structural Pattern Analysis
structural_score = ContractValidator._check_structural_patterns(text = text_lower)
score += structural_score
# Signature Block Check
has_signature_block = ContractValidator._has_signature_block(text = text_lower)
if has_signature_block:
score += 5
found_indicators.append("signature block")
# Effective Date Check
has_effective_date = ContractValidator._has_effective_date(text = text)
if has_effective_date:
score += 3
found_indicators.append("effective date")
# Party Identification Check
has_parties = ContractValidator._has_party_identification(text = text)
if has_parties:
score += 4
found_indicators.append("party identification")
# Validation Thresholds
if (score >= 50):
return (True, "high_confidence", f"Strong contract indicators detected (score: {score}). This is highly likely a legal contract.")
elif (score >= 40): # Reduced from 15 (now accepts lower confidence)
return (True, "medium_confidence", f"Contract indicators present (score: {score}). This appears to be a contract.")
elif (score >= 25):
return (True, "low_confidence", f"Some contract indicators present (score: {score}). Proceeding with analysis.")
else:
return (False, "not_contract", f"The provided document does not appear to be a legal contract. Please upload a valid contract for analysis.")
@staticmethod
def _check_structural_patterns(text: str) -> int:
"""
Check for structural patterns unique to contracts
"""
score = 0
patterns = [(r'in\s+consideration\s+of', 3),
(r'now,?\s+therefore', 3),
(r'agree\s+as\s+follows', 3),
(r'in\s+witness\s+whereof', 4),
(r'this\s+agreement.*(?:made|entered)', 3),
(r'between.*and.*(?:collectively|hereinafter)', 3),
(r'effective\s+as\s+of', 2),
(r'signed.*presence\s+of', 2),
(r'intending\s+to\s+be\s+legally\s+bound', 4),
(r'mutually\s+agree', 2),
(r'terms\s+and\s+conditions', 2),
]
for pattern, weight in patterns:
if re.search(pattern, text, re.IGNORECASE):
score += weight
return score
@staticmethod
def _has_signature_block(text: str) -> bool:
"""
Check for signature block patterns
"""
signature_patterns = [r'signature:?\s*_+',
r'signed:?\s*_+',
r'by:?\s*_+',
r'name:?\s*_+.*title:?\s*_+',
r'\[signature\]',
r'\[seal\]',
r'authorized\s+signatory',
r'in\s+witness\s+whereof.*executed',
]
return any(re.search(p, text, re.IGNORECASE) for p in signature_patterns)
@staticmethod
def _has_effective_date(text: str) -> bool:
"""
Check for effective date patterns
"""
date_patterns = [r'effective\s+(?:date|as\s+of)',
r'dated\s+as\s+of',
r'this\s+\d+(?:st|nd|rd|th)?\s+day\s+of',
r'(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2},?\s+\d{4}',
r'commencement\s+date',
r'execution\s+date',
]
return any(re.search(p, text, re.IGNORECASE) for p in date_patterns)
@staticmethod
def _has_party_identification(text: str) -> bool:
"""
Check if parties are clearly identified
"""
party_patterns = [r'between.*and.*\(.*".*"\)',
r'party\s+[a-z]\s*[:\-]',
r'(?:the\s+)?(?:employer|employee|consultant|contractor|client|vendor|landlord|tenant|buyer|seller)',
r'hereinafter\s+referred\s+to\s+as',
r'\("(?:the\s+)?(?:company|employee|consultant)"\)',
r'first\s+party.*second\s+party',
]
return any(re.search(p, text, re.IGNORECASE) for p in party_patterns)
@staticmethod
def validate_file_integrity(file_path: str) -> Tuple[bool, str]:
"""
Validate file isn't corrupted and is readable
"""
try:
file_path = Path(file_path)
if not file_path.exists():
return False, "File does not exist"
file_size = file_path.stat().st_size
if (file_size == 0):
return False, "File is empty (0 bytes)"
if (file_size < 1024):
return (False, f"File suspiciously small ({file_size} bytes)")
with open(file_path, 'rb') as f:
first_kb = f.read(1024)
if (b'\x00' * 10 in first_kb):
return (False, "File appears corrupted (contains null bytes)")
return (True, "File integrity OK")
except PermissionError:
return (False, "Permission denied - cannot read file")
except Exception as e:
return (False, f"File integrity check failed: {repr(e)}")
@staticmethod
def get_validation_report(text: str) -> Dict[str, any]:
"""
Get detailed validation report with scores and findings
"""
is_valid, validation_type, message = ContractValidator.is_valid_contract(text = text)
text_lower = text.lower()
# Calculate individual scores
indicator_score = sum(weight for indicator, weight in ContractValidator.STRONG_INDICATORS.items() if indicator in text_lower)
anti_score = sum(weight for pattern, weight in ContractValidator.ANTI_PATTERNS.items() if pattern in text_lower)
structural_score = ContractValidator._check_structural_patterns(text = text_lower)
# Collect found indicators
found_indicators = [indicator for indicator in ContractValidator.STRONG_INDICATORS.keys() if indicator in text_lower]
found_anti_patterns = [pattern for pattern in ContractValidator.ANTI_PATTERNS.keys() if pattern in text_lower]
return {"is_valid" : is_valid,
"validation_type" : validation_type,
"message" : message,
"scores" : {"total" : indicator_score + structural_score,
"indicators" : indicator_score,
"structural" : structural_score,
"anti_patterns" : anti_score,
},
"features" : {"has_signature_block" : ContractValidator._has_signature_block(text = text_lower),
"has_effective_date" : ContractValidator._has_effective_date(text = text),
"has_party_identification" : ContractValidator._has_party_identification(text = text),
},
"found_indicators" : found_indicators,
"found_anti_patterns" : found_anti_patterns,
"text_statistics" : {"length" : len(text),
"word_count" : len(text.split()),
"line_count" : len(text.split('\n')),
}
} |