OpenAI math manuscripts: LaTeX sources + OCR reasoning summaries (openai/math@adc7f12)
Browse files- README.md +131 -0
- data/overview.parquet +3 -0
- data/papers.parquet +3 -0
- data/reasoning_summaries.parquet +3 -0
- scripts/build_papers.py +274 -0
- scripts/build_reasoning.py +73 -0
- scripts/ocr_reasoning.py +115 -0
README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pretty_name: OpenAI Math Manuscripts
|
| 6 |
+
size_categories:
|
| 7 |
+
- n<1K
|
| 8 |
+
task_categories:
|
| 9 |
+
- text-generation
|
| 10 |
+
tags:
|
| 11 |
+
- mathematics
|
| 12 |
+
- latex
|
| 13 |
+
- research-mathematics
|
| 14 |
+
- reasoning
|
| 15 |
+
- chain-of-thought
|
| 16 |
+
configs:
|
| 17 |
+
- config_name: papers
|
| 18 |
+
default: true
|
| 19 |
+
data_files:
|
| 20 |
+
- split: train
|
| 21 |
+
path: data/papers.parquet
|
| 22 |
+
- config_name: reasoning_summaries
|
| 23 |
+
data_files:
|
| 24 |
+
- split: train
|
| 25 |
+
path: data/reasoning_summaries.parquet
|
| 26 |
+
- config_name: overview
|
| 27 |
+
data_files:
|
| 28 |
+
- split: train
|
| 29 |
+
path: data/overview.parquet
|
| 30 |
+
---
|
| 31 |
+
|
| 32 |
+
# OpenAI Math Manuscripts
|
| 33 |
+
|
| 34 |
+
This dataset is a machine-readable copy of [`openai/math`](https://github.com/openai/math) at commit
|
| 35 |
+
[`adc7f12`](https://github.com/openai/math/tree/adc7f1241b42e322a6451854ab7e4b4c146bf78a). That
|
| 36 |
+
repository holds research manuscripts produced by an internal OpenAI model.
|
| 37 |
+
|
| 38 |
+
| Config | Rows | Content |
|
| 39 |
+
|---|---:|---|
|
| 40 |
+
| `papers` (default) | 722 | Full LaTeX source of every manuscript in `preprints/` (372 result families, 17 subjects, 34,815 PDF pages, ~36.4M tokens with o200k_base) |
|
| 41 |
+
| `reasoning_summaries` | 10 | Abridged summaries of the model's reasoning from `reasoning_traces/`, transcribed to Markdown + LaTeX (~149k tokens) |
|
| 42 |
+
| `overview` | 1 | LaTeX source of the catalogue `overview.pdf` |
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
from datasets import load_dataset
|
| 46 |
+
papers = load_dataset("ituperceptron/openai-math", "papers", split="train")
|
| 47 |
+
summaries = load_dataset("ituperceptron/openai-math", "reasoning_summaries", split="train")
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## How the text was produced
|
| 51 |
+
|
| 52 |
+
**Papers: from the source, not the PDFs.** Every manuscript is published with its LaTeX source
|
| 53 |
+
under `build/`. We take the root file (the one containing `\begin{document}`) and inline every
|
| 54 |
+
`\input` and `\lstinputlisting` recursively. We remove `%` comments, but leave verbatim and listing
|
| 55 |
+
environments untouched. One manuscript bundles two standalone documents with `\includepdf`, so its
|
| 56 |
+
`latex` field holds both documents one after the other. The text is never OCR'd, so formulas are
|
| 57 |
+
exactly as the authors wrote them. Bibliographies are either inline `thebibliography` blocks in
|
| 58 |
+
`latex` or the referenced `.bib` files in `bib`. Figures are left as TikZ code or
|
| 59 |
+
`\includegraphics` references.
|
| 60 |
+
|
| 61 |
+
**Reasoning summaries: OCR with a vision model.** OpenAI released 9 of the 10 summaries only as
|
| 62 |
+
PDFs. We sent each page (rendered at 150 dpi) together with the PDF text layer to `gpt-6-sol`
|
| 63 |
+
(OpenAI). The text layer supplies exact spelling. The image supplies structure and math, which plain
|
| 64 |
+
text extraction breaks: flattened sub/superscripts, Unicode italic letters, lost spaces, split
|
| 65 |
+
ligatures. The model was told to transcribe the page verbatim:
|
| 66 |
+
|
| 67 |
+
- prose as Markdown, with math as `$…$` / `$$…$$`;
|
| 68 |
+
- original-prompt excerpts and `VERBATIM EXCERPT` passages as ```` ```text ```` blocks, copied as
|
| 69 |
+
written;
|
| 70 |
+
- running headers and page numbers dropped.
|
| 71 |
+
|
| 72 |
+
Page outputs were then joined, continuing paragraphs and code blocks across page breaks. A
|
| 73 |
+
word-level comparison with the text layer shows no dropped content. The only differences are
|
| 74 |
+
hyphenation and ligature fragments that the text layer had split. The Mézard–Parisi summary also
|
| 75 |
+
has an official LaTeX source, which is included in its `latex` field.
|
| 76 |
+
|
| 77 |
+
## Fields
|
| 78 |
+
|
| 79 |
+
### `papers`
|
| 80 |
+
|
| 81 |
+
| Field | Description |
|
| 82 |
+
|---|---|
|
| 83 |
+
| `id` | Manuscript directory name in `preprints/` |
|
| 84 |
+
| `family` | Result family number (`001`–`372`); a family groups a main result with companions and alternative proofs |
|
| 85 |
+
| `subject` | Subject heading from `overview.tex` (e.g. Number theory, Combinatorics) |
|
| 86 |
+
| `family_title`, `family_summary` | Family title and description from `CONTENTS.md` |
|
| 87 |
+
| `title`, `abstract` | Manuscript title and abstract from `CONTENTS.md` (Markdown with `$…$` math) |
|
| 88 |
+
| `note` | Annotation next to the link in `CONTENTS.md` (e.g. `secondary writeup`), otherwise null |
|
| 89 |
+
| `date` | Release date from the directory name (ISO) |
|
| 90 |
+
| `latex` | Flattened LaTeX source of the whole document, including the preamble and macros |
|
| 91 |
+
| `bib` | Contents of the `.bib` files referenced by `\bibliography`, otherwise null |
|
| 92 |
+
| `num_pages` | Page count of the published PDF |
|
| 93 |
+
| `has_lean` | Whether the family has a Lean formalization in the source repository |
|
| 94 |
+
| `pdf_url`, `source_dir_url` | Published PDF and source directory at the pinned commit |
|
| 95 |
+
|
| 96 |
+
### `reasoning_summaries`
|
| 97 |
+
|
| 98 |
+
| Field | Description |
|
| 99 |
+
|---|---|
|
| 100 |
+
| `family`, `subject`, `title` | Result family, subject, and title from the source README |
|
| 101 |
+
| `slug` | Source file name without extension |
|
| 102 |
+
| `markdown` | Transcribed text (Markdown + LaTeX) |
|
| 103 |
+
| `latex` | Official LaTeX source when published (only `mezard-parisi-formula`), otherwise null |
|
| 104 |
+
| `num_pages`, `ocr_model`, `pdf_url` | PDF page count, transcription model, and source PDF |
|
| 105 |
+
|
| 106 |
+
## Limitations
|
| 107 |
+
|
| 108 |
+
- OpenAI notes that some results have not been formalized and could contain errors. The text here
|
| 109 |
+
is reproduced as published; it has not been checked.
|
| 110 |
+
- The `latex` documents are flattened but not normalized. Package files, figures, and the
|
| 111 |
+
pdfTeX-only `\input glyphtounicode` lines are still referenced but not included, so not every
|
| 112 |
+
document compiles as-is.
|
| 113 |
+
- Model transcription of the reasoning summaries can still contain small errors in math. When an
|
| 114 |
+
exact formula matters, check it against `pdf_url`.
|
| 115 |
+
- The `reasoning_summaries` are OpenAI's abridged third-person summaries ("the assistant
|
| 116 |
+
considered…"), not raw chains of thought.
|
| 117 |
+
|
| 118 |
+
## Reproduction
|
| 119 |
+
|
| 120 |
+
The build scripts are in this repository under `scripts/`. Steps:
|
| 121 |
+
|
| 122 |
+
1. `build_papers.py` clones the pinned commit without the Lean library and writes the `papers` and
|
| 123 |
+
`overview` configs.
|
| 124 |
+
2. `ocr_reasoning.py` transcribes the summary PDFs page by page and caches each page.
|
| 125 |
+
3. `build_reasoning.py` joins the cached pages into `reasoning_summaries`.
|
| 126 |
+
|
| 127 |
+
## License
|
| 128 |
+
|
| 129 |
+
Apache License 2.0, the same as the source repository. Content © OpenAI. The reasoning-summary
|
| 130 |
+
transcriptions were produced with an OpenAI model (`gpt-6-sol`). Packaged by
|
| 131 |
+
[ITU Perceptron](https://huggingface.co/ituperceptron).
|
data/overview.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6fe230726de213b9ff66e5724ee2f3c4215d10e0b0cc96697d5c1f9aa3a0e8c
|
| 3 |
+
size 129887
|
data/papers.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c7ac1e33937373ad72e8cb7ae4c95393a3e3a8063c6b1e2d059265e605049ca
|
| 3 |
+
size 67185639
|
data/reasoning_summaries.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b15ad787c5a47260c8aeab59acc89690e91139646a0cce9d14e6d305c4c58a30
|
| 3 |
+
size 383399
|
scripts/build_papers.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""openai/math preprint'lerinin LaTeX kaynaklarını tek dosyaya açıp parquet üretir.
|
| 2 |
+
|
| 3 |
+
PDF'ler OCR'lanmaz: her makalenin `build/` altındaki kaynağı kullanılır. Kök .tex
|
| 4 |
+
dosyasındaki `\\input` ve `\\lstinputlisting` çağrıları içerikle değiştirilir, yorumlar
|
| 5 |
+
atılır; `\\includepdf` ile birleştirilen alt belgeler sırayla eklenir. Aile, konu ve
|
| 6 |
+
özet bilgileri `CONTENTS.md` ile `overview.tex` dosyalarından alınır.
|
| 7 |
+
|
| 8 |
+
python3 build_papers.py # -> data/papers.parquet, data/overview.parquet
|
| 9 |
+
"""
|
| 10 |
+
import re
|
| 11 |
+
import subprocess
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import fitz # PyMuPDF; yalnız sayfa sayısı için
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
REPO = "openai/math"
|
| 18 |
+
COMMIT = "adc7f1241b42e322a6451854ab7e4b4c146bf78a"
|
| 19 |
+
BLOB = f"https://github.com/{REPO}/blob/{COMMIT}/"
|
| 20 |
+
SPARSE = ["/preprints/", "/reasoning_traces/", "/overview.*", "/CONTENTS.md", "/README.md", "/LICENSE"]
|
| 21 |
+
|
| 22 |
+
HERE = Path(__file__).parent
|
| 23 |
+
SRC = HERE / "raw" / "math"
|
| 24 |
+
OUT = HERE / "data"
|
| 25 |
+
|
| 26 |
+
# `(?<!\\)`: `\\input 1` (satır sonu + metin) komut değildir.
|
| 27 |
+
INPUT_RE = re.compile(r"(?<!\\)\\input(?:\s*\{([^}]*)\}|\s+([^\s{}\\]+))")
|
| 28 |
+
LST_RE = re.compile(r"(?<!\\)\\lstinputlisting\s*(\[[^\]]*\])?\s*\{([^}]*)\}")
|
| 29 |
+
INCLUDEPDF_RE = re.compile(r"(?<!\\)\\includepdf\s*(?:\[[^\]]*(?:\{[^}]*\}[^\]]*)*\])?\s*\{([^}]*)\}")
|
| 30 |
+
BIB_RE = re.compile(r"(?<!\\)\\bibliography\s*\{([^}]*)\}")
|
| 31 |
+
# pdfTeX'in kendi dosyaları; kaynakta yoktur, olduğu gibi bırakılır.
|
| 32 |
+
TEX_SYSTEM_INPUTS = {"glyphtounicode", "glyphtounicode-cmex", "glyphtounicode-cmr"}
|
| 33 |
+
BEGIN_DOC_RE = re.compile(r"^[^%\n]*\\begin\{document\}", re.M)
|
| 34 |
+
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})$")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fetch_source():
|
| 38 |
+
"""Pinned commit'i Lean dosyaları olmadan klonlar (önbellek varsa atlar)."""
|
| 39 |
+
if (SRC / "CONTENTS.md").exists():
|
| 40 |
+
head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=SRC, capture_output=True, text=True).stdout.strip()
|
| 41 |
+
if head != COMMIT:
|
| 42 |
+
raise SystemExit(f"{SRC} commit {head}, beklenen {COMMIT}")
|
| 43 |
+
return
|
| 44 |
+
SRC.parent.mkdir(parents=True, exist_ok=True)
|
| 45 |
+
subprocess.run(["git", "clone", "-q", "--filter=blob:none", "--no-checkout",
|
| 46 |
+
f"https://github.com/{REPO}.git", str(SRC)], check=True)
|
| 47 |
+
subprocess.run(["git", "sparse-checkout", "set", "--no-cone", *SPARSE], cwd=SRC, check=True)
|
| 48 |
+
subprocess.run(["git", "checkout", "-q", COMMIT], cwd=SRC, check=True)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
VERBATIM_BEGIN = re.compile(r"\\begin\{(verbatim\*?|Verbatim|lstlisting|minted)\}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def strip_comments(tex: str) -> str:
|
| 55 |
+
"""`%` yorumlarını atar; tamamı yorum olan satırlar silinir, verbatim ortamlarına dokunulmaz."""
|
| 56 |
+
out, verb = [], None
|
| 57 |
+
for line in tex.split("\n"):
|
| 58 |
+
if verb:
|
| 59 |
+
out.append(line)
|
| 60 |
+
if f"\\end{{{verb}}}" in line:
|
| 61 |
+
verb = None
|
| 62 |
+
continue
|
| 63 |
+
i = 0
|
| 64 |
+
while True:
|
| 65 |
+
i = line.find("%", i)
|
| 66 |
+
if i < 0:
|
| 67 |
+
kept = line
|
| 68 |
+
break
|
| 69 |
+
backslashes = len(line[:i]) - len(line[:i].rstrip("\\"))
|
| 70 |
+
if backslashes % 2 == 0:
|
| 71 |
+
kept = line[:i].rstrip() if line[:i].strip() else None
|
| 72 |
+
break
|
| 73 |
+
i += 1
|
| 74 |
+
if kept is None:
|
| 75 |
+
continue
|
| 76 |
+
out.append(kept)
|
| 77 |
+
m = VERBATIM_BEGIN.search(kept)
|
| 78 |
+
if m and f"\\end{{{m.group(1)}}}" not in kept[m.end():]:
|
| 79 |
+
verb = m.group(1)
|
| 80 |
+
return "\n".join(out)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def resolve(name: str, cur: Path, root: Path, exts=(".tex", "")):
|
| 84 |
+
for base in (root, cur):
|
| 85 |
+
for ext in exts:
|
| 86 |
+
p = base / (name + ext)
|
| 87 |
+
if p.is_file():
|
| 88 |
+
return p
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def flatten(path: Path, root: Path, pkg: Path, missing: list, seen=()) -> str:
|
| 93 |
+
"""`root`: \\input yollarının göreli olduğu dizin; `pkg`: makalenin preprints/ dizini."""
|
| 94 |
+
if path in seen:
|
| 95 |
+
raise RuntimeError(f"döngüsel input: {path}")
|
| 96 |
+
tex = strip_comments(path.read_text(encoding="utf-8", errors="replace"))
|
| 97 |
+
cur = path.parent
|
| 98 |
+
|
| 99 |
+
def sub_input(m):
|
| 100 |
+
name = (m.group(1) or m.group(2)).strip()
|
| 101 |
+
if re.sub(r"\.tex$", "", name) in TEX_SYSTEM_INPUTS:
|
| 102 |
+
return m.group(0)
|
| 103 |
+
p = resolve(name, cur, root)
|
| 104 |
+
if p is None:
|
| 105 |
+
missing.append(name)
|
| 106 |
+
return m.group(0)
|
| 107 |
+
return flatten(p, root, pkg, missing, seen + (path,)).strip("\n")
|
| 108 |
+
|
| 109 |
+
def sub_lst(m):
|
| 110 |
+
name = m.group(2).strip()
|
| 111 |
+
p = resolve(name, cur, root, exts=("",))
|
| 112 |
+
if p is None:
|
| 113 |
+
# Yayında dizin adı değişmiş olabilir (certificate/ -> verification/): tek eşleşen ada düş.
|
| 114 |
+
hits = list(pkg.rglob(Path(name).name))
|
| 115 |
+
p = hits[0] if len(hits) == 1 else None
|
| 116 |
+
if p is None:
|
| 117 |
+
missing.append(name)
|
| 118 |
+
return m.group(0)
|
| 119 |
+
code = p.read_text(encoding="utf-8", errors="replace").rstrip("\n")
|
| 120 |
+
return f"\\begin{{lstlisting}}{m.group(1) or ''}\n{code}\n\\end{{lstlisting}}"
|
| 121 |
+
|
| 122 |
+
tex = LST_RE.sub(sub_lst, tex)
|
| 123 |
+
return INPUT_RE.sub(sub_input, tex)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def flatten_paper(root: Path, pkg: Path, missing: list) -> str:
|
| 127 |
+
"""Kök yalnız `\\includepdf` ile ayrı belgeleri birleştiriyorsa, o belgeleri sırayla açar.
|
| 128 |
+
|
| 129 |
+
Sarmalayıcı kök derlenmiş PDF'leri iliştirir; metin alt belgelerin kaynağındadır.
|
| 130 |
+
"""
|
| 131 |
+
parts = INCLUDEPDF_RE.findall(strip_comments(root.read_text(encoding="utf-8", errors="replace")))
|
| 132 |
+
if not parts:
|
| 133 |
+
return collapse(flatten(root, root.parent, pkg, missing))
|
| 134 |
+
docs = []
|
| 135 |
+
for name in parts:
|
| 136 |
+
p = resolve(re.sub(r"\.pdf$", "", name.strip()), root.parent, root.parent, exts=(".tex",))
|
| 137 |
+
if p is None:
|
| 138 |
+
missing.append(name)
|
| 139 |
+
continue
|
| 140 |
+
docs.append(collapse(flatten(p, root.parent, pkg, missing)))
|
| 141 |
+
return "\n".join(docs)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def collapse(tex: str) -> str:
|
| 145 |
+
tex = "\n".join(line.rstrip() for line in tex.split("\n"))
|
| 146 |
+
return re.sub(r"\n{3,}", "\n\n", tex).strip() + "\n"
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def find_root(d: Path, pdf: Path) -> Path:
|
| 150 |
+
"""`\\begin{document}` içeren .tex; birden fazlaysa PDF adıyla ya da main ile eşleşen en sığ dosya.
|
| 151 |
+
|
| 152 |
+
`\\documentclass` aranmaz: bazı makalelerde o satır `\\input` edilen preamble dosyasında.
|
| 153 |
+
"""
|
| 154 |
+
roots = [p for p in d.rglob("*.tex") if BEGIN_DOC_RE.search(p.read_text(encoding="utf-8", errors="replace"))]
|
| 155 |
+
if len(roots) == 1:
|
| 156 |
+
return roots[0]
|
| 157 |
+
for key in (pdf.stem, "main"):
|
| 158 |
+
hit = sorted((p for p in roots if p.stem == key), key=lambda p: len(p.parts))
|
| 159 |
+
if len(hit) == 1 or len(hit) > 1 and len(hit[0].parts) < len(hit[1].parts):
|
| 160 |
+
return hit[0]
|
| 161 |
+
raise RuntimeError(f"kök .tex belirsiz: {d.name}: {roots}")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def bib_text(tex: str, root: Path) -> str:
|
| 165 |
+
parts = []
|
| 166 |
+
for m in BIB_RE.finditer(tex):
|
| 167 |
+
for name in m.group(1).split(","):
|
| 168 |
+
p = resolve(name.strip(), root, root, exts=(".bib", ""))
|
| 169 |
+
if p is not None:
|
| 170 |
+
parts.append(p.read_text(encoding="utf-8", errors="replace").strip())
|
| 171 |
+
return "\n\n".join(parts) or None
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def md_inline(s: str) -> str:
|
| 175 |
+
"""CONTENTS.md'deki HTML/GitHub-math işaretlerini sade Markdown+LaTeX'e çevirir."""
|
| 176 |
+
s = re.sub(r"\$`(.*?)`\$", r"$\1$", s)
|
| 177 |
+
s = re.sub(r"</?i>", "*", s)
|
| 178 |
+
s = re.sub(r"</?b>", "**", s)
|
| 179 |
+
s = re.sub(r"</?sub>|</?sup>", "", s)
|
| 180 |
+
for a, b in ((">", ">"), ("<", "<"), ("&", "&"), (" ", ""), (" ", " ")):
|
| 181 |
+
s = s.replace(a, b)
|
| 182 |
+
s = s.replace("\\gt", ">").replace("\\lt", "<")
|
| 183 |
+
return s.strip()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def parse_contents(text: str) -> dict:
|
| 187 |
+
"""pdf yolu -> {family, family_title, family_summary, title, abstract, lean_doc}."""
|
| 188 |
+
cells = re.findall(r"<td>\n\n(.*?)\n\n</td>", text, re.S)
|
| 189 |
+
fam = None
|
| 190 |
+
out = {}
|
| 191 |
+
for cell in cells:
|
| 192 |
+
m = re.match(r"\*\*(\d{3})\. (.*?)\*\* (.*)", cell, re.S)
|
| 193 |
+
if m:
|
| 194 |
+
summary = m.group(3)
|
| 195 |
+
lean = re.search(r"\(\[Lean\]\((lean/docs/\d+\.md)\)\)", summary)
|
| 196 |
+
summary = re.sub(r"\s*\(\[Lean\]\([^)]*\)\)", "", summary)
|
| 197 |
+
fam = {"family": m.group(1), "family_title": md_inline(m.group(2)).rstrip("."),
|
| 198 |
+
"family_summary": md_inline(summary), "lean_doc": lean.group(1) if lean else None}
|
| 199 |
+
continue
|
| 200 |
+
m = re.match(r" \[(.*)\]\((preprints/[^\n]+?\.pdf)\)([^\n]*)\n\n(.*)", cell, re.S)
|
| 201 |
+
if not m:
|
| 202 |
+
raise RuntimeError(f"tanınmayan hücre: {cell[:120]}")
|
| 203 |
+
note = m.group(3).strip(" —") or None
|
| 204 |
+
out[m.group(2)] = dict(fam, title=md_inline(m.group(1)), note=note, abstract=md_inline(m.group(4)))
|
| 205 |
+
return out
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def parse_subjects(tex: str) -> dict:
|
| 209 |
+
subj, out = None, {}
|
| 210 |
+
for m in re.finditer(r"\\cataloguesection\{([^}]*)\}|\\resultentry\{(\d{3})\}", tex):
|
| 211 |
+
if m.group(1):
|
| 212 |
+
subj = m.group(1)
|
| 213 |
+
else:
|
| 214 |
+
out[m.group(2)] = subj
|
| 215 |
+
return out
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def parse_date(name: str):
|
| 219 |
+
m = DATE_RE.search(name)
|
| 220 |
+
if not m:
|
| 221 |
+
return None
|
| 222 |
+
fmt = "%Y-%m-%d" if m.group(1)[0].isdigit() else "%B-%d-%Y"
|
| 223 |
+
return pd.to_datetime(m.group(1), format=fmt).date().isoformat()
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def main():
|
| 227 |
+
fetch_source()
|
| 228 |
+
contents = parse_contents((SRC / "CONTENTS.md").read_text(encoding="utf-8"))
|
| 229 |
+
subjects = parse_subjects((SRC / "overview.tex").read_text(encoding="utf-8"))
|
| 230 |
+
rows, problems = [], []
|
| 231 |
+
for pdf_rel, meta in contents.items():
|
| 232 |
+
pdf = SRC / pdf_rel
|
| 233 |
+
d = pdf.parent
|
| 234 |
+
root = find_root(d, pdf)
|
| 235 |
+
missing = []
|
| 236 |
+
latex = flatten_paper(root, d, missing)
|
| 237 |
+
if missing:
|
| 238 |
+
problems.append((d.name, missing))
|
| 239 |
+
for needle in ("\\documentclass", "\\begin{document}", "\\end{document}"):
|
| 240 |
+
if needle not in latex:
|
| 241 |
+
problems.append((d.name, [f"{needle} yok"]))
|
| 242 |
+
with fitz.open(pdf) as doc:
|
| 243 |
+
num_pages = doc.page_count
|
| 244 |
+
rows.append({
|
| 245 |
+
"id": d.name,
|
| 246 |
+
"family": meta["family"],
|
| 247 |
+
"subject": subjects[meta["family"]],
|
| 248 |
+
"family_title": meta["family_title"],
|
| 249 |
+
"family_summary": meta["family_summary"],
|
| 250 |
+
"title": meta["title"],
|
| 251 |
+
"note": meta["note"],
|
| 252 |
+
"abstract": meta["abstract"],
|
| 253 |
+
"date": parse_date(d.name),
|
| 254 |
+
"latex": latex,
|
| 255 |
+
"bib": bib_text(latex, root.parent),
|
| 256 |
+
"num_pages": num_pages,
|
| 257 |
+
"has_lean": meta["lean_doc"] is not None,
|
| 258 |
+
"pdf_url": BLOB + pdf_rel,
|
| 259 |
+
"source_dir_url": BLOB.replace("/blob/", "/tree/") + str(root.parent.relative_to(SRC)),
|
| 260 |
+
})
|
| 261 |
+
OUT.mkdir(exist_ok=True)
|
| 262 |
+
df = pd.DataFrame(rows).sort_values(["family", "id"]).reset_index(drop=True)
|
| 263 |
+
df.to_parquet(OUT / "papers.parquet", index=False)
|
| 264 |
+
|
| 265 |
+
overview = collapse(strip_comments((SRC / "overview.tex").read_text(encoding="utf-8")))
|
| 266 |
+
pd.DataFrame([{"latex": overview, "pdf_url": BLOB + "overview.pdf"}]).to_parquet(OUT / "overview.parquet", index=False)
|
| 267 |
+
|
| 268 |
+
print(f"{len(df)} makale, {df.family.nunique()} aile, {df.subject.nunique()} konu")
|
| 269 |
+
for name, miss in problems:
|
| 270 |
+
print("ÇÖZÜLEMEYEN:", name, miss)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
main()
|
scripts/build_reasoning.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`ocr_reasoning.py` sayfa çıktılarını belge başına birleştirip parquet üretir.
|
| 2 |
+
|
| 3 |
+
python3 build_reasoning.py # -> data/reasoning_summaries.parquet
|
| 4 |
+
"""
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import fitz
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from build_papers import BLOB, SRC, OUT, parse_subjects, strip_comments, collapse
|
| 13 |
+
|
| 14 |
+
TRACES = SRC / "reasoning_traces"
|
| 15 |
+
OCR = Path(__file__).parent / "raw" / "ocr"
|
| 16 |
+
SENTENCE_END = re.compile(r"[.!?:;)\]$`*]\s*$")
|
| 17 |
+
BLOCK_START = re.compile(r"^(#|>|```|[-*+] |\d+\. |\||\$\$)")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def readme_table() -> dict:
|
| 21 |
+
"""README 'Reasoning summaries' tablosu: slug -> (family, title)."""
|
| 22 |
+
text = (SRC / "README.md").read_text(encoding="utf-8")
|
| 23 |
+
rows = re.findall(r"^\| (\d{3}) \| \[(.+?)\]\(reasoning_traces/([^)]+)\.pdf\) \|$", text, re.M)
|
| 24 |
+
return {slug: (fam, title) for fam, title, slug in rows}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def join_pages(pages: list) -> str:
|
| 28 |
+
out = pages[0]
|
| 29 |
+
for page in pages[1:]:
|
| 30 |
+
# Sayfa sonunda kapanıp sonraki sayfada yeniden açılan aynı kod bloğunu birleştir.
|
| 31 |
+
if out.endswith("```") and page.startswith("```text"):
|
| 32 |
+
out = out[:-3].rstrip("\n") + "\n" + page[len("```text"):].lstrip("\n")
|
| 33 |
+
# Sayfa cümle ortasında bitiyorsa paragrafı sürdür (satır sonu tirelerinde boşluksuz).
|
| 34 |
+
elif not SENTENCE_END.search(out) and not BLOCK_START.match(page):
|
| 35 |
+
out = out.rstrip() + ("" if out.rstrip().endswith(("–", "-")) else " ") + page
|
| 36 |
+
else:
|
| 37 |
+
out = out.rstrip() + "\n\n" + page
|
| 38 |
+
return re.sub(r"\n{3,}", "\n\n", out).strip() + "\n"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
table = readme_table()
|
| 43 |
+
subjects = parse_subjects((SRC / "overview.tex").read_text(encoding="utf-8"))
|
| 44 |
+
rows = []
|
| 45 |
+
for pdf in sorted(TRACES.glob("*.pdf")):
|
| 46 |
+
with fitz.open(pdf) as doc:
|
| 47 |
+
n = doc.page_count
|
| 48 |
+
files = [OCR / pdf.stem / f"{i:03d}.json" for i in range(1, n + 1)]
|
| 49 |
+
missing = [f.name for f in files if not f.exists()]
|
| 50 |
+
if missing:
|
| 51 |
+
raise SystemExit(f"{pdf.stem}: OCR eksik sayfalar {missing}")
|
| 52 |
+
pages = [json.loads(f.read_text()) for f in files]
|
| 53 |
+
tex = pdf.with_suffix(".tex")
|
| 54 |
+
fam, title = table[pdf.stem]
|
| 55 |
+
rows.append({
|
| 56 |
+
"family": fam,
|
| 57 |
+
"subject": subjects[fam],
|
| 58 |
+
"title": title,
|
| 59 |
+
"slug": pdf.stem,
|
| 60 |
+
"markdown": join_pages([p["markdown"] for p in pages]),
|
| 61 |
+
"latex": collapse(strip_comments(tex.read_text(encoding="utf-8"))) if tex.exists() else None,
|
| 62 |
+
"num_pages": n,
|
| 63 |
+
"ocr_model": ",".join(sorted({p["model"] for p in pages})),
|
| 64 |
+
"pdf_url": BLOB + f"reasoning_traces/{pdf.name}",
|
| 65 |
+
})
|
| 66 |
+
df = pd.DataFrame(rows).sort_values("family").reset_index(drop=True)
|
| 67 |
+
OUT.mkdir(exist_ok=True)
|
| 68 |
+
df.to_parquet(OUT / "reasoning_summaries.parquet", index=False)
|
| 69 |
+
print(df[["family", "slug", "num_pages"]].assign(chars=df.markdown.str.len()).to_string())
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
main()
|
scripts/ocr_reasoning.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""openai/math reasoning_traces PDF'lerini sayfa sayfa OpenAI vision ile Markdown+LaTeX'e çevirir.
|
| 2 |
+
|
| 3 |
+
Her sayfa için görüntü ve PyMuPDF metin katmanı birlikte gönderilir: kelimeler metin
|
| 4 |
+
katmanından doğru okunur, formül yapısı görüntüden kurulur. Sonuç sayfa başına
|
| 5 |
+
`raw/ocr/<slug>/<sayfa>.json` olarak saklanır; yeniden çalıştırınca biten sayfalar atlanır.
|
| 6 |
+
Kota 1M grubundan düşer; `--budget` aşılmadan durur (önceki çalıştırmalar dahil).
|
| 7 |
+
|
| 8 |
+
python3 ocr_reasoning.py --pages irrationality-exponent-of-pi:5 # pilot
|
| 9 |
+
python3 ocr_reasoning.py # hepsi
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import base64
|
| 13 |
+
import json
|
| 14 |
+
import sys
|
| 15 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import fitz
|
| 19 |
+
from dotenv import load_dotenv
|
| 20 |
+
from openai import OpenAI
|
| 21 |
+
|
| 22 |
+
HERE = Path(__file__).parent
|
| 23 |
+
TRACES = HERE / "raw" / "math" / "reasoning_traces"
|
| 24 |
+
OCR = HERE / "raw" / "ocr"
|
| 25 |
+
MODEL = "gpt-6-sol"
|
| 26 |
+
EFFORT = "none"
|
| 27 |
+
DPI = 150
|
| 28 |
+
|
| 29 |
+
PROMPT = """You are transcribing one page of a mathematics document (an abridged summary of a model's chain of thought) into Markdown with LaTeX math.
|
| 30 |
+
|
| 31 |
+
You get the page image and the PDF's text layer. The text layer has the correct words but broken math: italic Unicode letters, lost spaces, flattened sub/superscripts, broken line wraps. Use the image as the authority for structure and math, and the text layer to spell words exactly.
|
| 32 |
+
|
| 33 |
+
Rules:
|
| 34 |
+
- Transcribe everything on the page in reading order, verbatim. Do not summarize, correct, complete, or add anything.
|
| 35 |
+
- Math: inline as $...$, display as $$...$$ on their own lines. Use standard LaTeX (\\pi, \\mathbb{Z}, x^{2}, a_{k}, \\frac{}{}, \\le). No Unicode math letters.
|
| 36 |
+
- Headings as Markdown headings (#, ##, ###) matching the visual hierarchy. Keep bold/italic. Lists as Markdown lists. Tables as Markdown tables.
|
| 37 |
+
- Monospace quoted blocks (original prompt excerpts and "VERBATIM EXCERPT" passages): put the label shown above the block, if any, on its own line in bold (`**VERBATIM EXCERPT**`), then the block text in a ```text fenced block. Copy it exactly as written; do not convert its ASCII math to LaTeX. Join lines that wrap only because they reached the right margin; keep real line breaks (list items, indented lines, blank lines).
|
| 38 |
+
- Join lines that wrap within a paragraph; remove hyphenation introduced by line breaks; separate paragraphs with one blank line.
|
| 39 |
+
- Omit running headers, footers and page numbers.
|
| 40 |
+
- If the page begins or ends mid-sentence, begin or end mid-sentence as well.
|
| 41 |
+
- Keep URLs, citation markers like [17], and reference list entries exactly.
|
| 42 |
+
|
| 43 |
+
Output only the page's Markdown, with no preamble and no surrounding code fence."""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def page_inputs(pdf: Path, index: int):
|
| 47 |
+
with fitz.open(pdf) as doc:
|
| 48 |
+
page = doc[index]
|
| 49 |
+
png = page.get_pixmap(dpi=DPI).tobytes("png")
|
| 50 |
+
text = page.get_text("text")
|
| 51 |
+
return base64.b64encode(png).decode(), text
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def ocr_page(client: OpenAI, pdf: Path, index: int, model: str, effort: str) -> dict:
|
| 55 |
+
img, text = page_inputs(pdf, index)
|
| 56 |
+
resp = client.responses.create(
|
| 57 |
+
model=model,
|
| 58 |
+
reasoning={"effort": effort},
|
| 59 |
+
input=[{"role": "user", "content": [
|
| 60 |
+
{"type": "input_text", "text": PROMPT},
|
| 61 |
+
{"type": "input_text", "text": f"Text layer of page {index + 1}:\n<<<\n{text}\n>>>"},
|
| 62 |
+
{"type": "input_image", "image_url": f"data:image/png;base64,{img}", "detail": "high"},
|
| 63 |
+
]}],
|
| 64 |
+
)
|
| 65 |
+
if resp.status != "completed":
|
| 66 |
+
raise RuntimeError(f"{pdf.stem} s.{index + 1}: {resp.status} {resp.incomplete_details}")
|
| 67 |
+
u = resp.usage
|
| 68 |
+
return {"slug": pdf.stem, "page": index + 1, "model": model, "markdown": resp.output_text.strip(),
|
| 69 |
+
"input_tokens": u.input_tokens, "output_tokens": u.output_tokens,
|
| 70 |
+
"reasoning_tokens": u.output_tokens_details.reasoning_tokens}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def spent() -> int:
|
| 74 |
+
return sum(r["input_tokens"] + r["output_tokens"]
|
| 75 |
+
for r in (json.loads(p.read_text()) for p in OCR.glob("*/*.json")))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main():
|
| 79 |
+
ap = argparse.ArgumentParser()
|
| 80 |
+
ap.add_argument("--pages", nargs="*", help="slug:sayfa (1 tabanlı); verilmezse tüm PDF'ler")
|
| 81 |
+
ap.add_argument("--model", default=MODEL)
|
| 82 |
+
ap.add_argument("--effort", default=EFFORT, help="modelin desteklediği en düşük reasoning effort")
|
| 83 |
+
ap.add_argument("--budget", type=int, default=900_000, help="tüm çalıştırmalar için toplam token sınırı")
|
| 84 |
+
ap.add_argument("--workers", type=int, default=8)
|
| 85 |
+
args = ap.parse_args()
|
| 86 |
+
load_dotenv(HERE.parents[1] / ".env")
|
| 87 |
+
client = OpenAI()
|
| 88 |
+
|
| 89 |
+
if args.pages:
|
| 90 |
+
jobs = [(TRACES / f"{s.split(':')[0]}.pdf", int(s.split(':')[1]) - 1) for s in args.pages]
|
| 91 |
+
else:
|
| 92 |
+
jobs = []
|
| 93 |
+
for pdf in sorted(TRACES.glob("*.pdf")):
|
| 94 |
+
with fitz.open(pdf) as doc:
|
| 95 |
+
jobs += [(pdf, i) for i in range(doc.page_count)]
|
| 96 |
+
jobs = [(pdf, i) for pdf, i in jobs if not (OCR / pdf.stem / f"{i + 1:03d}.json").exists()]
|
| 97 |
+
|
| 98 |
+
used = spent()
|
| 99 |
+
print(f"{len(jobs)} sayfa kaldı, şimdiye kadar {used:,} token", flush=True)
|
| 100 |
+
with ThreadPoolExecutor(args.workers) as pool:
|
| 101 |
+
pending = list(jobs)
|
| 102 |
+
while pending:
|
| 103 |
+
if used >= args.budget:
|
| 104 |
+
sys.exit(f"bütçe doldu: {used:,} >= {args.budget:,}; {len(pending)} sayfa kaldı")
|
| 105 |
+
batch, pending = pending[:args.workers], pending[args.workers:]
|
| 106 |
+
for r in pool.map(lambda j: ocr_page(client, j[0], j[1], args.model, args.effort), batch):
|
| 107 |
+
out = OCR / r["slug"] / f"{r['page']:03d}.json"
|
| 108 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 109 |
+
out.write_text(json.dumps(r, ensure_ascii=False, indent=1))
|
| 110 |
+
used += r["input_tokens"] + r["output_tokens"]
|
| 111 |
+
print(f"{r['slug']} s.{r['page']}: {r['input_tokens']}+{r['output_tokens']} (toplam {used:,})", flush=True)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
main()
|