""" MudraForge End-to-End Statutory Parser (Stage 1 4-Expert MoE -> Stage 2 + PPO -> Boundary Pointer Refiner) =========================================================================================================== Takes ANY raw Indian or US statutory tax/commercial law text and outputs: 1. Stage 1 Atomic Entities (10 types: ACTOR_SCOPE, OPERAND, OP, MONEY, RATE, DATE, DURATION, COUNT, XREF, DEFINED_TERM) powered by our 2.5M-token backbone + 4-Expert Token-Level Sparse MoE (93.15% Part / 88.80% Exact F1). 2. Stage 2 Legal Clauses (4 types: COND, RULE_EFFECT, EXCEPTION, INLINE_DEF) powered by Stage 2 + Sequential PPO Actor-Critic + Stage 2B Exact-Boundary Pointer Refiner. 3. Structured Legal Rule Tree binding every Stage 1 atom inside its owning Stage 2 clause + structural completeness audit. Strictly zero regex (AST-audited at startup). All caches pinned to E:\\mudraforge_parser\\cache\\. """ from __future__ import annotations import os import argparse import ast import json from pathlib import Path import sys from typing import Any import torch SRC_DIR = Path(__file__).resolve().parent ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent))) CKPT_DIR = ROOT_DIR / "checkpoints" if str(SRC_DIR) not in sys.path: sys.path.insert(0, str(SRC_DIR)) import core_features as v2 from models import SpecialistAtomicModel, ATOM_TAGS, ATOMIC_LABELS, SCOPE_LABELS, MAX_SEQ_LEN, snap_atomic_boundaries from lexical_encoder import SUBWORD_BUCKETS, char_tensor_bounded, extract_subword_ids from stage1_mask import build_illicit_tensor from train_stage2_clauses import Stage2ScopeSpecialistV3, preprocess_scope_doc from train_stage2_ppo import PPOClauseAgent, extract_stage2_candidate_pool, rollout_episode from train_stage2_refiner import ClauseBoundaryPointerRefiner, build_token_boundary_clues, refine_doc_predictions SINGLE_PUNCT = set("₹$€£,.():;%–-/\"+§") def tokenize_statute_zero_regex(text: str) -> tuple[list[str], list[list[int]]]: """Deterministic zero-regex legal tokenizer matching canonical statutory token/offset rules.""" tokens: list[str] = [] offsets: list[list[int]] = [] n = len(text) i = 0 def _is_word_ch(ch: str) -> bool: return ch.isalnum() or ch == "_" while i < n: ch = text[i] if ch.isspace(): i += 1 continue # 1. Special multi-word phrase: "per cent" / "per centum" (word-bounded) prev_ok = (i == 0) or (not _is_word_ch(text[i - 1])) if prev_ok and text[i:i + 3].lower() == "per" and i + 3 < n and text[i + 3].isspace(): j = i + 3 while j < n and text[j].isspace(): j += 1 if text[j:j + 6].lower() == "centum" and (j + 6 == n or not _is_word_ch(text[j + 6])): tokens.append(text[i:j + 6]) offsets.append([i, j + 6]) i = j + 6 continue if text[j:j + 4].lower() == "cent" and (j + 4 == n or not _is_word_ch(text[j + 4])): tokens.append(text[i:j + 4]) offsets.append([i, j + 4]) i = j + 4 continue # 2. Numeric tokens: DD.MM.YYYY, comma-grouped numbers (1,00,000.50), decimals (12.5) if ch.isdigit(): # Check DD.MM.YYYY j = i while j < n and text[j].isdigit(): j += 1 if 1 <= (j - i) <= 2 and j < n and text[j] == ".": j2 = j + 1 while j2 < n and text[j2].isdigit(): j2 += 1 if 1 <= (j2 - (j + 1)) <= 2 and j2 < n and text[j2] == ".": j3 = j2 + 1 while j3 < n and text[j3].isdigit(): j3 += 1 if (j3 - (j2 + 1)) == 4 and (j3 == n or not _is_word_ch(text[j3])): tokens.append(text[i:j3]) offsets.append([i, j3]) i = j3 continue # Check Indian/US comma-grouped number: 1,00,000 or 50,000.50 if 1 <= (j - i) <= 3 and j < n and text[j] == ",": k = j ok_groups = False while k < n and text[k] == ",": g_s = k + 1 g_e = g_s while g_e < n and text[g_e].isdigit(): g_e += 1 if 2 <= (g_e - g_s) <= 3: ok_groups = True k = g_e else: break if ok_groups: if k < n and text[k] == "." and k + 1 < n and text[k + 1].isdigit(): k += 1 while k < n and text[k].isdigit(): k += 1 if k == n or not _is_word_ch(text[k]): tokens.append(text[i:k]) offsets.append([i, k]) i = k continue # Check simple decimal: 12.5 if j < n and text[j] == "." and j + 1 < n and text[j + 1].isdigit(): k = j + 1 while k < n and text[k].isdigit(): k += 1 if k == n or not _is_word_ch(text[k]): tokens.append(text[i:k]) offsets.append([i, k]) i = k continue # Standard alphanumeric token (e.g. 194Q, 80C, 2025) k = i while k < n and _is_word_ch(text[k]): k += 1 tokens.append(text[i:k]) offsets.append([i, k]) i = k continue # 3. Alphanumeric words (including hyphenated form codes like Form-10B / GSTR-3B) if _is_word_ch(ch): k = i while k < n and text[k].isalpha(): k += 1 if k > i and k < n and text[k] == "-" and k + 1 < n and text[k + 1].isdigit(): k2 = k + 1 while k2 < n and (text[k2].isalnum() or text[k2] == "-"): k2 += 1 if k2 == n or not _is_word_ch(text[k2]): tokens.append(text[i:k2]) offsets.append([i, k2]) i = k2 continue k = i while k < n and _is_word_ch(text[k]): k += 1 tokens.append(text[i:k]) offsets.append([i, k]) i = k continue # 4. Legal punctuation symbols if ch in SINGLE_PUNCT: tokens.append(ch) offsets.append([i, i + 1]) i += 1 return tokens, offsets class MudraForgeStatuteParser: """Unified End-to-End Statutory Parser (Stage 1 MoE -> Stage 2 + PPO -> Boundary Refiner).""" def __init__( self, s1_ckpt_path: Path = CKPT_DIR / "stage1_moe_fold1.pt", s2_ckpt_path: Path = CKPT_DIR / "stage2_clauses_fold1.pt", ppo_ckpt_path: Path = CKPT_DIR / "stage2_ppo_fold1.pt", refiner_ckpt_path: Path | None = CKPT_DIR / "stage2_refiner_fold1.pt", device: torch.device | None = None, ): self.device = device or torch.device("cuda" if torch.cuda.is_available() else "cpu") # 1. Load Stage 1 (4-Expert Token-Level Sparse MoE) s1_ck = torch.load(s1_ckpt_path, map_location=self.device, weights_only=False) self.s1_vocab = s1_ck["word_vocab"] self.s1_model = SpecialistAtomicModel( vocab_size=len(self.s1_vocab), use_subword_v2=True, subword_buckets=s1_ck.get("subword_buckets", SUBWORD_BUCKETS), word_dropout=0.0, anchor_mode=s1_ck.get("anchor_mode", "drop80"), use_bilstm_head=s1_ck.get("use_bilstm_head", True), use_moe_head=s1_ck.get("use_moe_head", False), moe_num_experts=s1_ck.get("moe_num_experts", 4), moe_expert_hidden=s1_ck.get("moe_expert_hidden", 192), ).to(self.device) self.s1_model.load_state_dict(s1_ck["model_state_dict"]) self.s1_model.eval() trans_mask, start_mask, end_mask = v2.build_bilou_transitions(ATOM_TAGS) self.eff_trans = self.s1_model.crf_trans.detach().float() + trans_mask.to(self.device) self.start_mask = start_mask.to(self.device) self.end_mask = end_mask.to(self.device) # 2. Load Stage 2 Backbone s2_ck = torch.load(s2_ckpt_path, map_location=self.device, weights_only=False) self.s2_vocab = s2_ck["word_vocab"] self.s2_model = Stage2ScopeSpecialistV3( vocab_size=len(self.s2_vocab), num_atom_tags=len(ATOM_TAGS), num_atom_coarse=len(ATOMIC_LABELS), num_scope_labels=len(SCOPE_LABELS), d_model=256, nhead=8, num_layers=4, ff_dim=768, dropout=0.0, subword_buckets=s2_ck.get("subword_buckets", SUBWORD_BUCKETS), word_dropout=0.0, anchor_mode=s2_ck.get("anchor_mode", "drop80"), use_moe=s2_ck.get("use_moe", False), ).to(self.device) self.s2_model.load_state_dict(s2_ck["model_state_dict"]) self.s2_model.eval() # 3. Load Stage 2 Sequential PPO Actor-Critic Agent (optional; omit for direct SFT + Refiner) self.ppo_agent: PPOClauseAgent | None = None if ppo_ckpt_path is not None and Path(ppo_ckpt_path).exists(): ppo_ck = torch.load(ppo_ckpt_path, map_location=self.device, weights_only=False) act_in_dim = ppo_ck["agent_state_dict"]["act_mlp.0.weight"].shape[1] - 64 - 14 self.ppo_agent = PPOClauseAgent(emb_dim=128, act_feat_dim=act_in_dim, glob_feat_dim=14, hidden=128).to(self.device) self.ppo_agent.load_state_dict(ppo_ck["agent_state_dict"]) self.ppo_agent.eval() # 4. Load Stage 2B Exact-Boundary Pointer Refiner (optional) self.refiner: ClauseBoundaryPointerRefiner | None = None if refiner_ckpt_path is not None and Path(refiner_ckpt_path).exists(): ref_ck = torch.load(refiner_ckpt_path, map_location=self.device, weights_only=False) self.refiner = ClauseBoundaryPointerRefiner().to(self.device) self.refiner.load_state_dict(ref_ck["refiner_state_dict"]) self.refiner.eval() def parse(self, text: str, doc_id: str = "RAW_STATUTE") -> dict[str, Any]: tokens, offsets = tokenize_statute_zero_regex(text) tokens = tokens[:MAX_SEQ_LEN] offsets = offsets[:MAX_SEQ_LEN] # Stage 1 Inference with torch.no_grad(): w1 = torch.tensor([self.s1_vocab.get(t.lower(), 1) for t in tokens], dtype=torch.long, device=self.device).unsqueeze(0) c1 = torch.tensor([char_tensor_bounded(t) for t in tokens], dtype=torch.long, device=self.device).unsqueeze(0) sw1 = torch.tensor([extract_subword_ids(t) for t in tokens], dtype=torch.long, device=self.device).unsqueeze(0) g1 = v2.extract_28d_discourse_geometry(tokens, offsets, text).to(self.device).unsqueeze(0) ci1 = v2.compute_clause_indices(tokens).to(self.device).unsqueeze(0) ill1 = build_illicit_tensor(tokens, ATOM_TAGS).to(self.device).unsqueeze(0) h1 = self.s1_model.encode(w1, c1, g1, ci1, sw_ids=sw1) s1_logits = (self.s1_model.forward_atom(h1) + ill1).clamp(min=-20.0).float() best_tags = v2._crf_viterbi_decode(s1_logits[0], self.eff_trans, self.start_mask, self.end_mask) raw_atoms, _ = v2.bilou_ids_to_spans_and_violations(best_tags, ATOM_TAGS, tokens=tokens) atoms = snap_atomic_boundaries(raw_atoms, tokens) enriched_atoms = [] for a in atoms: cs, ce = offsets[a["tokStart"]][0], offsets[a["tokEnd"]][1] enriched_atoms.append({ "label": a["label"], "text": text[cs:ce], "tokStart": a["tokStart"], "tokEnd": a["tokEnd"], "charStart": cs, "charEnd": ce, }) # Stage 2 + PPO + Stage 2B Refiner Inference raw_doc = { "id": doc_id, "text": text, "tokens": tokens, "offsets": offsets, "atomic_spans": enriched_atoms, "scope_spans": [], } dp = preprocess_scope_doc(raw_doc, self.s2_vocab, self.device) with torch.no_grad(): h2, ca2 = self.s2_model.encode(dp["w_ids"], dp["c_mat"], dp["sw_ids"], dp["g_feat"], dp["c_idx"], s1_logits) pool = extract_stage2_candidate_pool(self.s2_model, dp, s1_logits, self.device, use_amp=False) if self.ppo_agent is not None: _, base_preds = rollout_episode(self.ppo_agent, pool, self.device, deterministic=True) else: base_preds = pool["raw_sft_preds"] if self.refiner is not None: doc_cache = { "tokens": tokens, "t_lower": dp["t_lower"], "h": h2[0].float().cpu(), "ca": ca2[0].float().cpu(), "clues": build_token_boundary_clues(tokens), } final_clauses = refine_doc_predictions(self.refiner, doc_cache, base_preds, self.device) else: final_clauses = base_preds # Bind Stage 1 atoms inside their owning Stage 2 clauses structured_clauses = [] for cl in sorted(final_clauses, key=lambda x: (x["tokStart"], x["tokEnd"])): ts, te = cl["tokStart"], cl["tokEnd"] cs, ce = offsets[ts][0], offsets[te][1] bound_atoms = [ a for a in enriched_atoms if a["tokStart"] >= ts and a["tokEnd"] <= te ] structured_clauses.append({ "label": cl["label"], "text": text[cs:ce], "tokStart": ts, "tokEnd": te, "prob": round(float(cl.get("prob", 0.0)), 3), "atoms": bound_atoms, }) # Structural completeness audit clause_types = {c["label"] for c in structured_clauses} atom_types = {a["label"] for a in enriched_atoms} is_computable = ( ("RULE_EFFECT" in clause_types or "INLINE_DEF" in clause_types) and ("OP" in atom_types) and bool(atom_types & {"OPERAND", "MONEY", "RATE", "DURATION", "COUNT", "DATE", "XREF"}) ) return { "id": doc_id, "num_tokens": len(tokens), "is_computable_rule": is_computable, "atoms": enriched_atoms, "clauses": structured_clauses, } DEMO_UNSEEN_INDIAN_LAWS = [ ( "UNSEEN_IN_ITA2025_CAPGAIN", "Where the total income of an assessee includes any income chargeable under the head Capital gains arising from the transfer of a long-term capital asset, the tax payable by the assessee shall be calculated at the rate of twelve and a half per cent on such long-term capital gains exceeding one lakh twenty-five thousand rupees in a financial year: Provided that nothing in this section shall apply to transfer of equity shares where securities transaction tax has not been paid.", ), ( "UNSEEN_IN_CGST_ITC_BLOCK", "Notwithstanding anything contained in section 16, where a registered person fails to pay the supplier the value of supply along with tax payable thereon within one hundred and eighty days from the date of issue of invoice, an amount equal to the input tax credit availed shall be added to his output tax liability along with interest at eighteen per cent per annum.", ), ( "UNSEEN_IN_MSMED_INTEREST", "Where any buyer fails to make payment of the amount to the supplier within forty-five days from the day of acceptance, the buyer shall be liable to pay compound interest with monthly rests to the supplier on that amount from the appointed day at three times of the bank rate notified by the Reserve Bank.", ), ] def main() -> None: parser = argparse.ArgumentParser(description="MudraForge End-to-End Indian Statutory Parser") parser.add_argument("--text", type=str, default="", help="Raw statutory text to parse") parser.add_argument("--indian_exp", action="store_true", help="Use Indian Positive-Only Stage 2 checkpoint (90.9% EXCEPTION)") parser.add_argument("--verify_tokenizer", action="store_true", help="Verify zero-regex tokenizer parity against ground_truth_250.json") parser.add_argument("--demo", action="store_true", help="Run live end-to-end parse on 3 unseen Indian computational laws") args = parser.parse_args() # AST zero-regex check with open(__file__, "r", encoding="utf-8") as f: tree = ast.parse(f.read()) for node in ast.walk(tree): if isinstance(node, ast.Import) and any(a.name == "re" for a in node.names): raise RuntimeError("Regex import forbidden!") if isinstance(node, ast.ImportFrom) and node.module == "re": raise RuntimeError("Regex import forbidden!") if args.verify_tokenizer: docs = json.load(open(ROOT_DIR / "data" / "ground_truth_250.json", encoding="utf-8")) exact = 0 for d in docs: toks, offs = tokenize_statute_zero_regex(d["text"]) if toks == d["tokens"] and offs == d["offsets"]: exact += 1 print(f"Zero-Regex Tokenizer Parity on 250 benchmark laws: {exact}/{len(docs)} exact matches.") if args.indian_exp: engine = MudraForgeStatuteParser( s1_ckpt_path=CKPT_DIR / "stage1_moe_fold1.pt", s2_ckpt_path=CKPT_DIR / "stage2_clauses_fold1_posonly.pt", ppo_ckpt_path=CKPT_DIR / "stage2_ppo_fold1_posonly.pt", refiner_ckpt_path=CKPT_DIR / "stage2_refiner_fold1_posonly.pt", ) else: engine = MudraForgeStatuteParser() targets = [("CLI_INPUT", args.text)] if args.text else (DEMO_UNSEEN_INDIAN_LAWS if args.demo or not args.verify_tokenizer else []) for doc_id, txt in targets: res = engine.parse(txt, doc_id=doc_id) print("\n" + "=" * 88) print(f"PARSED LAW: {res['id']} ({res['num_tokens']} tokens | Computable Rule: {res['is_computable_rule']})") print("=" * 88) print("Stage 1 Atoms:") for a in res["atoms"]: print(f" [{a['label']:<12}] {a['text']}") print("\nStage 2 Clauses (with bound Stage 1 atoms):") for c in res["clauses"]: atom_summary = ", ".join(f"{a['label']}='{a['text']}'" for a in c["atoms"][:6]) more = f" (+{len(c['atoms'])-6} more)" if len(c["atoms"]) > 6 else "" print(f" [{c['label']:<11} | p={c['prob']:.2f}] {c['text']}") print(f" -> Atoms: {atom_summary}{more}") if __name__ == "__main__": main()