OpenAI math manuscripts: LaTeX sources + OCR reasoning summaries (openai/math@adc7f12)
c6e5669 verified Download scripts/ocr_reasoning.py from ituperceptron/openai-math: direct link, hf CLI and curl.
- Browser
- Download file 5.96 kB
-
https://huggingface.co/datasets/ituperceptron/openai-math/resolve/main/scripts/ocr_reasoning.py
- Command line
-
hf download hf://datasets/ituperceptron/openai-math/scripts/ocr_reasoning.py
-
curl -L -o ocr_reasoning.py https://huggingface.co/datasets/ituperceptron/openai-math/resolve/main/scripts/ocr_reasoning.py
5.96 kB
| """openai/math reasoning_traces PDF'lerini sayfa sayfa OpenAI vision ile Markdown+LaTeX'e çevirir. | |
| Her sayfa için görüntü ve PyMuPDF metin katmanı birlikte gönderilir: kelimeler metin | |
| katmanından doğru okunur, formül yapısı görüntüden kurulur. Sonuç sayfa başına | |
| `raw/ocr/<slug>/<sayfa>.json` olarak saklanır; yeniden çalıştırınca biten sayfalar atlanır. | |
| Kota 1M grubundan düşer; `--budget` aşılmadan durur (önceki çalıştırmalar dahil). | |
| python3 ocr_reasoning.py --pages irrationality-exponent-of-pi:5 # pilot | |
| python3 ocr_reasoning.py # hepsi | |
| """ | |
| import argparse | |
| import base64 | |
| import json | |
| import sys | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| import fitz | |
| from dotenv import load_dotenv | |
| from openai import OpenAI | |
| HERE = Path(__file__).parent | |
| TRACES = HERE / "raw" / "math" / "reasoning_traces" | |
| OCR = HERE / "raw" / "ocr" | |
| MODEL = "gpt-6-sol" | |
| EFFORT = "none" | |
| DPI = 150 | |
| 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. | |
| 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. | |
| Rules: | |
| - Transcribe everything on the page in reading order, verbatim. Do not summarize, correct, complete, or add anything. | |
| - 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. | |
| - Headings as Markdown headings (#, ##, ###) matching the visual hierarchy. Keep bold/italic. Lists as Markdown lists. Tables as Markdown tables. | |
| - 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). | |
| - Join lines that wrap within a paragraph; remove hyphenation introduced by line breaks; separate paragraphs with one blank line. | |
| - Omit running headers, footers and page numbers. | |
| - If the page begins or ends mid-sentence, begin or end mid-sentence as well. | |
| - Keep URLs, citation markers like [17], and reference list entries exactly. | |
| Output only the page's Markdown, with no preamble and no surrounding code fence.""" | |
| def page_inputs(pdf: Path, index: int): | |
| with fitz.open(pdf) as doc: | |
| page = doc[index] | |
| png = page.get_pixmap(dpi=DPI).tobytes("png") | |
| text = page.get_text("text") | |
| return base64.b64encode(png).decode(), text | |
| def ocr_page(client: OpenAI, pdf: Path, index: int, model: str, effort: str) -> dict: | |
| img, text = page_inputs(pdf, index) | |
| resp = client.responses.create( | |
| model=model, | |
| reasoning={"effort": effort}, | |
| input=[{"role": "user", "content": [ | |
| {"type": "input_text", "text": PROMPT}, | |
| {"type": "input_text", "text": f"Text layer of page {index + 1}:\n<<<\n{text}\n>>>"}, | |
| {"type": "input_image", "image_url": f"data:image/png;base64,{img}", "detail": "high"}, | |
| ]}], | |
| ) | |
| if resp.status != "completed": | |
| raise RuntimeError(f"{pdf.stem} s.{index + 1}: {resp.status} {resp.incomplete_details}") | |
| u = resp.usage | |
| return {"slug": pdf.stem, "page": index + 1, "model": model, "markdown": resp.output_text.strip(), | |
| "input_tokens": u.input_tokens, "output_tokens": u.output_tokens, | |
| "reasoning_tokens": u.output_tokens_details.reasoning_tokens} | |
| def spent() -> int: | |
| return sum(r["input_tokens"] + r["output_tokens"] | |
| for r in (json.loads(p.read_text()) for p in OCR.glob("*/*.json"))) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--pages", nargs="*", help="slug:sayfa (1 tabanlı); verilmezse tüm PDF'ler") | |
| ap.add_argument("--model", default=MODEL) | |
| ap.add_argument("--effort", default=EFFORT, help="modelin desteklediği en düşük reasoning effort") | |
| ap.add_argument("--budget", type=int, default=900_000, help="tüm çalıştırmalar için toplam token sınırı") | |
| ap.add_argument("--workers", type=int, default=8) | |
| args = ap.parse_args() | |
| load_dotenv(HERE.parents[1] / ".env") | |
| client = OpenAI() | |
| if args.pages: | |
| jobs = [(TRACES / f"{s.split(':')[0]}.pdf", int(s.split(':')[1]) - 1) for s in args.pages] | |
| else: | |
| jobs = [] | |
| for pdf in sorted(TRACES.glob("*.pdf")): | |
| with fitz.open(pdf) as doc: | |
| jobs += [(pdf, i) for i in range(doc.page_count)] | |
| jobs = [(pdf, i) for pdf, i in jobs if not (OCR / pdf.stem / f"{i + 1:03d}.json").exists()] | |
| used = spent() | |
| print(f"{len(jobs)} sayfa kaldı, şimdiye kadar {used:,} token", flush=True) | |
| with ThreadPoolExecutor(args.workers) as pool: | |
| pending = list(jobs) | |
| while pending: | |
| if used >= args.budget: | |
| sys.exit(f"bütçe doldu: {used:,} >= {args.budget:,}; {len(pending)} sayfa kaldı") | |
| batch, pending = pending[:args.workers], pending[args.workers:] | |
| for r in pool.map(lambda j: ocr_page(client, j[0], j[1], args.model, args.effort), batch): | |
| out = OCR / r["slug"] / f"{r['page']:03d}.json" | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| out.write_text(json.dumps(r, ensure_ascii=False, indent=1)) | |
| used += r["input_tokens"] + r["output_tokens"] | |
| print(f"{r['slug']} s.{r['page']}: {r['input_tokens']}+{r['output_tokens']} (toplam {used:,})", flush=True) | |
| if __name__ == "__main__": | |
| main() | |