Index of theproofnetwork/open-problems@860a535/scripts/import_prove2me.py
qedmarket’s copy of theproofnetwork/open-problems@860a535, 1 Dec 2026original source ↗
#!/usr/bin/env python3"""Copy Prove2Me's open problems into Prove2Me/. python3 -I scripts/import_prove2me.py [--refresh] [--drop THEOREM ...] "Open" on Prove2Me only means "not proved there yet", and almost all of its ~60,000 open theorems are lemmas offormalization projects. So this takes the main theorem of every mission of type `OpenProblem` whose main theorem isstill open, in the default environment, public and not deprecated, and skips those whose source is formal-conjectures(already in FormalConjectures/) and those `Prove2Me/duplicates.json` lists as the same problem as a formal-conjecturesstatement. Each theorem becomes `Prove2Me/Theorems/Thm_<slug>.lean`: its `preamble` and `formal_statement` verbatim, with theplatform's imports `Definitions.Def_<slug>` and `Theorems.Thm_<slug>` rewritten to this folder, and the definitionsand theorems it imports copied the same way. `Prove2Me/upstream.json` records ids, links and metadata. API responses are cached under .lake/prove2me/; `--refresh` fetches them anew. `--drop` leaves out a main theorem(for one that doesn't compile on this repository's Mathlib); `patches/prove2me/` holds fixes that port files to it. Prove2Me's contributions are Apache-2.0 "to the extentthe contributor owns them" (its terms)."""import jsonimport reimport shutilimport subprocessimport sysimport timefrom pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent))import prove2me_api # noqa: E402 ROOT = Path(__file__).resolve().parent.parentOUT = ROOT / "Prove2Me"CACHE = ROOT / ".lake/prove2me"SITE = "https://prove2.me"# What a module here can import besides Prove2Me's own: Lean, Mathlib and Mathlib's dependencies.KNOWN_ROOTS = {"Init", "Std", "Lean", "Lake", "Mathlib", "Batteries", "Aesop", "Qq", "Plausible", "ProofWidgets", "ImportGraph", "LeanSearchClient", "Cli"}ANY_IMPORT = re.compile(r"^\s*(?:(?:public|private|meta)\s+)*import\s+\S+\s*$")IMPORT = re.compile(r"^(\s*(?:(?:public|private|meta)\s+)*import\s+)(Definitions|Theorems)\.(Def|Thm)_(\S+)(.*)$") # Paragraphs of a statement written for Prove2Me's agents, not for readers: where to work on the mission graph.AGENT_TEXT = re.compile(r"\*\*Status on the graph|Open leaves beneath|GET /|open-leaves`|Work there\.|submitting a direct proof") def for_readers(text): """A statement without the paragraphs that instruct Prove2Me's agents, and without a `---` rule left before them.""" if not text: return text paras = [p for p in re.split(r"\n\s*\n", text) if not AGENT_TEXT.search(p)] while paras and paras[-1].strip() == "---": paras.pop() return "\n\n".join(paras).strip() def slug(name): """Prove2Me's module slug: the name with `.` replaced by `_`.""" return name.replace(".", "_") def ident(s): return re.sub(r"[^A-Za-z0-9_]", "_", s) def cached(client, key, path, **params): f = CACHE / "items" / (re.sub(r"[^A-Za-z0-9_.-]", "_", key) + ".json") if f.exists(): return json.loads(f.read_text()) data = client.get(path, **params) f.parent.mkdir(parents=True, exist_ok=True) f.write_text(json.dumps(data)) time.sleep(0.3) return data def main(argv): if "--refresh" in argv: shutil.rmtree(CACHE, ignore_errors=True) drop = set(argv[argv.index("--drop") + 1:]) if "--drop" in argv else set() client = prove2me_api.Client() env = next(e for e in client.get("/environments")["environments"] if e["is_default"]) missions = client.pages("/missions", "missions", CACHE / "missions", limit=100) # Problems formal-conjectures states already (Prove2Me/duplicates.json, kept by hand): its statement is reviewed. same = json.loads((OUT / "duplicates.json").read_text())["same"] wanted, skipped = {}, [] for m in missions: main_ = m.get("main_theorem") or {} if m.get("mission_type") != "OpenProblem" or main_.get("status") != "Open" or main_.get("deprecated_at"): continue t = cached(client, "thm-" + main_["theorem_id"], f"/theorems/{main_['theorem_id']}") t = t.get("theorem", t) why = ("not public" if t.get("visibility") != "public" else "another environment" if t.get("mathlib_rev") != env["mathlib_rev"] else "from formal-conjectures" if "formal-conjectures" in (t.get("source") or "") else f"the same problem as formal-conjectures' {same[t['theorem_name']]}" if t["theorem_name"] in same else "dropped" if t["theorem_name"] in drop else None) if why: skipped.append({"theorem": t["theorem_name"], "mission": m["name"], "reason": why}) continue if t["theorem_name"] not in wanted: wanted[t["theorem_name"]] = (t, m) shutil.rmtree(OUT / "Definitions", ignore_errors=True) shutil.rmtree(OUT / "Theorems", ignore_errors=True) written, record_defs, record_deps, missing = {}, {}, {}, [] def by_slug(kind, s): """A definition or theorem another one imports, by its module slug (`.` became `_`): exact name lookups of the spellings that slug can come from, at most a few dots back.""" path, key, field = (("/definitions", "definitions", "definition_name") if kind == "Def" else ("/theorems", "theorems", "theorem_name")) parts = s.split("_") names = [s] + [".".join(["_".join(parts[:i]), "_".join(parts[i:])]) for i in range(1, len(parts))] for name in names: res = cached(client, f"{kind}-name-{name}", path, **{field: name, "view": "full"}) for row in res.get(key, []): if (row.get("mathlib_rev") == env["mathlib_rev"] and slug(row[field]) == s and not row.get("deprecated_at")): return row return None def emit(kind, s, header, preamble, body): """Write one module; returns its module name, or None when something it imports can't be found.""" module = f"Prove2Me.{'Definitions.Def_' if kind == 'Def' else 'Theorems.Thm_'}{ident(s)}" if module in written: return written[module] written[module] = module # imports don't form cycles; this guards anyway # Some definitions carry imports in their code, after comments: Lean wants all of them first, after a # `module` line if there is one. Everything else keeps its order. is_module, imports, rest = False, [], [] for line in (preamble + "\n\n" + body).split("\n"): if line.strip() == "module": is_module = True continue mm = IMPORT.match(line) if mm: dep = resolve(mm.group(3), mm.group(4)) if dep is None: written[module] = None return None imports.append(mm.group(1).lstrip() + dep + mm.group(5)) elif ANY_IMPORT.match(line): root = line.split()[-1].split(".")[0] if root not in KNOWN_ROOTS: # a project's own modules, pasted in: nothing here has them missing.append(line.split()[-1]) written[module] = None return None if line.strip() not in imports: imports.append(line.strip()) else: rest.append(line) path = ROOT / Path(*module.split(".")).with_suffix(".lean") path.parent.mkdir(parents=True, exist_ok=True) path.write_text(f"/-\n{header}\n-/\n" + ("module\n\n" if is_module else "") + "\n".join(imports) + "\n\n" + "\n".join(rest).strip("\n") + "\n") return module def resolve(kind, s): if kind == "Def": d = by_slug("Def", s) if d is None: missing.append(f"Definitions.Def_{s}") return None record_defs[d["definition_name"]] = {"definition_id": d["definition_id"], "url": f"{SITE}/definitions/{d['definition_id']}"} return emit("Def", s, f"From Prove2Me, definition `{d['definition_name']}` ({SITE}/definitions/" f"{d['definition_id']}). Apache-2.0 per Prove2Me's terms.", d.get("preamble") or "", d["definition"]) t = by_slug("Thm", s) if t is None: missing.append(f"Theorems.Thm_{s}") return None record_deps[t["theorem_name"]] = {"theorem_id": t["theorem_id"], "url": f"{SITE}/theorems/{t['theorem_id']}"} return emit("Thm", s, f"From Prove2Me, theorem `{t['theorem_name']}` ({SITE}/theorems/{t['theorem_id']}), " f"imported by another one. Apache-2.0 per Prove2Me's terms.", t["preamble"], t["formal_statement"]) record = {} for name, (t, m) in sorted(wanted.items()): header = (f"From Prove2Me: mission \"{m['name']}\" ({SITE}/missions/{m['id']}), main theorem `{name}` " f"({SITE}/theorems/{t['theorem_id']}).\nSource: {t.get('source') or 'not given'}\n" f"Apache-2.0 per Prove2Me's terms.") module = emit("Thm", slug(name), header, t["preamble"], t["formal_statement"]) if module is None: skipped.append({"theorem": name, "mission": m["name"], "reason": "imports something not found"}) continue # What it is proved from on Prove2Me: its open leaves, when they are other theorems than itself. leaves = cached(client, "leaves-" + t["theorem_id"], f"/theorems/{t['theorem_id']}/open-leaves", limit=100) lemmas = [x["theorem_name"] for x in leaves.get("open_leaves", []) if x["theorem_id"] != t["theorem_id"]] record[name] = { "module": module, "theorem_id": t["theorem_id"], "url": f"{SITE}/theorems/{t['theorem_id']}", "title": m["name"], "mission_id": m["id"], "mission_url": f"{SITE}/missions/{m['id']}", "statement": for_readers(t.get("natural_language_statement")), "openLemmas": lemmas, "openLemmasTotal": leaves.get("total", 0) if lemmas else 0, "openLemmasAt": time.strftime("%Y-%m-%d", time.gmtime()), "source": t.get("source"), "tags": t.get("tags") or [], "fields": [f["name"] for f in m.get("fields") or []], "mathlib_rev": t.get("mathlib_rev"), } # Fixes that port files to this repository's Mathlib, made by hand (`git diff > patches/prove2me/…`). for patch in sorted((ROOT / "patches/prove2me").glob("*.patch")): subprocess.run(["git", "apply", "--whitespace=nowarn", str(patch)], cwd=ROOT, check=True) print(f"applied {patch.name}") (OUT / "upstream.json").write_text(json.dumps({ "site": SITE, "fetchedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "environment": env, "theorems": record, "imported": {"definitions": record_defs, "theorems": record_deps}, "skipped": skipped, "missing": sorted(set(missing)), }, indent=1, ensure_ascii=False) + "\n") print(f"{len(record)} theorems, {len(record_defs)} definitions, {len(record_deps)} imported theorems; " f"{len(skipped)} skipped, {len(set(missing))} imports not found") if __name__ == "__main__": main(sys.argv[1:])