"""Lean Proof Checker: a ZeroGPU Gradio Space. Upload a PDF of theorems + proofs (or paste one). Each proof is turned into a Lean 4 skeleton, each step is proved by automatic tactics or an open prover model, and Lean checks everything. ZeroGPU authorises every GPU call with a short-lived token that arrives with each browser request, so a long job cannot run inside one request. Instead a job is a Python generator kept on the server; a timer in the page sends a fresh request every second and each request advances the job by at most ONE GPU call (plus any Lean work around it). """ import json, os, tempfile, threading, time import gradio as gr import leanenv leanenv.start() # Lean + Mathlib install in the background while models load import core # noqa: E402 import models # noqa: E402 (loads both models at startup, as ZeroGPU requires) MAX_PROBLEMS = 10 TICK_SECONDS = 20 # max wall time per request when no GPU call happens JOBS = {} # session hash -> job # ----------------------------------------------------------------------------- display helpers def lean_status_md(): s = leanenv.status() if s["status"] == "ready": return "**Lean + Mathlib:** ready" if s["status"] == "failed": return f"**Lean + Mathlib:** setup failed\n\n```\n{(s['error'] or '')[-1200:]}\n```" return (f"**Lean + Mathlib:** {s['status']} ({s['minutes']} min). " "The first start after the Space wakes takes about 5–10 minutes.") def summary_md(reports): if not reports: return "" rows = ["| # | Theorem | Result | Steps proved | Lean statement says |", "|---|---|---|---|---|"] for r in reports: steps = r.get("steps", []) done = sum(s["status"].startswith("proved") for s in steps) result = {"verified": "✅ verified", "partial": "⚠️ partial", "verified_direct": "✅ verified (proved whole; human steps not checked)", "unproved": "❌ statement formalised, no proof found", "skeleton_failed": "❌ not formalised", "error": "❌ error"}.get(r["status"], r["status"]) cell = lambda t: str(t or "").replace("|", "/").replace("\n", " ") rows.append(f"| {r['n']} | {cell(r['theorem'])[:120]} | {result} | " f"{f'{done}/{len(steps)}' if steps else '–'} | {cell(r.get('statement_back_translation'))[:200]} |") return "\n".join(rows) def write_files(reports, outdir): paths = [] for r in reports: stem = f"problem_{r['n']:02d}" if r.get("lean_file"): p = os.path.join(outdir, stem + ".lean") with open(p, "w") as f: f.write(r["lean_file"]) paths.append(p) p = os.path.join(outdir, stem + "_report.json") with open(p, "w") as f: json.dump(r, f, indent=2, ensure_ascii=False) paths.append(p) return paths or None def emit(job): return "\n".join(job["log"][-300:]), summary_md(job["reports"]), write_files(job["reports"], job["outdir"]) # ----------------------------------------------------------------------------- jobs class CountingModels: """Same interface as `models`, but counts GPU calls so a request can stop after one.""" def __init__(self, job): self.job, self.VL_ID, self.PROVER_ID = job, models.VL_ID, models.PROVER_ID def _call(self, fn, *args, **kwargs): self.job["gpu_calls"] += 1 return fn(*args, **kwargs) def chat(self, *a, **k): return self._call(models.chat, *a, **k) def prove(self, *a, **k): return self._call(models.prove, *a, **k) def read_pages(self, *a, **k): return self._call(models.read_pages, *a, **k) def problems_from_pdf(m, pdf_path): if not pdf_path: yield "log", "Upload a PDF first." return pages = core.render_pdf(pdf_path) yield "log", f"Rendered {len(pages)} page(s); reading them with {m.VL_ID}…" text = m.read_pages(pages, core.READ_SYSTEM, f"Transcribe all problems from these {len(pages)} page(s).", think_tokens=2000, answer_tokens=3000) probs = core.parse_problems(text) if not probs: yield "log", "No problems found. What the model read:\n" + text[:1500] return yield "log", f"Found {len(probs)} problem(s)." yield "problems", probs def problems_from_text(m, theorem, proof): if not (theorem or "").strip(): yield "log", "Enter a theorem first." return proof = (proof or "").strip() or "(No proof given. Construct a proof.)" yield "problems", [(1, theorem.strip(), proof)] def work(job, source, args): """The whole job as a generator; it yields whenever there is progress to show.""" log, m = job["log"], job["models"] while not leanenv.ready(): s = leanenv.status() if s["status"] == "failed": raise RuntimeError("Lean setup failed:\n" + (s["error"] or "")[-1200:]) msg = f"Waiting for Lean + Mathlib to finish installing ({s['status']}, {s['minutes']} min so far)…" if log and log[-1].startswith("Waiting for Lean"): log[-1] = msg else: log.append(msg) yield time.sleep(5) problems = None for kind, val in source(m, *args): if kind == "log": log.append(val) yield else: problems = val if not problems: return for n, thm, prf in problems[:MAX_PROBLEMS]: log.append(f"=== Problem {n}: {thm[:100]}") yield report = None try: for kind, val in core.check_problem(m, thm, prf): if kind == "log": log.append(val) yield else: report = val except Exception as e: if "ZeroGPU" in type(e).__name__ or "quota" in str(e).lower(): raise # GPU unavailable: stop the job, don't burn the rest report = {"theorem": thm, "proof": prf, "status": "error", "error": f"{type(e).__name__}: {e}"} log.append(f" ERROR: {type(e).__name__}: {e}") report["n"] = n job["reports"].append(report) log.append(f" RESULT: {report['status']}" + (f" in {report['seconds']} s" if "seconds" in report else "")) yield if len(problems) > MAX_PROBLEMS: log.append(f"Only the first {MAX_PROBLEMS} problems were checked.") def new_job(request, source, args): for sid in [s for s, j in JOBS.items() if time.time() - j["created"] > 6 * 3600]: JOBS.pop(sid, None) job = {"log": ["Starting…"], "reports": [], "gpu_calls": 0, "done": False, "created": time.time(), "outdir": tempfile.mkdtemp(prefix="leancheck_"), "lock": threading.Lock()} job["models"] = CountingModels(job) job["gen"] = work(job, source, args) JOBS[request.session_hash] = job return emit(job) + (gr.Timer(active=True),) def start_pdf(pdf_path, request: gr.Request): return new_job(request, problems_from_pdf, (pdf_path,)) def start_text(theorem, proof, request: gr.Request): return new_job(request, problems_from_text, (theorem, proof)) def tick(request: gr.Request): """Advance this session's job by at most one GPU call (fresh ZeroGPU token per request).""" job = JOBS.get(request.session_hash) if job is None or job["done"]: return gr.skip(), gr.skip(), gr.skip(), gr.Timer(active=False) if not job["lock"].acquire(blocking=False): return gr.skip(), gr.skip(), gr.skip(), gr.skip() try: calls0, t0 = job["gpu_calls"], time.time() while True: try: next(job["gen"]) except StopIteration: job["log"].append("DONE.") job["done"] = True break except Exception as e: job["log"].append(f"STOPPED: {type(e).__name__}: {e}") job["done"] = True break if job["gpu_calls"] > calls0 or time.time() - t0 > TICK_SECONDS: break finally: job["lock"].release() return emit(job) + (gr.Timer(active=not job["done"]),) # ----------------------------------------------------------------------------- UI with gr.Blocks(title="Lean Proof Checker") as demo: gr.Markdown( "# Lean Proof Checker\n" "Upload a PDF of theorems with proofs, or paste one. Each proof is turned into a Lean 4 " "skeleton that follows the human steps; each step is then proved by automatic tactics or by " f"the open prover model `{models.PROVER_ID}`, and Lean 4 + Mathlib checks everything. " f"Reading the PDF, writing the skeleton and translating statements back use `{models.VL_ID}`.\n\n" "**Read the result with care:** *verified* means Lean accepted the proof of the Lean statement. " "Compare the plain-English reading of that statement with your theorem.\n\n" "GPU time comes from your daily ZeroGPU quota (sign in to use your own). Keep this tab open " "while a job runs: the page drives it.") status = gr.Markdown(lean_status_md()) with gr.Tab("PDF"): pdf = gr.File(label="PDF (up to 6 pages)", file_types=[".pdf"], type="filepath") go_pdf = gr.Button("Check the PDF", variant="primary") with gr.Tab("Paste a theorem"): thm = gr.Textbox(label="Theorem", lines=3, placeholder="For every integer n, 6 divides n^3 - n.") prf = gr.Textbox(label="Proof", lines=8, placeholder="n^3 - n = (n-1)n(n+1), a product of three consecutive integers…") go_txt = gr.Button("Check", variant="primary") log = gr.Textbox(label="Progress", lines=16, max_lines=30, autoscroll=True) table = gr.Markdown() files = gr.File(label="Lean files and reports", file_count="multiple") runner = gr.Timer(1.0, active=False) outs = [log, table, files, runner] go_pdf.click(start_pdf, inputs=pdf, outputs=outs, concurrency_id="start") go_txt.click(start_text, inputs=[thm, prf], outputs=outs, concurrency_id="start") runner.tick(tick, outputs=outs, trigger_mode="once", concurrency_id="work", concurrency_limit=1, show_progress="hidden") gr.Timer(15).tick(lean_status_md, outputs=status, show_progress="hidden") demo.queue(default_concurrency_limit=1) if __name__ == "__main__": demo.launch()