""" AST-CatalaGen Studio Web Server (Strictly Zero Regex) ==================================================== Dedicated interactive Web Studio & visualization server for AST-CatalaGen. Serves a responsive, dual-column/single-column chat-like UI with: - Rich multi-line statutory text input area (no terminal limits) - Interactive top-to-bottom Rule Lifecycle Flow Diagrams (Mermaid & structured DAG) - Side-by-side Statutory AST (.ast.json) and Literate Catala (.catala_en) views - Tasks, benchmark presets (SARA Gold 20, US IRC, India Tax), queries, and history - Clickable links to disk artifacts (.ast.json, .catala_en, HTML/PDF reports) - Live pipeline stage controls (Stage 1 -> Stage 2B -> Stage 3 Emitter) Uses Python standard library http.server (100% zero external web dependencies). Strictly ZERO regex. Zero emojis. """ from __future__ import annotations from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json import os from pathlib import Path import subprocess import sys import threading import time from typing import Any import urllib.parse import webbrowser from canonical_pipeline import ( MudraForgeCanonicalPipeline, normalize_stage_name, resolve_stage_range, ) from catala_ast_emitter import ( build_statutory_ast, render_catala_source, write_ast_and_catala_artifacts, ) from statutory_diagram import generate_rule_lifecycle_diagram ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent))) STUDIO_EMIT_DIR = ROOT_DIR / "emitted" / "studio" STUDIO_EMIT_DIR.mkdir(parents=True, exist_ok=True) DEFAULT_PORT = 8765 STUDIO_PRESETS: dict[str, dict[str, str]] = { "US_IRC_1_A": { "id": "US_IRC_1_A", "title": "IRC Section 1(a) -- Married Joint Return (5 Progressive Tax Brackets)", "law": "26 U.S. Code Section 1(a)", "category": "US Federal Income Tax", "text": ( "(a) Married individuals filing joint returns and surviving spouses: " "There is hereby imposed on the taxable income of every married individual who makes a single return jointly with his spouse under section 6013, and of every surviving spouse: " "If taxable income is: Not over $36,900, the tax is 15% of taxable income. " "Over $36,900 but not over $89,150, the tax is $5,535, plus 28% of the excess over $36,900. " "Over $89,150 but not over $140,000, the tax is $20,165, plus 31% of the excess over $89,150. " "Over $140,000 but not over $250,000, the tax is $35,928.50, plus 36% of the excess over $140,000. " "Over $250,000, the tax is $75,528.50, plus 39.6% of the excess over $250,000." ), }, "US_IRC_63_A": { "id": "US_IRC_63_A", "title": "IRC Section 63(a) -- Taxable Income Definition & Subsection (b) Exception", "law": "26 U.S. Code Section 63(a)", "category": "US Federal Income Tax", "text": ( "(a) In general: Except as provided in subsection (b), for purposes of this subtitle, " "the term taxable income means gross income minus the deductions allowed by this chapter (other than the standard deduction)." ), }, "US_IRC_63_B": { "id": "US_IRC_63_B", "title": "IRC Section 63(b) -- Non-Itemizers Subtraction Formula", "law": "26 U.S. Code Section 63(b)", "category": "US Federal Income Tax", "text": ( "(b) Individuals who do not itemize deductions: In the case of an individual who does not elect to itemize his deductions for the taxable year, " "for purposes of this subtitle, the term taxable income means adjusted gross income, minus- (1) the standard deduction, and (2) the deduction for personal exemptions provided in section 151." ), }, "US_IRC_68_A": { "id": "US_IRC_68_A", "title": "IRC Section 68(a) -- Itemized Deduction Haircut (Dual-Rate Min Combinator)", "law": "26 U.S. Code Section 68(a)", "category": "US Federal Income Tax", "text": ( "(a) General rule: In the case of an individual whose adjusted gross income exceeds the applicable amount, " "the amount of the itemized deductions otherwise allowable for the taxable year shall be reduced by the lesser of- " "(1) 3 percent of the excess of adjusted gross income over the applicable amount, or " "(2) 80 percent of the amount of the itemized deductions otherwise allowable for such taxable year." ), }, "US_IRC_68_B": { "id": "US_IRC_68_B", "title": "IRC Section 68(b) -- Applicable Amount (Subparagraph Value Lookup Table)", "law": "26 U.S. Code Section 68(b)", "category": "US Federal Income Tax", "text": ( "(b) Applicable amount: (1) In general For purposes of this section, the term \"applicable amount\" means- " "(A) $300,000 in the case of a joint return or a surviving spouse (as defined in section 2(a)), " "(B) $275,000 in the case of a head of household (as defined in section 2(b)), " "(C) $250,000 in the case of an individual who is not married and who is not a surviving spouse or head of household, and " "(D) 1/2 the amount applicable under subparagraph (A) in the case of a married individual filing a separate return. " "For purposes of this paragraph, marital status shall be determined under section 7703." ), }, "US_IRC_68_F": { "id": "US_IRC_68_F", "title": "IRC Section 68(f) -- TCJA Temporary Suspension Date Window", "law": "26 U.S. Code Section 68(f)", "category": "US Federal Income Tax", "text": ( "(f) Section not to apply: This section shall not apply to any taxable year beginning after December 31, 2017, and before January 1, 2026." ), }, "US_IRC_3301": { "id": "US_IRC_3301", "title": "IRC Section 3301 -- Federal Unemployment Tax Act (FUTA) 6% Rate", "law": "26 U.S. Code Section 3301", "category": "US Federal Employment Tax", "text": ( "There is hereby imposed on every employer (as defined in section 3306(a)) for each calendar year an excise tax, " "with respect to having individuals in his employ, equal to 6.0 percent of the total wages (as defined in section 3306(b)) " "paid by him during the calendar year with respect to employment (as defined in section 3306(c))." ), }, "US_IRC_7703_B": { "id": "US_IRC_7703_B", "title": "IRC Section 7703(b) -- Married Individuals Living Apart", "law": "26 U.S. Code Section 7703(b)", "category": "US Federal Income Tax", "text": ( "(b) Certain married individuals living apart: For purposes of those provisions of this title which refer to this subsection, if- " "(1) an individual who is married (within the meaning of subsection (a)) and who files a separate return maintains as his home a household " "which constitutes for more than one-half of the taxable year the principal place of abode of a child, such individual shall not be considered as married." ), }, "IN_ITA_194Q": { "id": "IN_ITA_194Q", "title": "India Income-tax Act Section 194Q -- TDS on Purchase of Goods Exceeding Rs 50 Lakh", "law": "Section 194Q, Income-tax Act, 1961", "category": "India Direct Tax", "text": ( "Any person, being a buyer who is responsible for paying any sum to any resident for purchase of any goods " "of the value or aggregate of such value exceeding fifty lakh rupees in any previous year, shall, at the time of credit " "of such sum to the account of the seller or at the time of payment thereof by any mode, whichever is earlier, " "deduct an amount equal to 0.1 per cent of such sum exceeding fifty lakh rupees as income-tax." ), }, "IN_ITA_194C": { "id": "IN_ITA_194C", "title": "India Income-tax Act Section 194C -- TDS on Payments to Contractors", "law": "Section 194C, Income-tax Act, 1961", "category": "India Direct Tax", "text": ( "Any person responsible for paying any sum to any resident for carrying out any work in pursuance of a contract between the contractor " "and a specified person shall deduct an amount equal to- (i) one per cent where the payment is being made or credit is given to an individual or a Hindu undivided family; " "(ii) two per cent where the payment is being made or credit is given to a person other than an individual or a Hindu undivided family, of such sum as income-tax." ), }, } _SESSION_HISTORY: list[dict[str, Any]] = [] _HISTORY_LOCK = threading.Lock() class StudioRequestHandler(BaseHTTPRequestHandler): """Zero-regex, high-performance request handler for AST-CatalaGen Studio.""" pipeline_ref: MudraForgeCanonicalPipeline | None = None def log_message(self, format: str, *args: Any) -> None: """Suppress noisy default request logs; write to sys.stderr cleanly.""" sys.stderr.write(f"[Studio HTTP] {format % args}\n") def _send_json(self, status: int, data: Any) -> None: raw = json.dumps(data, indent=2, ensure_ascii=False).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(raw))) self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Headers", "Content-Type") self.end_headers() self.wfile.write(raw) def _send_html(self, status: int, html_str: str) -> None: raw = html_str.encode("utf-8") self.send_response(status) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(raw))) self.send_header("Access-Control-Allow-Origin", "*") self.end_headers() self.wfile.write(raw) def do_OPTIONS(self) -> None: self.send_response(200) self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") self.send_header("Access-Control-Allow-Headers", "Content-Type") self.end_headers() def do_GET(self) -> None: parsed = urllib.parse.urlparse(self.path) path = parsed.path query = urllib.parse.parse_qs(parsed.query) if path in ("/", "/index.html", "/studio"): self._send_html(200, _get_studio_html()) return if path == "/api/status": pipe = self.pipeline_ref res = { "status": "online", "app": "AST-CatalaGen Studio v6.1.0", "device": pipe.device if pipe else "unknown", "loaded_stages": list(pipe.loaded_stages) if pipe else [], "statutory_guard": "isAuthorizedToDisburse: false", "zero_regex_safety": True, "history_count": len(_SESSION_HISTORY), } self._send_json(200, res) return if path == "/api/presets": self._send_json(200, list(STUDIO_PRESETS.values())) return if path == "/api/history": with _HISTORY_LOCK: self._send_json(200, list(_SESSION_HISTORY)) return if path == "/api/open": target = query.get("file", [""])[0] if not target: self._send_json(400, {"error": "Missing 'file' parameter"}) return p = Path(target) if not p.exists(): self._send_json(404, {"error": f"File '{target}' not found"}) return try: if sys.platform == "win32": os.startfile(str(p)) elif sys.platform == "darwin": subprocess.run(["open", str(p)], check=False) else: subprocess.run(["xdg-open", str(p)], check=False) self._send_json(200, {"opened": str(p)}) except Exception as exc: self._send_json(500, {"error": f"Failed to open file: {exc}"}) return if path.startswith("/api/artifacts/"): rel_name = path[len("/api/artifacts/"):] art_path = STUDIO_EMIT_DIR / rel_name if art_path.exists() and art_path.is_file(): content = art_path.read_text(encoding="utf-8") if art_path.suffix == ".json": self._send_json(200, json.loads(content)) else: self._send_html(200, f"
{content}")
return
self._send_json(404, {"error": "Artifact not found"})
return
self._send_json(404, {"error": f"Not found: {path}"})
def do_POST(self) -> None:
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
if path == "/api/clear_history":
with _HISTORY_LOCK:
_SESSION_HISTORY.clear()
self._send_json(200, {"cleared": True})
return
if path == "/api/compile":
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length).decode("utf-8")
try:
payload = json.loads(body)
except Exception as exc:
self._send_json(400, {"error": f"Invalid JSON payload: {exc}"})
return
text = str(payload.get("text", "")).strip()
if not text:
self._send_json(400, {"error": "No statutory text provided."})
return
doc_id = str(payload.get("doc_id") or "STATUTE_001").strip()
start_st = normalize_stage_name(str(payload.get("start_stage", "stage1")))
end_st = normalize_stage_name(str(payload.get("end_stage", "stage2b")))
use_mem = bool(payload.get("use_memory", True))
pipe = self.pipeline_ref
if pipe is None:
stages = resolve_stage_range(start_st, end_st)
pipe = MudraForgeCanonicalPipeline(stages=stages, device="auto")
StudioRequestHandler.pipeline_ref = pipe
t0 = time.perf_counter()
run_res = pipe.run_pipeline(
text=text,
doc_id=doc_id,
start_stage=start_st,
end_stage=end_st,
use_memory=use_mem,
)
ast_obj = build_statutory_ast(run_res)
catala_src = render_catala_source(ast_obj)
diagram_data = generate_rule_lifecycle_diagram(ast_obj, run_res)
# Write artifacts to disk
emitted = write_ast_and_catala_artifacts(run_res, emit_dir=STUDIO_EMIT_DIR)
tot_latency_ms = round((time.perf_counter() - t0) * 1000.0, 2)
# Generate lightweight printable HTML report
report_path = STUDIO_EMIT_DIR / f"{doc_id}_report.html"
report_html = _build_standalone_statute_report(doc_id, text, ast_obj, catala_src, diagram_data["mermaid"])
report_path.write_text(report_html, encoding="utf-8")
written_paths = {
"ast_json": str(emitted.get("written", {}).get("ast_json", "")),
"catala_en": str(emitted.get("written", {}).get("catala_en", "")),
"html_report": str(report_path),
}
resp_item = {
"run_id": run_res.get("run_id"),
"timestamp_utc": ast_obj.get("generated_at_utc"),
"doc_id": doc_id,
"text": text,
"latency_ms": tot_latency_ms,
"pipeline_latency_ms": run_res.get("latency_ms", {}),
"stages_executed": run_res.get("stages_executed", []),
"stage_sources": run_res.get("stage_sources", {}),
"device": run_res.get("device", "cuda"),
"token_count": len(run_res.get("tokens", [])),
"ast": ast_obj,
"catala": catala_src,
"diagram": diagram_data,
"review_flags": ast_obj.get("review_flags", []),
"statutory_guard": "isAuthorizedToDisburse: false",
"written_artifacts": written_paths,
}
with _HISTORY_LOCK:
_SESSION_HISTORY.insert(0, resp_item)
if len(_SESSION_HISTORY) > 50:
_SESSION_HISTORY.pop()
self._send_json(200, resp_item)
return
self._send_json(404, {"error": f"Unknown POST endpoint: {path}"})
def _build_standalone_statute_report(
doc_id: str,
text: str,
ast_obj: dict[str, Any],
catala_src: str,
mermaid_code: str,
) -> str:
"""Creates a print-ready standalone HTML report for the compiled statute."""
ast_json_str = json.dumps(ast_obj, indent=2, ensure_ascii=False)
return f"""
{text}
{mermaid_code}
{ast_json_str}
{catala_src}