Files
Volve-DIA/scripts/04_ocr.py
lamlvh a3c175638f Add P0 infrastructure for the Volve-DIA benchmark
Set up the data, parsing and quality-control layer for a public benchmark
on the Volve daily drilling reports (DDR) and WITSML real-time data.

- Data manifest with SHA-256 hashes of the three Volve subtrees in use.
- DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447
  activities, 17 tables) with locked expected counts.
- Render QC of the publisher HTML against the XML (272,544 items).
- OCR client for the shared chandra vLLM service, with a page cache keyed
  on model, prompt hash, dpi, max_tokens and temperature, and OCR QC
  against the HTML on a 26-report pilot.
- Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and
  40 tests.
- Research plan, technical overview and progress page (in Vietnamese).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:52:22 +00:00

103 lines
4.5 KiB
Python

"""OCR the DDR PDFs with chandra (configs/ocr.yaml) into the page cache, outputs/ocr/pages/.
python scripts/04_ocr.py --pilot # one report per wellbore: 26 reports
python scripts/04_ocr.py --docs 15_9_F_12_2008_01_01,15_9_F_14_2008_06_22
python scripts/04_ocr.py --all # 1,759 reports, 3,066 pages (~5.3 h with 4 workers)
python scripts/04_ocr.py --all --limit 100 # at most 100 pages not read yet
Resumable: a page already read with the current settings is never sent again, a failed page is sent again. Run
long jobs detached (`setsid nohup scripts/runlog.sh -n ocr_full -- scripts/04_ocr.py --all > /dev/null 2>&1 &`).
Writes outputs/ocr/ddr_docs.csv: one row per report with its pages by status, OCR seconds and tokens. Exits 1 if the
service is down or a page failed in this run.
"""
from __future__ import annotations
import argparse
import collections
import sys
from pathlib import Path
import pandas as pd
from volve_dia import ocr, paths
from volve_dia.names import canonical
def pilot(pdfs: list[Path]) -> list[Path]:
"""One report per wellbore: the middle one of its reports in date order."""
by_wellbore = collections.defaultdict(list)
for p in sorted(pdfs):
by_wellbore[canonical(p.stem[: -len("_YYYY_MM_DD")])].append(p)
return [v[len(v) // 2] for _, v in sorted(by_wellbore.items())]
def doc_table(tasks: list[ocr.Task], cfg: ocr.Config) -> pd.DataFrame:
rows: dict[str, dict] = {}
for t in tasks:
r = rows.setdefault(t.file, {"report_id": Path(t.file).stem, "doc_sha256": t.doc_sha256,
"n_pages": t.n_pages, "ok": 0, "failed": 0, "skipped": 0, "missing": 0,
"looped": 0, "length_capped": 0, "seconds": 0.0, "prompt_tokens": 0,
"completion_tokens": 0})
rec = ocr.cached(t.doc_sha256, t.page, cfg)
if rec is None:
r["missing"] += 1
continue
r[rec["status"]] += 1
r["looped"] += bool(rec.get("looped"))
r["length_capped"] += rec.get("finish_reason") == "length"
r["seconds"] += rec.get("seconds") or 0.0
usage = rec.get("usage") or {}
r["prompt_tokens"] += usage.get("prompt_tokens") or 0
r["completion_tokens"] += usage.get("completion_tokens") or 0
return pd.DataFrame(rows.values())
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
which = ap.add_mutually_exclusive_group(required=True)
which.add_argument("--pilot", action="store_true")
which.add_argument("--all", action="store_true")
which.add_argument("--docs", type=lambda s: [d.strip() for d in s.split(",") if d.strip()])
ap.add_argument("--limit", type=int, help="read at most this many pages")
args = ap.parse_args()
cfg = ocr.load_config()
pdfs = sorted(paths.ddr_pdf_dir().glob("*.pdf"))
if args.docs:
unknown = sorted(set(args.docs) - {p.stem for p in pdfs})
if unknown:
print(f"no such report: {unknown}")
return 2
chosen = ({p.stem for p in pdfs} if args.all else set(args.docs) if args.docs else
{p.stem for p in pilot(pdfs)})
all_tasks = ocr.tasks_for(pdfs, paths.volve_root())
tasks = [t for t in all_tasks if Path(t.file).stem in chosen]
print(f"[ocr] {len(chosen)} reports selected", flush=True)
try:
counts = ocr.run(tasks, cfg, limit=args.limit)
except ocr.OCRError as exc:
print(f"[ocr] {exc}", flush=True)
return 1
print(f"[ocr] this run: {counts}", flush=True)
out = paths.outputs_dir() / "ocr"
out.mkdir(parents=True, exist_ok=True)
docs = doc_table(all_tasks, cfg)
docs.to_csv(out / "ddr_docs.csv", index=False)
read = docs[docs["ok"] > 0]
pages_ok = int(docs["ok"].sum())
print(f"[ocr] cache: {int((docs['ok'] == docs['n_pages']).sum())}/{len(docs)} reports fully read; pages ok "
f"{pages_ok}/{int(docs['n_pages'].sum())}, failed {int(docs['failed'].sum())}, skipped "
f"{int(docs['skipped'].sum())}, looped {int(docs['looped'].sum())}, at token cap "
f"{int(docs['length_capped'].sum())}")
if pages_ok:
print(f"[ocr] per page read: {read['seconds'].sum() / pages_ok:.1f} s, "
f"{read['completion_tokens'].sum() / pages_ok:.0f} output tokens, "
f"{read['prompt_tokens'].sum() / pages_ok:.0f} prompt tokens")
return 1 if counts["failed"] else 0
if __name__ == "__main__":
sys.exit(main())