law2code / src /catala_tree_router.py
yamero999's picture
feat: initialize law2code statutory studio on Gradio
7215e83 verified
Raw History Blame Contribute Delete
5.16 kB
"""
Zero-Regex Hierarchical Catala/USVM Tree Router
================================================
Routes extracted statutory spans and coarse branch types (NUMERIC_METRIC,
CATEGORY_FILTER, DOC_POINTER, COMPLIANCE_ATTESTATION) down to exact, deterministic
Catala variables, declarations, and USVM fact keys.
Guarantees 100% key invariance and safe custom fallbacks for novel statutory terms.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
SCHEMA_PATH = Path(__file__).resolve().parent.parent / "data" / "taxonomy_catala_tree.json"
_TREE_DATA: dict[str, Any] | None = None
def get_taxonomy_tree() -> dict[str, Any]:
global _TREE_DATA
if _TREE_DATA is None:
if not SCHEMA_PATH.exists():
raise FileNotFoundError(f"Missing taxonomy tree: {SCHEMA_PATH}")
_TREE_DATA = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
return _TREE_DATA
DETERMINER_STOPWORDS = frozenset({
"any", "such", "the", "a", "an", "all", "of", "in", "to", "for", "by", "under", "on", "it", "is"
})
def _clean_and_snake_case(text: str) -> str:
"""Zero-regex stopword stripping and snake_casing for safe novel statutory terms."""
words = [w.lower().strip(" ,.;:\"'()[]{}") for w in text.split()]
meaningful = [w for w in words if w and w not in DETERMINER_STOPWORDS]
if not meaningful:
meaningful = [w for w in words if w]
return "_".join(meaningful) if meaningful else "unnamed_variable"
def route_to_catala_leaf(span_text: str, branch_label: str) -> dict[str, Any]:
"""
Descends the taxonomy tree to pick the exact Catala variable, declaration,
and USVM key. Falls back safely if the leaf is not in the predefined dictionary.
"""
tree = get_taxonomy_tree()
branches = tree.get("branches", {})
branch = branches.get(branch_label)
clean_text = span_text.lower().strip()
if not branch:
# Fallback to general custom metric
var_name = _clean_and_snake_case(clean_text)
return {
"branch": branch_label,
"leaf_id": "UNKNOWN_BRANCH_FALLBACK",
"catala_type": "money",
"catala_variable": var_name,
"catala_declaration": f"data {var_name} content money",
"usvm_key": var_name,
"is_custom_fallback": True,
}
catala_type = branch.get("catala_type", "money")
leaves = branch.get("leaves", [])
# 1. Exact or Substring Keyword Matching in this Branch
best_leaf = None
best_match_score = 0
clean_padded = f" {clean_text} "
for leaf in leaves:
for kw in leaf.get("keywords", []):
kw_low = kw.lower()
kw_padded = f" {kw_low} "
score = 0
if kw_low == clean_text:
score = 2000 + len(kw_low)
elif kw_padded in clean_padded:
score = 1000 + len(kw_low)
elif clean_padded in kw_padded and len(clean_text) >= 4:
score = 500 + len(clean_text)
elif kw_low in clean_text and len(kw_low) >= 4:
score = 100 + len(kw_low)
if score > best_match_score:
best_match_score = score
best_leaf = leaf
if best_leaf:
return {
"branch": branch_label,
"leaf_id": best_leaf["leaf_id"],
"catala_type": catala_type,
"catala_variable": best_leaf.get("catala_variable", ""),
"catala_declaration": best_leaf.get("catala_declaration") or best_leaf.get("catala_binding", ""),
"catala_binding": best_leaf.get("catala_binding", ""),
"usvm_key": best_leaf.get("usvm_fact_key") or best_leaf.get("usvm_guard_field") or best_leaf.get("usvm_attestation_key") or "",
"is_custom_fallback": False,
}
# 2. Safe Fallback Leaf
var_name = _clean_and_snake_case(clean_text)
if branch_label == "CATEGORY_FILTER":
full_var = f"is_{var_name}"
return {
"branch": branch_label,
"leaf_id": "FILTER_CUSTOM",
"catala_type": "boolean",
"catala_variable": full_var,
"catala_declaration": f"data {full_var} content boolean",
"usvm_key": full_var,
"is_custom_fallback": True,
}
elif branch_label == "DOC_POINTER":
return {
"branch": branch_label,
"leaf_id": "SCOPE_CUSTOM",
"catala_type": "scope_reference",
"catala_variable": f"in.{var_name}",
"catala_declaration": f"in.{var_name}",
"usvm_key": var_name,
"is_custom_fallback": True,
}
else:
return {
"branch": branch_label,
"leaf_id": "BASE_CUSTOM",
"catala_type": "money",
"catala_variable": var_name,
"catala_declaration": f"data {var_name} content money",
"usvm_key": var_name,
"is_custom_fallback": True,
}