law2code / src /studio_server.py
yamero999's picture
feat: initialize law2code statutory studio on Gradio
7215e83 verified
Raw History Blame Contribute Delete
52.1 kB
""" 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"<pre>{content}</pre>") 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"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MudraForge Statutory AST Report - {doc_id}</title> <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script> <style> body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #0b0f19; color: #f1f5f9; padding: 2rem; margin: 0; }} h1, h2, h3 {{ color: #38bdf8; }} .badge {{ display: inline-block; padding: 0.25rem 0.6rem; border-radius: 4px; font-size: 0.85rem; font-weight: bold; background: #1e293b; color: #10b981; border: 1px solid #334155; margin-right: 0.5rem; }} .badge.warn {{ color: #f59e0b; border-color: #f59e0b; }} .box {{ background: #111827; border: 1px solid #1f2937; border-radius: 8px; padding: 1.25rem; margin-bottom: 1.5rem; }} pre {{ background: #030712; padding: 1rem; border-radius: 6px; overflow-x: auto; color: #a5f3fc; font-size: 0.9rem; line-height: 1.4; }} .grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }} @media print {{ body {{ background: #fff; color: #000; }} pre {{ background: #f8fafc; color: #000; }} }} </style> </head> <body> <h1>MudraForge Formal Statutory Compiler Report</h1> <div> <span class="badge">Doc ID: {doc_id}</span> <span class="badge">Pipeline: v6.1.0-prod</span> <span class="badge warn">isAuthorizedToDisburse: false (Statutory Invariant)</span> <span class="badge">Zero-Regex Verified</span> </div> <h2>1. Raw Statutory Text</h2> <div class="box"> <p style="white-space: pre-wrap; font-family: Georgia, serif; line-height: 1.6;">{text}</p> </div> <h2>2. Statutory Rule Lifecycle Flow Diagram</h2> <div class="box"> <pre class="mermaid"> {mermaid_code} </pre> </div> <h2>3. Emitted Formal Specifications</h2> <div class="grid"> <div class="box"> <h3>Formal Statutory AST (.ast.json)</h3> <pre><code>{ast_json_str}</code></pre> </div> <div class="box"> <h3>Literate INRIA Catala (.catala_en)</h3> <pre><code>{catala_src}</code></pre> </div> </div> <script> mermaid.initialize({{ startOnLoad: true, theme: 'dark' }}); </script> </body> </html> """ def _get_studio_html() -> str: """Returns the embedded single-page application for AST-CatalaGen Studio.""" return """<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AST-CatalaGen Studio | MudraForge Formal Legal Engine</title> <!-- Mermaid.js for visual rule flowcharts --> <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script> <style> :root { --bg: #090d16; --bg-panel: #0f172a; --bg-card: #131d34; --bg-code: #050811; --border: #1e293b; --border-accent: #0284c7; --primary: #38bdf8; --primary-hover: #0ea5e9; --emerald: #10b981; --amber: #f59e0b; --rose: #f43f5e; --purple: #a855f7; --text: #f8fafc; --text-muted: #94a3b8; --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } * { box-sizing: border-box; margin: 0; padding: 0; } body { background-color: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; height: 100vh; display: flex; flex-direction: column; overflow: hidden; } /* Top Config & Brand Bar */ header { background: #060911; border-bottom: 1px solid var(--border); padding: 0.65rem 1.25rem; display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-shrink: 0; } .brand { display: flex; align-items: center; gap: 0.75rem; } .brand-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -0.02em; color: var(--primary); text-transform: uppercase; } .brand-sub { font-size: 0.78rem; color: var(--text-muted); background: #1e293b; padding: 0.15rem 0.5rem; border-radius: 4px; border: 1px solid #334155; } .top-controls { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; } .badge { display: inline-flex; align-items: center; gap: 0.35rem; font-size: 0.75rem; font-weight: 600; padding: 0.2rem 0.6rem; border-radius: 4px; background: var(--bg-card); border: 1px solid var(--border); color: var(--text-muted); } .badge.green { color: var(--emerald); border-color: rgba(16, 185, 129, 0.4); } .badge.amber { color: var(--amber); border-color: rgba(245, 158, 11, 0.4); } .badge.blue { color: var(--primary); border-color: rgba(56, 189, 248, 0.4); } .badge.guard { color: var(--purple); border-color: rgba(168, 85, 247, 0.4); background: rgba(168, 85, 247, 0.08); } .btn { background: var(--bg-card); color: var(--text); border: 1px solid var(--border); padding: 0.35rem 0.75rem; border-radius: 6px; font-size: 0.8rem; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 0.4rem; transition: all 0.15s ease; } .btn:hover { background: #1e293b; border-color: var(--primary); } .btn-primary { background: #0284c7; color: #fff; border-color: #38bdf8; } .btn-primary:hover { background: #0369a1; } .btn-emerald { background: rgba(16, 185, 129, 0.15); color: var(--emerald); border-color: rgba(16, 185, 129, 0.5); } .btn-emerald:hover { background: rgba(16, 185, 129, 0.25); } /* Main Layout */ .app-body { display: flex; flex: 1; height: calc(100vh - 58px); overflow: hidden; } /* Left Sidebar: Tasks, Presets, History */ aside { width: 320px; background: #0a0e1a; border-right: 1px solid var(--border); display: flex; flex-direction: column; flex-shrink: 0; } .sidebar-tabs { display: flex; border-bottom: 1px solid var(--border); background: #060911; } .sidebar-tab { flex: 1; padding: 0.65rem; text-align: center; font-size: 0.8rem; font-weight: 700; color: var(--text-muted); cursor: pointer; border-bottom: 2px solid transparent; transition: all 0.15s ease; } .sidebar-tab.active { color: var(--primary); border-bottom-color: var(--primary); background: rgba(56, 189, 248, 0.05); } .sidebar-content { flex: 1; overflow-y: auto; padding: 0.75rem; } .preset-card, .history-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 6px; padding: 0.75rem; margin-bottom: 0.6rem; cursor: pointer; transition: all 0.15s ease; } .preset-card:hover, .history-card:hover { border-color: var(--primary); transform: translateY(-1px); } .preset-title, .history-title { font-size: 0.85rem; font-weight: 700; color: var(--primary); margin-bottom: 0.25rem; } .preset-law { font-size: 0.72rem; color: var(--emerald); margin-bottom: 0.35rem; } .preset-snippet, .history-snippet { font-size: 0.75rem; color: var(--text-muted); line-height: 1.35; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } /* Central Content Area */ main { flex: 1; display: flex; flex-direction: column; height: 100%; background: var(--bg); overflow: hidden; } /* Input Workspace Header */ .input-workspace { background: #0c1222; border-bottom: 1px solid var(--border); padding: 0.85rem 1.25rem; display: flex; flex-direction: column; gap: 0.6rem; flex-shrink: 0; } .input-header-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; } .field-group { display: flex; align-items: center; gap: 0.5rem; } .field-label { font-size: 0.75rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; } input[type="text"], select { background: #050811; border: 1px solid var(--border); color: var(--text); padding: 0.35rem 0.6rem; border-radius: 4px; font-size: 0.82rem; font-family: var(--font-mono); outline: none; } input[type="text"]:focus, select:focus, textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 1px rgba(56, 189, 248, 0.3); } .textarea-wrapper { position: relative; } textarea { width: 100%; height: 95px; min-height: 80px; max-height: 220px; background: #050811; border: 1px solid var(--border); color: #e2e8f0; padding: 0.65rem; border-radius: 6px; font-family: Georgia, serif; font-size: 0.95rem; line-height: 1.45; resize: vertical; outline: none; } .input-actions-row { display: flex; align-items: center; justify-content: space-between; } .input-counters { font-size: 0.75rem; color: var(--text-muted); } /* Scrollable Timeline Stream */ .timeline-stream { flex: 1; overflow-y: auto; padding: 1.25rem; display: flex; flex-direction: column; gap: 1.25rem; } /* Execution Card in Stream */ .timeline-card { background: var(--bg-panel); border: 1px solid var(--border); border-radius: 8px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4); display: flex; flex-direction: column; overflow: hidden; animation: fadeIn 0.25s ease-out; } @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } } .card-top { background: #0d1527; border-bottom: 1px solid var(--border); padding: 0.65rem 1rem; display: flex; align-items: center; justify-content: space-between; gap: 1rem; } .card-doc-info { display: flex; align-items: center; gap: 0.6rem; } .card-doc-id { font-size: 0.95rem; font-weight: 800; color: var(--primary); font-family: var(--font-mono); } .card-source-panel { padding: 0.75rem 1rem; background: rgba(15, 23, 42, 0.6); border-bottom: 1px solid var(--border); font-size: 0.85rem; line-height: 1.5; color: #cbd5e1; font-family: Georgia, serif; } /* Diagram Panel */ .diagram-panel { background: #080d1a; border-bottom: 1px solid var(--border); padding: 1rem; display: flex; flex-direction: column; gap: 0.5rem; } .panel-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.4rem; } .panel-title { font-size: 0.82rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.04em; color: var(--emerald); display: flex; align-items: center; gap: 0.4rem; } .mermaid-box { background: #040711; border: 1px solid #1e293b; border-radius: 6px; padding: 1rem; overflow-x: auto; text-align: center; min-height: 140px; } /* Dual-Column or Single-Column Output Grid */ .columns-container { display: grid; gap: 1px; background: var(--border); } .columns-container.dual { grid-template-columns: 1fr 1fr; } .columns-container.single { grid-template-columns: 1fr; } .output-column { background: var(--bg-panel); display: flex; flex-direction: column; min-width: 0; } .column-header { background: #0c1424; border-bottom: 1px solid var(--border); padding: 0.5rem 0.85rem; display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; } .column-title { font-size: 0.8rem; font-weight: 700; color: #93c5fd; font-family: var(--font-mono); } .code-container { background: var(--bg-code); padding: 0.85rem; font-family: var(--font-mono); font-size: 0.82rem; line-height: 1.45; color: #7dd3fc; overflow-x: auto; max-height: 380px; overflow-y: auto; white-space: pre; } /* Artifacts / Direct Links Footer */ .artifacts-bar { background: #080d19; border-top: 1px solid var(--border); padding: 0.6rem 1rem; display: flex; align-items: center; justify-content: space-between; gap: 1rem; font-size: 0.78rem; } .artifact-links { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; } .art-link { color: var(--primary); text-decoration: none; display: inline-flex; align-items: center; gap: 0.3rem; font-weight: 600; cursor: pointer; } .art-link:hover { text-decoration: underline; color: #fff; } /* Welcome / Empty State Card */ .welcome-card { background: linear-gradient(135deg, rgba(14, 165, 233, 0.08), rgba(16, 185, 129, 0.05)); border: 1px solid rgba(56, 189, 248, 0.25); border-radius: 8px; padding: 1.5rem; display: flex; flex-direction: column; gap: 0.75rem; } .welcome-title { font-size: 1.25rem; font-weight: 800; color: var(--primary); } .welcome-desc { font-size: 0.88rem; line-height: 1.5; color: #cbd5e1; } .pipeline-steps { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.75rem; margin-top: 0.5rem; } .step-box { background: rgba(15, 23, 42, 0.8); border: 1px solid var(--border); border-radius: 6px; padding: 0.75rem; } .step-name { font-size: 0.8rem; font-weight: 800; color: var(--primary); margin-bottom: 0.25rem; } .step-detail { font-size: 0.72rem; color: var(--text-muted); line-height: 1.35; } </style> </head> <body> <!-- Top Configuration and Status Bar --> <header> <div class="brand"> <div class="brand-title">AST-CATALA-GEN STUDIO</div> <div class="brand-sub">MudraForge Formal Legal Engine v6.1.0</div> </div> <div class="top-controls"> <span class="badge green" id="badge-device">Device: CUDA (RTX 3060)</span> <span class="badge blue" id="badge-memory">Memory: Episodic ON</span> <span class="badge guard" id="badge-guard">isAuthorizedToDisburse: false</span> <span class="badge amber" id="badge-regex">0 Regex Verified</span> <button class="btn" id="btn-toggle-layout" onclick="toggleLayout()">Layout: Dual Columns</button> </div> </header> <!-- Main Body Layout --> <div class="app-body"> <!-- Left Sidebar: Tasks, Presets, History --> <aside> <div class="sidebar-tabs"> <div class="sidebar-tab active" id="tab-presets-btn" onclick="switchSidebarTab('presets')">Benchmark Tasks</div> <div class="sidebar-tab" id="tab-history-btn" onclick="switchSidebarTab('history')">Run History (<span id="history-badge">0</span>)</div> </div> <div class="sidebar-content" id="sidebar-content"> <!-- Rendered by JS --> </div> </aside> <!-- Central Workspace & Timeline Stream --> <main> <!-- Input Workspace Area --> <section class="input-workspace"> <div class="input-header-row"> <div class="field-group"> <span class="field-label">Document ID:</span> <input type="text" id="input-doc-id" value="US_IRC_68_B" style="width: 170px;" /> </div> <div class="field-group"> <span class="field-label">Stage Range:</span> <select id="select-start-stage"> <option value="stage1" selected>Start: Stage 1 (Raw Text)</option> <option value="stage1_5">Start: Stage 1.5 (Operands)</option> <option value="stage2">Start: Stage 2 (Clauses)</option> </select> <select id="select-end-stage"> <option value="stage2b" selected>End: Stage 2B + Stage 3 Emitter</option> <option value="stage2">End: Stage 2 Scopes</option> <option value="stage1_5">End: Stage 1.5 Operands</option> </select> </div> <div class="field-group"> <label style="font-size: 0.75rem; font-weight: 600; color: var(--emerald); cursor: pointer; display: flex; align-items: center; gap: 0.35rem;"> <input type="checkbox" id="check-memory" checked /> Continual Memory </label> </div> </div> <div class="textarea-wrapper"> <textarea id="input-statute-text" placeholder="Enter or paste statutory text here (e.g. US Internal Revenue Code, India Tax Act, GST rules)..."></textarea> </div> <div class="input-actions-row"> <div class="input-counters"> <span id="char-count">0 chars</span> | <span id="word-count">0 words</span> | <span id="token-est">~0 tokens</span> </div> <div style="display: flex; gap: 0.5rem;"> <button class="btn" onclick="clearInput()">Clear</button> <button class="btn" onclick="loadRandomPreset()">Load Random Preset</button> <button class="btn btn-primary" id="btn-compile" onclick="compileStatute()"> Compile to AST & Catala (Ctrl+Enter) </button> </div> </div> </section> <!-- Scrollable Execution Timeline Stream --> <section class="timeline-stream" id="timeline-stream"> <!-- Initial Welcome Card --> <div class="welcome-card" id="welcome-card"> <div class="welcome-title">Welcome to AST-CatalaGen Studio</div> <div class="welcome-desc"> This interactive studio compiles raw statutory text into formal, deterministic <strong>Statutory AST (.ast.json)</strong>, executable <strong>Literate INRIA Catala (.catala_en)</strong> specifications, and visual <strong>Rule Lifecycle Flowcharts</strong> via the MudraForge 4-stage neural pipeline. </div> <div class="pipeline-steps"> <div class="step-box"> <div class="step-name">Stage 1: Non-Operand Atoms</div> <div class="step-detail">37-tag Hierarchical Tree + Fast Memory M1 + CRF (MONEY, RATE, DATE, XREF, ACTOR).</div> </div> <div class="step-box"> <div class="step-name">Stage 1.5: Catala Operands</div> <div class="step-detail">17-tag Leaf Router + Continual Learning (Leaves, Entities, Metrics, Dates).</div> </div> <div class="step-box"> <div class="step-name">Stage 2: Clause Scopes</div> <div class="step-detail">COND, EXCEPTION, RULE_EFFECT, INLINE_DEF boundaries + Fast Memory M2.</div> </div> <div class="step-box"> <div class="step-name">Stage 3: AST & Catala Emitter</div> <div class="step-detail">Reflexion Critic, case tables, multi-slab brackets, min combinators, and statutory guard.</div> </div> </div> </div> </section> </main> </div> <script> mermaid.initialize({ startOnLoad: false, theme: 'dark', themeVariables: { darkMode: true, background: '#040711', primaryColor: '#0f172a', primaryTextColor: '#f8fafc', primaryBorderColor: '#38bdf8', lineColor: '#64748b' } }); let currentLayout = 'dual'; // 'dual' or 'single' let currentTab = 'presets'; // 'presets' or 'history' let presetsData = []; let historyData = []; // Initialize Studio window.addEventListener('DOMContentLoaded', async () => { await loadPresets(); await loadHistory(); setupInputListeners(); // Preload first preset if (presetsData.length > 0) { selectPreset(presetsData[4].id); // IRC 68(b) } }); function setupInputListeners() { const txt = document.getElementById('input-statute-text'); txt.addEventListener('input', updateCounters); txt.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); compileStatute(); } }); updateCounters(); } function updateCounters() { const val = document.getElementById('input-statute-text').value; const chars = val.length; const words = val.trim() ? val.trim().split(/\s+/).length : 0; const tokens = Math.round(words * 1.3); document.getElementById('char-count').innerText = `${chars} chars`; document.getElementById('word-count').innerText = `${words} words`; document.getElementById('token-est').innerText = `~${tokens} tokens`; } async function loadPresets() { try { const resp = await fetch('/api/presets'); presetsData = await resp.json(); renderPresets(); } catch (e) { console.error('Failed to load presets:', e); } } async function loadHistory() { try { const resp = await fetch('/api/history'); historyData = await resp.json(); document.getElementById('history-badge').innerText = historyData.length; if (currentTab === 'history') renderHistory(); } catch (e) { console.error('Failed to load history:', e); } } function switchSidebarTab(tab) { currentTab = tab; document.getElementById('tab-presets-btn').classList.toggle('active', tab === 'presets'); document.getElementById('tab-history-btn').classList.toggle('active', tab === 'history'); if (tab === 'presets') renderPresets(); else renderHistory(); } function renderPresets() { const container = document.getElementById('sidebar-content'); container.innerHTML = presetsData.map(p => ` <div class="preset-card" onclick="selectPreset('${p.id}')"> <div class="preset-title">${p.id}</div> <div class="preset-law">${p.title}</div> <div class="preset-snippet">${p.text}</div> </div> `).join(''); } function renderHistory() { const container = document.getElementById('sidebar-content'); if (historyData.length === 0) { container.innerHTML = '<div style="color: var(--text-muted); font-size: 0.8rem; padding: 1rem; text-align: center;">No compilations yet. Run a statute to see history.</div>'; return; } container.innerHTML = historyData.map(h => ` <div class="history-card" onclick="scrollToCard('${h.run_id}')"> <div class="history-title">${h.doc_id} (${h.latency_ms} ms)</div> <div style="font-size: 0.7rem; color: var(--emerald);">${h.timestamp_utc || 'just now'}</div> <div class="history-snippet">${h.text}</div> </div> `).join(''); } function selectPreset(id) { const p = presetsData.find(x => x.id === id); if (!p) return; document.getElementById('input-doc-id').value = p.id; document.getElementById('input-statute-text').value = p.text; updateCounters(); } function loadRandomPreset() { if (presetsData.length === 0) return; const idx = Math.floor(Math.random() * presetsData.length); selectPreset(presetsData[idx].id); } function clearInput() { document.getElementById('input-statute-text').value = ''; updateCounters(); } function toggleLayout() { currentLayout = (currentLayout === 'dual') ? 'single' : 'dual'; document.getElementById('btn-toggle-layout').innerText = `Layout: ${currentLayout === 'dual' ? 'Dual Columns' : 'Single Column'}`; document.querySelectorAll('.columns-container').forEach(el => { el.className = `columns-container ${currentLayout}`; }); } async function compileStatute() { const text = document.getElementById('input-statute-text').value.trim(); const doc_id = document.getElementById('input-doc-id').value.trim() || 'STATUTE_001'; const start_stage = document.getElementById('select-start-stage').value; const end_stage = document.getElementById('select-end-stage').value; const use_memory = document.getElementById('check-memory').checked; if (!text) { alert('Please enter statutory text to compile.'); return; } const btn = document.getElementById('btn-compile'); const originalText = btn.innerText; btn.innerText = 'Compiling Neural Pipeline...'; btn.disabled = true; try { const resp = await fetch('/api/compile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, doc_id, start_stage, end_stage, use_memory, }) }); if (!resp.ok) { const err = await resp.json(); alert(`Compilation failed: ${err.error || resp.statusText}`); return; } const data = await resp.json(); appendCardToStream(data); await loadHistory(); } catch (exc) { console.error('Error during compilation:', exc); alert(`Compilation error: ${exc.message}`); } finally { btn.innerText = originalText; btn.disabled = false; } } function appendCardToStream(data) { const stream = document.getElementById('timeline-stream'); const card = document.createElement('div'); card.className = 'timeline-card'; card.id = `card-${data.run_id}`; const astStr = JSON.stringify(data.ast, null, 2); const mermaidId = `mermaid-${data.run_id}`; card.innerHTML = ` <div class="card-top"> <div class="card-doc-info"> <span class="card-doc-id">${data.doc_id}</span> <span class="badge blue">Run: ${data.run_id}</span> <span class="badge green">${data.latency_ms} ms</span> <span class="badge amber">${data.token_count} tokens</span> <span class="badge guard">${data.statutory_guard}</span> </div> <div style="display: flex; gap: 0.4rem;"> <button class="btn" onclick="openArtifact('${data.written_artifacts?.html_report}')">View HTML/PDF Report</button> <button class="btn" onclick="openArtifact('${data.written_artifacts?.ast_json}')">Open .ast.json</button> <button class="btn" onclick="openArtifact('${data.written_artifacts?.catala_en}')">Open .catala_en</button> </div> </div> <div class="card-source-panel"> <strong>Statutory Source Text:</strong><br/> ${escapeHtml(data.text)} </div> <!-- Rule Lifecycle Diagram Panel --> <div class="diagram-panel"> <div class="panel-header"> <div class="panel-title"> Top-to-Bottom Statutory Rule Lifecycle Flowchart </div> <button class="btn" onclick="copyText('${escapeAttr(data.diagram?.mermaid || '')}')">Copy Mermaid</button> </div> <div class="mermaid-box" id="${mermaidId}"> <pre class="mermaid">${data.diagram?.mermaid || ''}</pre> </div> </div> <!-- Dual / Single Column Outputs --> <div class="columns-container ${currentLayout}"> <div class="output-column"> <div class="column-header"> <div class="column-title">Formal Statutory AST (.ast.json)</div> <div style="display: flex; gap: 0.35rem;"> <button class="btn" onclick="copyText('${escapeAttr(astStr)}')">Copy JSON</button> <button class="btn" onclick="downloadFile('${data.doc_id}.ast.json', '${escapeAttr(astStr)}')">Download</button> </div> </div> <div class="code-container">${escapeHtml(astStr)}</div> </div> <div class="output-column"> <div class="column-header"> <div class="column-title">Literate INRIA Catala (.catala_en)</div> <div style="display: flex; gap: 0.35rem;"> <button class="btn" onclick="copyText('${escapeAttr(data.catala || '')}')">Copy Catala</button> <button class="btn" onclick="downloadFile('${data.doc_id}.catala_en', '${escapeAttr(data.catala || '')}')">Download</button> </div> </div> <div class="code-container" style="color: #a7f3d0;">${escapeHtml(data.catala || '')}</div> </div> </div> <!-- Direct Artifacts Links --> <div class="artifacts-bar"> <div class="artifact-links"> <span>Disk Artifacts:</span> <span class="art-link" onclick="openArtifact('${data.written_artifacts?.ast_json}')"> 📄 ${data.written_artifacts?.ast_json || ''} </span> <span class="art-link" onclick="openArtifact('${data.written_artifacts?.catala_en}')"> 📄 ${data.written_artifacts?.catala_en || ''} </span> </div> <div style="color: var(--text-muted); font-size: 0.72rem;"> Click links to open natively in cursor/OS. </div> </div> `; stream.insertBefore(card, stream.children[1] || null); // Render Mermaid diagram try { mermaid.run({ nodes: card.querySelectorAll('.mermaid') }); } catch (mErr) { console.warn('Mermaid render issue:', mErr); } card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } function scrollToCard(run_id) { const el = document.getElementById(`card-${run_id}`); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' }); } async function openArtifact(path) { if (!path) return; try { const resp = await fetch(`/api/open?file=${encodeURIComponent(path)}`); const json = await resp.json(); if (json.error) alert(json.error); } catch (e) { alert(`Failed to open artifact: ${e.message}`); } } function copyText(str) { navigator.clipboard.writeText(str).then(() => { alert('Copied to clipboard.'); }).catch(err => { console.error('Copy failed:', err); }); } function downloadFile(filename, content) { const blob = new Blob([content], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); } function escapeHtml(text) { if (!text) return ''; return text .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;'); } function escapeAttr(text) { if (!text) return ''; return text .replace(/\\/g, '\\\\') .replace(/'/g, "\\'") .replace(/"/g, '&quot;') .replace(/\\n/g, '\\n') .replace(/\\r/g, ''); } </script> </body> </html> """ def run_studio_server( host: str = "127.0.0.1", port: int = DEFAULT_PORT, auto_open: bool = True, pipeline: MudraForgeCanonicalPipeline | None = None, ) -> None: """ Starts the threaded AST-CatalaGen Studio web server and optionally opens the browser automatically. """ StudioRequestHandler.pipeline_ref = pipeline server_address = (host, port) max_retries = 10 httpd: ThreadingHTTPServer | None = None for p in range(port, port + max_retries): try: httpd = ThreadingHTTPServer((host, p), StudioRequestHandler) port = p break except OSError: continue if httpd is None: raise RuntimeError(f"Could not bind to {host} on ports {port}-{port + max_retries}") url = f"http://{host}:{port}/" print("=" * 80) print(f"AST-CATALA-GEN STUDIO v6.1.0 (PROD)") print(f"Server Running at : {url}") print(f"Statutory Guard : isAuthorizedToDisburse: false") print(f"Zero-Regex Safety : 100% Audited") print("=" * 80) if auto_open: try: webbrowser.open(url) except Exception: pass try: httpd.serve_forever() except KeyboardInterrupt: print("\n[Studio] Shutting down server gracefully...") finally: httpd.server_close()
"""
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)",