File size: 11,166 Bytes
c6e5669 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | """openai/math preprint'lerinin LaTeX kaynaklarını tek dosyaya açıp parquet üretir.
PDF'ler OCR'lanmaz: her makalenin `build/` altındaki kaynağı kullanılır. Kök .tex
dosyasındaki `\\input` ve `\\lstinputlisting` çağrıları içerikle değiştirilir, yorumlar
atılır; `\\includepdf` ile birleştirilen alt belgeler sırayla eklenir. Aile, konu ve
özet bilgileri `CONTENTS.md` ile `overview.tex` dosyalarından alınır.
python3 build_papers.py # -> data/papers.parquet, data/overview.parquet
"""
import re
import subprocess
from pathlib import Path
import fitz # PyMuPDF; yalnız sayfa sayısı için
import pandas as pd
REPO = "openai/math"
COMMIT = "adc7f1241b42e322a6451854ab7e4b4c146bf78a"
BLOB = f"https://github.com/{REPO}/blob/{COMMIT}/"
SPARSE = ["/preprints/", "/reasoning_traces/", "/overview.*", "/CONTENTS.md", "/README.md", "/LICENSE"]
HERE = Path(__file__).parent
SRC = HERE / "raw" / "math"
OUT = HERE / "data"
# `(?<!\\)`: `\\input 1` (satır sonu + metin) komut değildir.
INPUT_RE = re.compile(r"(?<!\\)\\input(?:\s*\{([^}]*)\}|\s+([^\s{}\\]+))")
LST_RE = re.compile(r"(?<!\\)\\lstinputlisting\s*(\[[^\]]*\])?\s*\{([^}]*)\}")
INCLUDEPDF_RE = re.compile(r"(?<!\\)\\includepdf\s*(?:\[[^\]]*(?:\{[^}]*\}[^\]]*)*\])?\s*\{([^}]*)\}")
BIB_RE = re.compile(r"(?<!\\)\\bibliography\s*\{([^}]*)\}")
# pdfTeX'in kendi dosyaları; kaynakta yoktur, olduğu gibi bırakılır.
TEX_SYSTEM_INPUTS = {"glyphtounicode", "glyphtounicode-cmex", "glyphtounicode-cmr"}
BEGIN_DOC_RE = re.compile(r"^[^%\n]*\\begin\{document\}", re.M)
DATE_RE = re.compile(r"-((?:January|February|March|April|May|June|July|August|September|October|November|December)-\d{1,2}-\d{4}|\d{4}-\d{2}-\d{2})$")
def fetch_source():
"""Pinned commit'i Lean dosyaları olmadan klonlar (önbellek varsa atlar)."""
if (SRC / "CONTENTS.md").exists():
head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=SRC, capture_output=True, text=True).stdout.strip()
if head != COMMIT:
raise SystemExit(f"{SRC} commit {head}, beklenen {COMMIT}")
return
SRC.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(["git", "clone", "-q", "--filter=blob:none", "--no-checkout",
f"https://github.com/{REPO}.git", str(SRC)], check=True)
subprocess.run(["git", "sparse-checkout", "set", "--no-cone", *SPARSE], cwd=SRC, check=True)
subprocess.run(["git", "checkout", "-q", COMMIT], cwd=SRC, check=True)
VERBATIM_BEGIN = re.compile(r"\\begin\{(verbatim\*?|Verbatim|lstlisting|minted)\}")
def strip_comments(tex: str) -> str:
"""`%` yorumlarını atar; tamamı yorum olan satırlar silinir, verbatim ortamlarına dokunulmaz."""
out, verb = [], None
for line in tex.split("\n"):
if verb:
out.append(line)
if f"\\end{{{verb}}}" in line:
verb = None
continue
i = 0
while True:
i = line.find("%", i)
if i < 0:
kept = line
break
backslashes = len(line[:i]) - len(line[:i].rstrip("\\"))
if backslashes % 2 == 0:
kept = line[:i].rstrip() if line[:i].strip() else None
break
i += 1
if kept is None:
continue
out.append(kept)
m = VERBATIM_BEGIN.search(kept)
if m and f"\\end{{{m.group(1)}}}" not in kept[m.end():]:
verb = m.group(1)
return "\n".join(out)
def resolve(name: str, cur: Path, root: Path, exts=(".tex", "")):
for base in (root, cur):
for ext in exts:
p = base / (name + ext)
if p.is_file():
return p
return None
def flatten(path: Path, root: Path, pkg: Path, missing: list, seen=()) -> str:
"""`root`: \\input yollarının göreli olduğu dizin; `pkg`: makalenin preprints/ dizini."""
if path in seen:
raise RuntimeError(f"döngüsel input: {path}")
tex = strip_comments(path.read_text(encoding="utf-8", errors="replace"))
cur = path.parent
def sub_input(m):
name = (m.group(1) or m.group(2)).strip()
if re.sub(r"\.tex$", "", name) in TEX_SYSTEM_INPUTS:
return m.group(0)
p = resolve(name, cur, root)
if p is None:
missing.append(name)
return m.group(0)
return flatten(p, root, pkg, missing, seen + (path,)).strip("\n")
def sub_lst(m):
name = m.group(2).strip()
p = resolve(name, cur, root, exts=("",))
if p is None:
# Yayında dizin adı değişmiş olabilir (certificate/ -> verification/): tek eşleşen ada düş.
hits = list(pkg.rglob(Path(name).name))
p = hits[0] if len(hits) == 1 else None
if p is None:
missing.append(name)
return m.group(0)
code = p.read_text(encoding="utf-8", errors="replace").rstrip("\n")
return f"\\begin{{lstlisting}}{m.group(1) or ''}\n{code}\n\\end{{lstlisting}}"
tex = LST_RE.sub(sub_lst, tex)
return INPUT_RE.sub(sub_input, tex)
def flatten_paper(root: Path, pkg: Path, missing: list) -> str:
"""Kök yalnız `\\includepdf` ile ayrı belgeleri birleştiriyorsa, o belgeleri sırayla açar.
Sarmalayıcı kök derlenmiş PDF'leri iliştirir; metin alt belgelerin kaynağındadır.
"""
parts = INCLUDEPDF_RE.findall(strip_comments(root.read_text(encoding="utf-8", errors="replace")))
if not parts:
return collapse(flatten(root, root.parent, pkg, missing))
docs = []
for name in parts:
p = resolve(re.sub(r"\.pdf$", "", name.strip()), root.parent, root.parent, exts=(".tex",))
if p is None:
missing.append(name)
continue
docs.append(collapse(flatten(p, root.parent, pkg, missing)))
return "\n".join(docs)
def collapse(tex: str) -> str:
tex = "\n".join(line.rstrip() for line in tex.split("\n"))
return re.sub(r"\n{3,}", "\n\n", tex).strip() + "\n"
def find_root(d: Path, pdf: Path) -> Path:
"""`\\begin{document}` içeren .tex; birden fazlaysa PDF adıyla ya da main ile eşleşen en sığ dosya.
`\\documentclass` aranmaz: bazı makalelerde o satır `\\input` edilen preamble dosyasında.
"""
roots = [p for p in d.rglob("*.tex") if BEGIN_DOC_RE.search(p.read_text(encoding="utf-8", errors="replace"))]
if len(roots) == 1:
return roots[0]
for key in (pdf.stem, "main"):
hit = sorted((p for p in roots if p.stem == key), key=lambda p: len(p.parts))
if len(hit) == 1 or len(hit) > 1 and len(hit[0].parts) < len(hit[1].parts):
return hit[0]
raise RuntimeError(f"kök .tex belirsiz: {d.name}: {roots}")
def bib_text(tex: str, root: Path) -> str:
parts = []
for m in BIB_RE.finditer(tex):
for name in m.group(1).split(","):
p = resolve(name.strip(), root, root, exts=(".bib", ""))
if p is not None:
parts.append(p.read_text(encoding="utf-8", errors="replace").strip())
return "\n\n".join(parts) or None
def md_inline(s: str) -> str:
"""CONTENTS.md'deki HTML/GitHub-math işaretlerini sade Markdown+LaTeX'e çevirir."""
s = re.sub(r"\$`(.*?)`\$", r"$\1$", s)
s = re.sub(r"</?i>", "*", s)
s = re.sub(r"</?b>", "**", s)
s = re.sub(r"</?sub>|</?sup>", "", s)
for a, b in ((">", ">"), ("<", "<"), ("&", "&"), (" ", ""), (" ", " ")):
s = s.replace(a, b)
s = s.replace("\\gt", ">").replace("\\lt", "<")
return s.strip()
def parse_contents(text: str) -> dict:
"""pdf yolu -> {family, family_title, family_summary, title, abstract, lean_doc}."""
cells = re.findall(r"<td>\n\n(.*?)\n\n</td>", text, re.S)
fam = None
out = {}
for cell in cells:
m = re.match(r"\*\*(\d{3})\. (.*?)\*\* (.*)", cell, re.S)
if m:
summary = m.group(3)
lean = re.search(r"\(\[Lean\]\((lean/docs/\d+\.md)\)\)", summary)
summary = re.sub(r"\s*\(\[Lean\]\([^)]*\)\)", "", summary)
fam = {"family": m.group(1), "family_title": md_inline(m.group(2)).rstrip("."),
"family_summary": md_inline(summary), "lean_doc": lean.group(1) if lean else None}
continue
m = re.match(r" \[(.*)\]\((preprints/[^\n]+?\.pdf)\)([^\n]*)\n\n(.*)", cell, re.S)
if not m:
raise RuntimeError(f"tanınmayan hücre: {cell[:120]}")
note = m.group(3).strip(" —") or None
out[m.group(2)] = dict(fam, title=md_inline(m.group(1)), note=note, abstract=md_inline(m.group(4)))
return out
def parse_subjects(tex: str) -> dict:
subj, out = None, {}
for m in re.finditer(r"\\cataloguesection\{([^}]*)\}|\\resultentry\{(\d{3})\}", tex):
if m.group(1):
subj = m.group(1)
else:
out[m.group(2)] = subj
return out
def parse_date(name: str):
m = DATE_RE.search(name)
if not m:
return None
fmt = "%Y-%m-%d" if m.group(1)[0].isdigit() else "%B-%d-%Y"
return pd.to_datetime(m.group(1), format=fmt).date().isoformat()
def main():
fetch_source()
contents = parse_contents((SRC / "CONTENTS.md").read_text(encoding="utf-8"))
subjects = parse_subjects((SRC / "overview.tex").read_text(encoding="utf-8"))
rows, problems = [], []
for pdf_rel, meta in contents.items():
pdf = SRC / pdf_rel
d = pdf.parent
root = find_root(d, pdf)
missing = []
latex = flatten_paper(root, d, missing)
if missing:
problems.append((d.name, missing))
for needle in ("\\documentclass", "\\begin{document}", "\\end{document}"):
if needle not in latex:
problems.append((d.name, [f"{needle} yok"]))
with fitz.open(pdf) as doc:
num_pages = doc.page_count
rows.append({
"id": d.name,
"family": meta["family"],
"subject": subjects[meta["family"]],
"family_title": meta["family_title"],
"family_summary": meta["family_summary"],
"title": meta["title"],
"note": meta["note"],
"abstract": meta["abstract"],
"date": parse_date(d.name),
"latex": latex,
"bib": bib_text(latex, root.parent),
"num_pages": num_pages,
"has_lean": meta["lean_doc"] is not None,
"pdf_url": BLOB + pdf_rel,
"source_dir_url": BLOB.replace("/blob/", "/tree/") + str(root.parent.relative_to(SRC)),
})
OUT.mkdir(exist_ok=True)
df = pd.DataFrame(rows).sort_values(["family", "id"]).reset_index(drop=True)
df.to_parquet(OUT / "papers.parquet", index=False)
overview = collapse(strip_comments((SRC / "overview.tex").read_text(encoding="utf-8")))
pd.DataFrame([{"latex": overview, "pdf_url": BLOB + "overview.pdf"}]).to_parquet(OUT / "overview.parquet", index=False)
print(f"{len(df)} makale, {df.family.nunique()} aile, {df.subject.nunique()} konu")
for name, miss in problems:
print("ÇÖZÜLEMEYEN:", name, miss)
if __name__ == "__main__":
main()
|