law2code / src /stage1_rules.py
yamero999's picture
feat: initialize law2code statutory studio on Gradio
7215e83 verified
Raw History Blame Contribute Delete
7.93 kB
"""
Audit Proposed Illicit Constraints Against 100% Ground Truth
============================================================
Checks that NO ground truth token is ever masked by proposed illicit state constraints.
Zero regex, 100% real statutory law.
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent)))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import core_features as v2
from models import ATOM_TAGS
DATA_PATH = ROOT_DIR / "data" / "ground_truth_250.json"
PUNCT_ONLY_CHARS = set(".,;:?!()[]{}\"'-/\\—–`*")
STOPWORDS = {
"the", "a", "an", "of", "and", "or", "in", "by", "at", "for", "with", "from", "on", "as", "to", "than", "is", "are", "was", "were", "be", "been", "being"
}
MODAL_AUXILIARIES = {
"shall", "may", "must", "will", "would", "should", "cannot", "need"
}
NUMBER_WORDS = {
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety", "hundred", "thousand", "lakh", "crore", "million", "billion",
"nil", "zero", "first", "second", "third", "fourth", "fifth",
"single", "multiple", "both", "twice", "thrice", "half", "double"
}
INANIMATE_FINANCIAL_NOUNS = {
"turnover", "sales", "invoice", "invoices", "rent", "rents", "salary",
"salaries", "dividend", "dividends", "interest", "royalty", "royalties",
"consideration", "cost", "costs", "challan", "challans",
}
ANIMATE_ACTOR_HEADS = {
"assessee", "assessees", "authority", "bank", "buyer", "buyers",
"child", "children", "citizen", "citizens", "companies", "company",
"contractor", "contractors", "corporation", "corporations", "dealer",
"decedent", "director", "directors", "employee", "employees",
"employer", "employers", "estates", "government", "husband",
"individual", "individuals", "member", "members", "officer",
"partner", "partners", "partnership", "partnerships", "payee", "payees",
"payer", "payers", "person", "persons", "recipient", "recipients",
"resident", "residents", "seller", "sellers", "shareholder",
"shareholders", "spouse", "spouses", "supplier", "suppliers",
"taxpayer", "taxpayers", "transferee", "transferees", "transferor",
"transferors", "trustee", "trustees", "wife",
}
OPEN_PREPS = {
"of", "to", "for", "in", "by", "under", "with", "from", "at", "on", "into", "through", "during"
}
CLAUSE_DELIM_PUNCT = {",", ";", ":"}
START_PREPS = {"of", "at", "into", "through"}
def is_illicit(tok: str, tag: str) -> bool:
"""Return True if assigning `tag` to `tok` is strictly impossible in statutory law."""
t_lower = tok.lower()
is_pure_punct = len(tok) > 0 and all(c in PUNCT_ONLY_CHARS for c in tok)
has_digit = any(c.isdigit() for c in tok)
has_num_word = t_lower in NUMBER_WORDS
has_currency = any(c in tok for c in ("₹", "$", "€", "£"))
has_percent = "%" in tok or t_lower in ("percent", "per cent", "percentum")
has_numeric_content = has_digit or has_num_word or has_currency or has_percent
pfx, lbl = v2._split_tag(tag)
# 1. Pure punctuation constraints:
# A standalone punctuation token can NEVER be a unit entity (single token entity) of any type
if is_pure_punct:
if pfx == "U":
return True
# Pure punctuation can never start an actor, operand, money, rate, or date
if pfx == "B" and lbl in ("ACTOR_SCOPE", "OPERAND", "MONEY", "RATE", "DATE", "COUNT"):
return True
# 2. Stopwords can never be single-token unit entities
if t_lower in STOPWORDS and pfx == "U":
return True
# 3. Modal auxiliaries can never be ACTOR_SCOPE, OPERAND, MONEY, RATE, COUNT, DATE, DURATION, DEFINED_TERM
if t_lower in MODAL_AUXILIARIES:
if lbl in ("ACTOR_SCOPE", "OPERAND", "MONEY", "RATE", "COUNT", "DATE", "DURATION", "DEFINED_TERM"):
return True
# 4. Inanimate financial nouns can NEVER be ACTOR_SCOPE (they are strictly OPERAND or background)
if t_lower in INANIMATE_FINANCIAL_NOUNS and lbl == "ACTOR_SCOPE":
return True
# 4B. Pure animate/legal-entity actor head nouns can NEVER terminate an OPERAND span (L/U-OPERAND)
# (Still allows pre-nominal modifiers like B-OPERAND in 'Children education allowance'.)
if t_lower in ANIMATE_ACTOR_HEADS and pfx in ("L", "U") and lbl == "OPERAND":
return True
# 5. Single-token Unit MONEY must have numeric or currency content
if pfx == "U" and lbl == "MONEY":
if not (has_digit or has_currency or has_num_word):
return True
# 6. Open prepositions can NEVER terminate a non-OP entity (Syntactic Head Rule)
if t_lower in OPEN_PREPS and pfx in ("L", "U") and lbl in ("OPERAND", "ACTOR_SCOPE", "MONEY", "RATE", "DATE", "COUNT", "DEFINED_TERM", "XREF"):
return True
# 7. Pure clause delimiter punctuation (comma, semicolon, colon) can NEVER start or end ANY entity
if tok in CLAUSE_DELIM_PUNCT and pfx in ("B", "L", "U"):
return True
# 8. Semicolon separates distinct rules and can NEVER be inside ANY entity
if tok == ";" and lbl != "O":
return True
# 9. Start prepositions can NEVER start or be an entity
if t_lower in START_PREPS and pfx in ("B", "U") and lbl in ("OPERAND", "ACTOR_SCOPE", "DEFINED_TERM"):
return True
# 10. Standalone digits and cardinal/ordinal number words can NEVER be ACTOR_SCOPE;
# standalone digits can never start or end OP
if (tok.isdigit() or t_lower in NUMBER_WORDS) and lbl == "ACTOR_SCOPE":
return True
if tok.isdigit() and pfx in ("B", "L", "U") and lbl == "OP":
return True
return False
def main():
data_path = Path(sys.argv[1]) if len(sys.argv) > 1 else DATA_PATH
with open(data_path, "r", encoding="utf-8") as f:
docs = json.load(f)
tag_to_id = {t: i for i, t in enumerate(ATOM_TAGS)}
total_tokens = 0
total_spans = 0
violations = []
for d_idx, d in enumerate(docs):
tokens = d["tokens"]
T = len(tokens)
total_tokens += T
gold_tag_ids = ["O"] * T
for a in d.get("atomic_spans", []):
total_spans += 1
s, e, lbl = a["tokStart"], a["tokEnd"], a["label"]
if s == e:
gold_tag_ids[s] = f"U-{lbl}"
else:
gold_tag_ids[s] = f"B-{lbl}"
for k in range(s + 1, e):
gold_tag_ids[k] = f"I-{lbl}"
gold_tag_ids[e] = f"L-{lbl}"
for t_idx, (tok, gold_tag) in enumerate(zip(tokens, gold_tag_ids)):
if is_illicit(tok, gold_tag):
violations.append({
"doc_id": d.get("id", d_idx),
"token_idx": t_idx,
"token": tok,
"gold_tag": gold_tag,
"context": " ".join(tokens[max(0, t_idx - 3): min(T, t_idx + 4)]),
})
print(f"Total Documents: {len(docs)}")
print(f"Total Tokens: {total_tokens}")
print(f"Total Atomic Spans: {total_spans}")
print(f"Violations Found: {len(violations)}")
if violations:
print("\n--- VIOLATIONS LIST ---")
for v in violations[:20]:
print(f"Doc {v['doc_id']} | Tok [{v['token']}] | Gold Tag: {v['gold_tag']} | Context: {v['context']}")
else:
print("\n>>> AUDIT PASSED: 100% Zero False Constraints across all 250 Statutory Laws! <<<")
if __name__ == "__main__":
main()