"""CPPTAI v2  Gradio demo for Hugging Face Spaces. Runs the 7-phase cognitive pipeline in OFFLINE mode by default (no API key, no external calls), so the Space builds and runs out of the box. Set CPPTAI_DISABLE_EXTERNAL=0 and provide DEEPSEEK_API_KEY as a Space Secret to enable live LLM calls. """ from __future__ import annotations import os import sys import time import traceback # --- Make `src/` importable both locally and on Spaces --- _HERE = os.path.dirname(os.path.abspath(__file__)) _SRC = os.path.join(_HERE, "src") if os.path.isdir(_SRC) and _SRC not in sys.path: sys.path.insert(0, _SRC) # --- Offline by default on Spaces (no secrets required) --- os.environ.setdefault("BENCH_DISABLE_EXTERNAL", "1") os.environ.setdefault("CPPTAI_DISABLE_EXTERNAL", "1") os.environ.setdefault("CPPTAI_CACHE_MODE", "offline") try: import gradio as gr except ImportError as exc: # pragma: no cover raise SystemExit("gradio is required: add gradio to requirements.txt") from exc try: from cpptai.core import CPPTAITraslocatore _IMPORT_ERROR: str | None = None except Exception: # pragma: no cover CPPTAITraslocatore = None # type: ignore[assignment] _IMPORT_ERROR = traceback.format_exc() DEFAULT_PROBLEM = ( "How can we address the global energy crisis considering: " "1) limits of renewables, 2) nuclear costs, 3) fossil dependency, " "4) geopolitical factors, 5) a just transition for workers?" ) HEADLINE = ( "Python framework (stdlib only) for a **7-phase cognitive pipeline**: " "Explorer (0)  Analyzer (0.5)  Entropic segregation (I)  " "Vertical topology (II)  Cognitive descent (III)  " "External convergence (IV)  Presentation (V)." ) def solve_problem(problem: str, enable_phase_iv: bool) -> tuple[str, str, str]: """Run CPPTAI offline and return (final_answer, arranged, debug).""" problem = (problem or "").strip() if not problem: return "Please enter a problem.", "", "" if CPPTAITraslocatore is None: return ( "Import error: could not load cpptai.core.", "", (_IMPORT_ERROR or "")[-4000:], ) t0 = time.perf_counter() try: # Offline mode: no external LLM calls unless explicitly enabled. if not enable_phase_iv: os.environ["CPPTAI_DISABLE_EXTERNAL"] = "1" traslocatore = CPPTAITraslocatore( enable_phase_iv=bool(enable_phase_iv), offline=not bool(enable_phase_iv), ) result = traslocatore.solve(problem) dt = time.perf_counter() - t0 final_answer = str(result.get("final_answer", "Undetermined")) arranged = str(result.get("final_arranged", "")) audit = result.get("responsible_ai_audit", {}) debug_lines = [ f"elapsed_sec: {dt:.2f}", f"offline: {not enable_phase_iv}", ] if isinstance(audit, dict) and audit: debug_lines.append(f"audit verdict: {audit.get('verdict', '')}") debug_lines.append(f"risk_score: {audit.get('risk_score', 0.0)}") return final_answer, arranged, "\n".join(debug_lines) except Exception: return "Error during execution.", "", traceback.format_exc()[-4000:] with gr.Blocks(title="CPPTAI v2  7-phase cognitive pipeline") as demo: gr.Markdown("# CPPTAI V2  7-phase cognitive pipeline") gr.Markdown(HEADLINE) gr.Markdown( "**Headline result (GSM8K N=200, paired): pipeline 96.0% vs DeepSeek " "single-shot 86.5% (+9.5pp, McNemar exact p = 0.00055).** \n" "Demo runs **offline** (no API key). Full benchmarks, LaTeX paper and " "diary (`DIARIO.md`) are included in the repo files." ) with gr.Row(): problem_in = gr.Textbox( label="Complex problem", value=DEFAULT_PROBLEM, lines=5, ) with gr.Row(): phase_iv = gr.Checkbox( label="Enable Phase IV (external convergence, requires network/keys)", value=False, ) run_btn = gr.Button("Run CPPTAI", variant="primary") with gr.Row(): out_answer = gr.Textbox(label="Final answer", lines=8) with gr.Row(): out_arranged = gr.Textbox(label="Arranged output (Phase V)", lines=12) with gr.Row(): out_debug = gr.Textbox(label="Run info", lines=4) gr.Examples( examples=[ [DEFAULT_PROBLEM, False], ["Solve: a train travels 120 km at 60 km/h, then 120 km at 40 km/h. Average speed?", False], ["Explain the trade-offs of Chain-of-Thought vs tree search for math reasoning.", False], ], inputs=[problem_in, phase_iv], ) run_btn.click( fn=solve_problem, inputs=[problem_in, phase_iv], outputs=[out_answer, out_arranged, out_debug], ) if __name__ == "__main__": # NOTE: ssr_mode=False = client-side rendering. On Spaces the default # SSR Node front-proxy (:7860 -> internal :7861) can leave the Space # unhealthy (RUNTIME_ERROR with no traceback), so serve directly. # Do NOT set share=True on Spaces (the platform exposes the app). demo.launch( server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")), ssr_mode=False, )