Xiorume-Kai-Delta / code /build_records.py
PureOne's picture
Upload Xiorume KAI Delta research dataset release
c1c9129 verified
Raw History Blame Contribute Delete
15.6 kB
#!/usr/bin/env python3
"""Build a deterministic, source-grounded JSONL index of the manuscript.
Only Python's standard library is required. This extracts authored source;
it does not independently prove, certify, or peer-review mathematics.
"""
from __future__ import annotations
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import re
import sys
SOURCE_FILENAMES = (
"Manuscript.tex", "singular_section.tex", "classification_new.tex",
"isolated_hyperbolic.tex", "scale_section.tex", "new_universality.tex",
"transfer_inverse_classification.tex", "weight_rigidity.tex",
"graded_section.tex",
)
TOPICS = {
"Manuscript.tex": "research_overview_and_retract_obstruction",
"singular_section.tex": "singular_information_geometry",
"classification_new.tex": "invariant_bilinear_forms_and_metric_existence",
"isolated_hyperbolic.tex": "isolated_point_hyperbolic_geometry",
"scale_section.tex": "scale_calculus_and_branching",
"new_universality.tex": "closed_set_merger_universality",
"transfer_inverse_classification.tex": "inverse_regularities",
"weight_rigidity.tex": "polyfold_weight_moduli",
"graded_section.tex": "graded_positivity_obstructions",
}
SCOPES = {
"Manuscript.tex": "The unrestricted abstract HWZ tripod realization problem remains unresolved in this manuscript.",
"singular_section.tex": "Use the stated singular-end, dimension, topology and symmetry hypotheses; numerical checks are not mathematical proof certification.",
"classification_new.tex": "The complete form classification is for fixed-density compactly supported interior volume isotropy, not arbitrary natural tensor fields under a larger geometric group.",
"isolated_hyperbolic.tex": "The hyperbolic model concerns the explicitly constructed centered one-point coefficient-cone metric in the integrable-centering regime.",
"scale_section.tex": "Bare scale-smooth maps are distinguished from nonlinear sc-Fredholm germs; the abstract HWZ tripod realization is not claimed solved.",
"new_universality.tex": "The zero-set nonmanifold-locus assertion assumes the prescribed closed set is nowhere dense, as stated in the theorem.",
"transfer_inverse_classification.tex": "The equivalences concern the specified finite-mode transfer class, not all scale-smooth maps.",
"weight_rigidity.tex": "The pointed-germ classification assumes n >= 0 and k >= 1 and the specified exponential-weight Sobolev cores.",
"graded_section.tex": "The obstruction requires the stated local degree-zero square-zero algebraic configuration; it is not asserted for all colored dimension types.",
}
ENV_RE = re.compile(r"\\begin\{(theorem|lemma|proposition|corollary|proof)\}")
LABEL_RE = re.compile(r"\\label\{([^{}]+)\}")
REF_RE = re.compile(r"\\ref\{([^{}]+)\}")
SECTION_RE = re.compile(r"\\section\*?\{")
STATUS_NOTE = "Authored analytic argument in an AI-generated manuscript; not proof-assistant certified."
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def balanced(text: str, start: int, left: str, right: str) -> tuple[str, int]:
if text[start] != left:
raise ValueError("Unbalanced title delimiter")
level = 0
for pos in range(start, len(text)):
if text[pos] == left and (pos == 0 or text[pos - 1] != "\\"):
level += 1
elif text[pos] == right and (pos == 0 or text[pos - 1] != "\\"):
level -= 1
if level == 0:
return text[start + 1:pos], pos + 1
raise ValueError("Unclosed title delimiter")
def line_at(text: str, offset: int) -> int:
return text.count("\n", 0, offset) + 1
def scan_environments(text: str) -> list[dict]:
found = []
for m in ENV_RE.finditer(text):
kind = m.group(1)
end_marker = "\\end{" + kind + "}"
end_start = text.find(end_marker, m.end())
if end_start < 0:
raise ValueError(f"Unclosed {kind} at line {line_at(text, m.start())}")
stop = end_start + len(end_marker)
cursor = m.end()
while cursor < len(text) and text[cursor].isspace():
cursor += 1
title = ""
if cursor < len(text) and text[cursor] == "[":
title, cursor = balanced(text, cursor, "[", "]")
raw = text[m.start():stop]
labels = LABEL_RE.findall(raw)
found.append({
"kind": kind, "start": m.start(), "end": stop,
"start_line": line_at(text, m.start()),
"end_line": line_at(text, stop - 1),
"title": title, "raw": raw, "label": labels[0] if labels else "",
})
return found
def section_context(text: str, position: int) -> str:
starts = [m.start() for m in SECTION_RE.finditer(text)]
left = max((x for x in starts if x <= position), default=0)
right = min((x for x in starts if x > position), default=len(text))
return text[left:right].strip()
def document_title(text: str, fallback: str) -> str:
m = SECTION_RE.search(text)
if m:
return balanced(text, m.end() - 1, "{", "}")[0]
return fallback
def make_record(**updates) -> dict:
base = {
"record_id": "", "record_type": "", "title": "", "source_file": "",
"source_label": "", "statement_latex": "", "proof_latex": "", "text": "",
"proof_status": "", "topic": "", "scope_note": "", "source_start_line": 0,
"source_end_line": 0, "statement_start_line": 0, "statement_end_line": 0,
"proof_locations_json": "[]", "source_context_latex": "", "source_sha256": "",
"related_labels": "", "content_origin": "AI-generated mathematical manuscript",
"dataset_edition": "expanded-2",
}
base.update(updates)
return base
def build(source_dir: Path) -> tuple[list[dict], dict]:
missing = [name for name in SOURCE_FILENAMES if not (source_dir / name).is_file()]
if missing:
raise ValueError("Missing authoritative source files: " + ", ".join(missing))
records: list[dict] = []
sources = []
explicit_proof_count = 0
attached_proof_count = 0
expected_statements = 0
for name in SOURCE_FILENAMES:
raw_bytes = (source_dir / name).read_bytes()
text = raw_bytes.decode("utf-8")
source_hash = sha256(raw_bytes)
lines = text.splitlines()
source_path = "proofs/" + name
short = Path(name).stem
common = {"source_file": source_path, "topic": TOPICS[name],
"scope_note": SCOPES[name], "source_sha256": source_hash}
records.append(make_record(
**common, record_id=f"source-document:{short}", record_type="source_document",
title=("Manuscript assembly, introduction, retract condition and references" if name == "Manuscript.tex"
else document_title(text, short)),
text=text, proof_status="not_applicable_full_source_document",
source_start_line=1, source_end_line=len(lines),
))
environments = scan_environments(text)
statements = [e for e in environments if e["kind"] != "proof"]
proofs = [e for e in environments if e["kind"] == "proof"]
expected_statements += len(statements)
explicit_proof_count += len(proofs)
by_label = {e["label"]: e for e in statements if e["label"]}
assigned = {e["start"]: [] for e in statements}
for proof in proofs:
refs = [ref for ref in REF_RE.findall(proof["title"]) if ref in by_label]
if refs:
if len(set(refs)) != 1:
raise ValueError(f"Ambiguous explicit proof target in {name}: {proof['title']}")
target = by_label[refs[0]]
else:
preceding = [e for e in statements if e["end"] <= proof["start"]]
if not preceding:
raise ValueError(f"Unattached proof in {name} line {proof['start_line']}")
target = max(preceding, key=lambda e: e["start"])
assigned[target["start"]].append(proof)
attached_proof_count += 1
for st in statements:
linked = assigned[st["start"]]
proof_text = "\n\n".join(x["raw"] for x in linked)
locations = [{"start_line": p["start_line"], "end_line": p["end_line"],
"heading_latex": p["title"], "extraction": "explicit_proof_environment"}
for p in linked]
status = ("multipart_explicit_proof_in_source" if len(linked) > 1
else "explicit_proof_in_source" if linked
else "statement_without_standalone_proof_environment")
related = ""
if st["label"] == "thm:arbitrary-branching":
if linked:
raise ValueError("Main scale theorem proof format changed; review narrative extraction")
following = [s["start"] for s in statements if s["start"] > st["end"]]
narrative_end = min(following, default=len(text))
proof_text = text[st["end"]:narrative_end].strip()
locations = [{"start_line": line_at(text, st["end"]),
"end_line": line_at(text, narrative_end - 1),
"heading_latex": "Narrative construction, all-orders estimates and consequences",
"extraction": "source_section_narrative_not_formal_proof_environment"}]
status = "proof_in_source_section"
elif st["label"] == "cor:fractal-zero-locus" and not linked:
status = "corollary_of_source_theorem_without_standalone_proof"
related = "thm:closed-universality"
last = max([st["end_line"]] + [p["end_line"] for p in locations])
stable = st["label"] or f"{st['kind']}:{short}:L{st['start_line']}"
title = st["title"] or st["kind"].capitalize()
combined = title + "\n\nSTATEMENT (LaTeX)\n" + st["raw"]
if proof_text:
combined += "\n\nSOURCE ARGUMENT (LaTeX; extraction status: " + status + ")\n" + proof_text
combined += "\n\nSOURCE SCOPE\n" + SCOPES[name] + " " + STATUS_NOTE
records.append(make_record(
**common, record_id="result:" + stable, record_type=st["kind"], title=title,
source_label=st["label"], statement_latex=st["raw"], proof_latex=proof_text,
text=combined, proof_status=status, source_start_line=st["start_line"],
source_end_line=last, statement_start_line=st["start_line"],
statement_end_line=st["end_line"], proof_locations_json=json.dumps(locations, ensure_ascii=False),
source_context_latex=section_context(text, st["start"]), related_labels=related,
))
sources.append({"source_file": source_path, "sha256": source_hash,
"lines": len(lines), "bytes": len(raw_bytes),
"statement_records": len(statements), "explicit_proof_environments": len(proofs)})
ids = [r["record_id"] for r in records]
if len(ids) != len(set(ids)):
raise ValueError("Duplicate record ids")
if attached_proof_count != explicit_proof_count:
raise ValueError("Some explicit proof environments were not attached exactly once")
if sum(r["record_type"] != "source_document" for r in records) != expected_statements:
raise ValueError("Theorem-family extraction count does not match source")
for record in records:
if record["record_type"] == "source_document":
continue
source_text = (source_dir / Path(record["source_file"]).name).read_text(encoding="utf-8")
source_lines = source_text.splitlines()
a, b = record["statement_start_line"], record["statement_end_line"]
assert 1 <= a <= b <= len(source_lines)
assert record["statement_latex"] in "\n".join(source_lines[a - 1:b])
assert 1 <= record["source_start_line"] <= record["source_end_line"] <= len(source_lines)
if record["proof_status"] in {"explicit_proof_in_source", "multipart_explicit_proof_in_source", "proof_in_source_section"}:
assert record["proof_latex"].strip(), "A linked argument cannot be empty"
for loc in json.loads(record["proof_locations_json"]):
assert 1 <= loc["start_line"] <= loc["end_line"] <= len(source_lines)
inventory = {
"dataset_name": "Xiorume-Kai-Delta", "edition": "expanded-2",
"data_file": "data/research_records.jsonl", "record_count": len(records),
"record_type_counts": dict(sorted(Counter(r["record_type"] for r in records).items())),
"proof_status_counts": dict(sorted(Counter(r["proof_status"] for r in records).items())),
"source_documents": sources,
"explicit_proof_environments": explicit_proof_count,
"attached_explicit_proof_environments": attached_proof_count,
"all_statement_environments_indexed": True, "unique_record_ids": True,
"line_anchors_validated": True,
"coverage_note": "Every current source file appears verbatim as a source_document record; every theorem, lemma, proposition and corollary is indexed separately. No PDF OCR or generated replacement proofs are used.",
"proof_status_note": "Status records source organization, not mathematical validity or independent verification. Analytic arguments are authored manuscript content; numerical formula checks remain separate metadata/code.",
}
return records, inventory
def main() -> int:
here = Path(__file__).resolve().parent
root = here.parent if here.name == "code" else here
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--source-dir", type=Path, default=root / "proofs")
p.add_argument("--output-dir", type=Path, default=root / "data")
p.add_argument("--metadata-dir", type=Path, default=root / "metadata")
p.add_argument("--check-only", action="store_true", help="Compare current output bytes without changing files")
args = p.parse_args()
try:
records, inventory = build(args.source_dir)
data = "".join(json.dumps(r, ensure_ascii=False, separators=(",", ":")) + "\n" for r in records).encode("utf-8")
inventory["data_sha256"] = sha256(data)
inventory["data_bytes"] = len(data)
inv = (json.dumps(inventory, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
outputs = [(args.output_dir / "research_records.jsonl", data),
(args.metadata_dir / "record_inventory.json", inv)]
if args.check_only:
if any(not path.is_file() or path.read_bytes() != content for path, content in outputs):
raise ValueError("Generated dataset or inventory differs from the current sources")
else:
for path, content in outputs:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
print(json.dumps({"records": len(records), "record_type_counts": inventory["record_type_counts"],
"proof_status_counts": inventory["proof_status_counts"], "data_sha256": inventory["data_sha256"],
"check_only": args.check_only}, ensure_ascii=False))
return 0
except (OSError, UnicodeError, ValueError, AssertionError) as exc:
print("Dataset build failed: " + str(exc), file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())