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>
This commit is contained in:
2026-10-29 12:45:34 +00:00
commit a3c175638f
172 changed files with 145856 additions and 0 deletions

View File

@@ -0,0 +1,84 @@
"""Write a SHA-256 manifest of the Volve data this project reads, and check it against the committed manifest.
python scripts/00_data_manifest.py # create/update data_manifest/volve_dia.json
python scripts/00_data_manifest.py --check # check only; exit 1 on a missing file or a hash mismatch
Only the subtrees in SUBTREES are hashed (~20 GB, mostly WITSML); the rest of data/Volve (well logs, seismic) is
not read by this project.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from pathlib import Path
from volve_dia.paths import REPO_ROOT, volve_root
MANIFEST = REPO_ROOT / "data_manifest" / "volve_dia.json"
DESCRIPTION = "Volve data village (Equinor and the Volve licence partners), CC BY-NC-SA 4.0"
SUBTREES = ["Well_technical_data", "Reports", "WITSML Realtime drilling data"]
def sha256(path: Path, chunk: int = 1 << 22) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
def scan(root: Path) -> dict[str, dict]:
files = sorted(p for sub in SUBTREES for p in (root / sub).rglob("*") if p.is_file())
with ThreadPoolExecutor(max_workers=8) as ex:
digests = list(ex.map(sha256, files))
return {
p.relative_to(root).as_posix(): {"size_bytes": p.stat().st_size, "sha256": d}
for p, d in zip(files, digests)
}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true")
args = ap.parse_args()
root = volve_root()
missing_dirs = [s for s in SUBTREES if not (root / s).is_dir()]
if missing_dirs:
print(f"missing under {root}: {missing_dirs}")
return 1
current = scan(root)
if args.check:
ref = json.loads(MANIFEST.read_text(encoding="utf-8"))["files"]
missing = sorted(set(ref) - set(current))
changed = sorted(k for k in set(ref) & set(current) if ref[k]["sha256"] != current[k]["sha256"])
extra = sorted(set(current) - set(ref))
for name, items in (("missing", missing), ("hash mismatch", changed), ("extra", extra)):
for k in items:
print(f"{name}: {k}")
print(f"{len(current)} files, {len(missing)} missing, {len(changed)} hash mismatch, {len(extra)} extra")
return 1 if (missing or changed) else 0
out = {
"dataset": DESCRIPTION,
"root": root.relative_to(REPO_ROOT).as_posix() if root.is_relative_to(REPO_ROOT) else str(root),
"subtrees": SUBTREES,
"created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"n_files": len(current),
"total_bytes": sum(v["size_bytes"] for v in current.values()),
"files": current,
}
MANIFEST.parent.mkdir(parents=True, exist_ok=True)
MANIFEST.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"{out['n_files']} files, {out['total_bytes'] / 1e9:.2f} GB -> {MANIFEST.relative_to(REPO_ROOT)}")
return 0
if __name__ == "__main__":
sys.exit(main())

112
scripts/01_inventory.py Normal file
View File

@@ -0,0 +1,112 @@
"""Inventory of the inputs: the three versions of every DDR, PDF pages, and the WITSML wellbores.
python scripts/01_inventory.py
Writes outputs/inventory/{ddr_files.csv, witsml_wellbores.csv, summary.json} and fails if the XML, HTML and PDF
versions do not hold the same reports.
"""
from __future__ import annotations
import json
import sys
from collections import Counter
import pandas as pd
import pymupdf
from volve_dia import paths
from volve_dia.names import canonical
from volve_dia.ocr import MEGABYTE, image_bytes, load_config
#: A page with fewer characters in its text layer than this is near-empty (or a scan). In the DDR PDFs all such
#: pages are the trailing page of a multi-page report: blank, or the last empty row of a table.
NEAR_EMPTY_CHARS = 50
def ddr_files(max_image_bytes: int) -> pd.DataFrame:
dirs = {"xml": (paths.ddr_xml_dir(), ".xml"), "html": (paths.ddr_html_dir(), ".html"),
"pdf": (paths.ddr_pdf_dir(), ".pdf")}
stems = {k: {p.stem: p for p in d.glob(f"*{ext}")} for k, (d, ext) in dirs.items()}
rows = []
for s in sorted(set().union(*stems.values())):
wb = s[: -len("_YYYY_MM_DD")]
row = {"report_id": s, "wellbore": canonical(wb), "file_date": "-".join(s.rsplit("_", 3)[1:])}
for k in dirs:
p = stems[k].get(s)
row[f"{k}_bytes"] = p.stat().st_size if p else None
pdf = stems["pdf"].get(s)
if pdf:
with pymupdf.open(pdf) as doc:
chars = [len(page.get_text()) for page in doc]
heavy = sum(image_bytes(doc, page) > max_image_bytes for page in doc)
near_empty = [i for i, c in enumerate(chars, 1) if c < NEAR_EMPTY_CHARS]
row.update(pdf_pages=len(chars), pdf_text_chars=sum(chars), pdf_near_empty_pages=len(near_empty),
pdf_near_empty_not_last=sum(i != len(chars) for i in near_empty), pdf_heavy_pages=heavy)
rows.append(row)
return pd.DataFrame(rows)
def witsml_wellbores(ddr_wellbores: set[str]) -> pd.DataFrame:
root = paths.witsml_dir()
meta = {}
for line in (root / "MetaFileInfo.txt").read_text(encoding="utf-8").splitlines():
parts = [p for p in line.split(" ") if p.strip()]
if len(parts) >= 3:
meta[parts[0].strip()] = (parts[1].strip(), parts[2].strip())
rows = []
for d in sorted(p for p in root.iterdir() if p.is_dir()):
files = [f for f in d.rglob("*") if f.is_file()]
objects = sorted({p.name for p in d.glob("*/*") if p.is_dir()}) # <folder>/<n>/{log,trajectory,...}
name, uid = meta.get(d.name, (None, None))
wb = canonical(d.name)
rows.append({"folder": d.name, "meta_name": name, "uid": uid, "wellbore": wb,
"meta_agrees": name is None or canonical(name) == wb, "in_ddr": wb in ddr_wellbores,
"has_log": "log" in objects, "objects": " ".join(objects),
"n_files": len(files), "bytes": sum(f.stat().st_size for f in files)})
return pd.DataFrame(rows)
def main() -> int:
out = paths.outputs_dir() / "inventory"
out.mkdir(parents=True, exist_ok=True)
ddr = ddr_files(load_config().max_page_image_mb * MEGABYTE)
ddr.to_csv(out / "ddr_files.csv", index=False)
complete = ddr[["xml_bytes", "html_bytes", "pdf_bytes"]].notna().all(axis=1)
ddr_wbs = set(ddr["wellbore"])
wits = witsml_wellbores(ddr_wbs)
wits.to_csv(out / "witsml_wellbores.csv", index=False)
log_wbs = set(wits.loc[wits["has_log"], "wellbore"])
summary = {
"ddr_reports": len(ddr),
"ddr_in_all_three_versions": int(complete.sum()),
"ddr_wellbores": len(ddr_wbs),
"ddr_reports_per_wellbore": {k: int(v) for k, v in sorted(Counter(ddr["wellbore"]).items())},
"ddr_bytes": {k: int(ddr[f"{k}_bytes"].sum()) for k in ("xml", "html", "pdf")},
"pdf_pages": int(ddr["pdf_pages"].sum()),
"pdf_pages_per_report": {str(k): int(v) for k, v in sorted(Counter(ddr["pdf_pages"]).items())},
"pdf_near_empty_pages": int(ddr["pdf_near_empty_pages"].sum()),
"pdf_near_empty_not_last_page": int(ddr["pdf_near_empty_not_last"].sum()),
"pdf_heavy_pages": int(ddr["pdf_heavy_pages"].sum()),
"witsml_folders": len(wits),
"witsml_wellbores": int(wits["wellbore"].nunique()),
"witsml_wellbores_with_ddr": int(wits.loc[wits["in_ddr"], "wellbore"].nunique()),
"witsml_wellbores_with_log": len(log_wbs),
"witsml_log_wellbores_with_ddr": len(log_wbs & ddr_wbs),
"witsml_folders_meta_disagrees": wits.loc[~wits["meta_agrees"], "folder"].tolist(),
"witsml_wellbores_without_ddr": sorted(set(wits.loc[~wits["in_ddr"], "wellbore"])),
"ddr_wellbores_without_witsml": sorted(ddr_wbs - set(wits["wellbore"])),
"ddr_reports_on_witsml_log_wellbores": int(ddr["wellbore"].isin(log_wbs).sum()),
"witsml_bytes": int(wits["bytes"].sum()),
}
(out / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8")
print(json.dumps({k: v for k, v in summary.items() if k != "ddr_reports_per_wellbore"}, indent=1))
if not complete.all():
print("reports missing a version:", ddr.loc[~complete, "report_id"].tolist())
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

102
scripts/02_parse_ddr.py Normal file
View File

@@ -0,0 +1,102 @@
"""Parse the DDR XML files into tables: outputs/ddr/<table>.parquet and outputs/ddr/volve_ddr.duckdb.
python scripts/02_parse_ddr.py
Fails if a count differs from EXPECTED (the counts the plan quotes), so a parser change that loses or adds rows is
caught. summary.json also holds the consistency checks of the source that the benchmark relies on.
"""
from __future__ import annotations
import json
import os
import sys
import duckdb
import pandas as pd
from volve_dia import paths
from volve_dia.ddr.xml import parse_dir
EXPECTED = {
"reports": 1759,
"wellbores": 26,
"activities": 23447,
"state": {"ok": 22967, "fail": 480},
"stateDetailActivity": {"success": 20802, "equipment failure": 1975, "operation failed": 456,
"stuck equipment": 109, "circulation loss": 92, "mud loss": 12, "injury": 1},
}
def checks(t: dict[str, pd.DataFrame]) -> dict:
r, a = t["reports"], t["activities"]
period_h = (r["end_utc"] - r["start_utc"]).dt.total_seconds() / 3600
span = a.merge(r[["report_id", "start_utc", "end_utc"]], on="report_id", suffixes=("", "_report"))
outside = (span["start_utc"] < span["start_utc_report"]) | (span["end_utc"] > span["end_utc_report"])
by_report = a.sort_values(["report_id", "seq"]).groupby("report_id")
gaps = (a.sort_values(["report_id", "seq"])["start_utc"]
- by_report["end_utc"].shift()).dt.total_seconds().div(3600).dropna()
covered = (by_report["duration_h"].sum() - period_h.set_axis(r["report_id"]).reindex(by_report.groups)).round(4)
return {
"file_date_is_period_end_date": int((r["file_date"] == r["dTimEnd"].str[:10]).sum()),
"duplicate_wellbore_dates": int(r.duplicated(["wellbore", "file_date"]).sum()),
"report_period_hours": {str(k): int(v) for k, v in period_h.round(2).value_counts().sort_index().items()},
"reports_without_activities": sorted(set(r["report_id"]) - set(a["report_id"])),
"reports_before_1990": r.loc[r["start_utc"].dt.year < 1990, "report_id"].tolist(),
"reports_sum24Hr_None": int((r["sum24Hr"].fillna("None") == "None").sum()), # published as "None"
"reports_forecast24Hr_None": int((r["forecast24Hr"].fillna("None") == "None").sum()),
"activities_missing_comments": int(a["comments"].isna().sum()),
"activities_missing_code": int(a["proprietaryCode"].isna().sum()),
"activities_nonpositive_duration": int((a["duration_h"] <= 0).sum()),
"activities_outside_report_period": int(outside.sum()),
"activity_gaps_hours": {"negative": int((gaps < 0).sum()), "zero": int((gaps == 0).sum()),
"positive": int((gaps > 0).sum())},
"activity_hours_vs_report_period": {"equal": int((covered == 0).sum()), "less": int((covered < 0).sum()),
"more": int((covered > 0).sum()),
"hours_uncovered": round(float(-covered[covered < 0].sum()), 2)},
"comment_chars_mean": round(float(a["comments"].str.len().mean()), 1),
"sum24Hr_chars_mean": round(float(r["sum24Hr"].str.len().mean()), 1),
"code_main": {k: int(v) for k, v in a["code_main"].value_counts().items()},
"codes": int(a["proprietaryCode"].nunique()),
}
def main() -> int:
out = paths.outputs_dir() / "ddr"
out.mkdir(parents=True, exist_ok=True)
tables = parse_dir(paths.ddr_xml_dir())
for name, df in tables.items():
df.to_parquet(out / f"{name}.parquet", index=False)
db, tmp = out / "volve_ddr.duckdb", out / "volve_ddr.duckdb.tmp"
tmp.unlink(missing_ok=True)
with duckdb.connect(str(tmp)) as con:
for name in tables:
con.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet('{out / name}.parquet')")
os.replace(tmp, db)
r, a = tables["reports"], tables["activities"]
got = {
"reports": len(r),
"wellbores": int(r["wellbore"].nunique()),
"activities": len(a),
"state": {k: int(v) for k, v in a["state"].value_counts().items()},
"stateDetailActivity": {k: int(v) for k, v in a["stateDetailActivity"].value_counts().items()},
}
summary = {
"counts": got,
"tables": {name: {"rows": len(df), "columns": df.shape[1]} for name, df in tables.items()},
"sentinels_replaced": int(tables["sentinels"]["n"].sum()),
"checks": checks(tables),
}
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(json.dumps({k: v for k, v in summary.items() if k != "tables"}, indent=1, ensure_ascii=False))
diff = {k: (EXPECTED[k], got[k]) for k in EXPECTED if EXPECTED[k] != got[k]}
if diff:
print("counts differ from EXPECTED (expected, got):", diff)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

92
scripts/03_render_qc.py Normal file
View File

@@ -0,0 +1,92 @@
"""Render fidelity: does the publisher HTML print what the XML source holds?
python scripts/03_render_qc.py # after 02_parse_ddr.py
ref = `qc.from_xml` of each drillReport (header lines, the header fields in `qc.FIELD_COLUMNS`, the two summaries,
the Operations table), hyp = the publisher HTML read by `rendered.parse_html`, values compared with `qc.same_value`.
The other 13 HTML tables (Drilling Fluid, Survey Station, ...) are not checked against the XML.
Writes outputs/render_qc/{items.parquet, by_key.csv, summary.json, summary.md}.
"""
from __future__ import annotations
import collections
import json
import sys
import pandas as pd
from volve_dia import paths
from volve_dia.ddr import qc
from volve_dia.ddr.rendered import parse_html
EXAMPLES = 3
def items() -> pd.DataFrame:
ddr = paths.outputs_dir() / "ddr"
reports = pd.read_parquet(ddr / "reports.parquet")
acts = collections.defaultdict(list)
for a in pd.read_parquet(ddr / "activities.parquet").to_dict("records"):
acts[a["report_id"]].append(a)
rows = []
for rep in reports.to_dict("records"):
html = (paths.ddr_html_dir() / f"{rep['report_id']}.html").read_text(encoding="utf-8")
hyp = qc.html_for_xml(parse_html(html))
for it in qc.compare(qc.from_xml(rep, acts[rep["report_id"]]), hyp, equal=qc.same_value, extras=False):
rows.append({"doc": rep["report_id"], "wellbore": rep["wellbore"], **it})
return pd.DataFrame(rows)
def main() -> int:
out = paths.outputs_dir() / "render_qc"
out.mkdir(parents=True, exist_ok=True)
df = items()
df.to_parquet(out / "items.parquet", index=False)
keys = ["part", "table", "key"]
unequal = df[~df["exact"]]
by_key = (df.groupby(keys, sort=False).agg(n=("exact", "size"), equal=("exact", "sum")).reset_index()
.merge(unequal.groupby(keys)["doc"].nunique().rename("docs_unequal").reset_index(), on=keys,
how="left")
.fillna({"docs_unequal": 0}))
by_key["rate"] = by_key["equal"] / by_key["n"]
by_key.to_csv(out / "by_key.csv", index=False)
mismatches = []
for (part, table, key), g in unequal.groupby(keys, sort=False):
pairs = collections.Counter(zip(g["ref"], g["hyp"].fillna("<absent>")))
mismatches.append({"part": part, "table": table, "key": key, "n": len(g), "docs": int(g["doc"].nunique()),
"top_pairs": [{"xml": r, "html": h, "n": n} for (r, h), n in pairs.most_common(EXAMPLES)]})
parts = df.groupby("part")["exact"].agg(["size", "sum"])
summary = {
"docs": int(df["doc"].nunique()),
"items": len(df),
"by_part": {p: {"n": int(r["size"]), "equal": int(r["sum"]), "rate": round(r["sum"] / r["size"], 6)}
for p, r in parts.iterrows()},
"docs_all_equal": int((df.groupby("doc")["exact"].all()).sum()),
"docs_all_equal_except_flags": int(df[~df["key"].isin(["tight well", "hpht"])].groupby("doc")["exact"]
.all().sum()),
"mismatches": mismatches,
}
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
lines = ["# Render fidelity: XML source vs publisher HTML", "",
f"{summary['docs']} reports, {summary['items']:,} items; values compared as printed values "
"(numbers as numbers, '', 'None' and sentinels as missing).", "",
"| part | items | equal | rate |", "|---|---:|---:|---:|"]
lines += [f"| {p} | {v['n']:,} | {v['equal']:,} | {v['rate']:.4f} |" for p, v in summary["by_part"].items()]
lines += ["", f"Reports equal everywhere: {summary['docs_all_equal']}; equal except Tight well / HPHT: "
f"{summary['docs_all_equal_except_flags']}.", "", "## Items that differ", "",
"| part | key | items | reports | most common (XML -> HTML) |", "|---|---|---:|---:|---|"]
for m in mismatches:
pairs = "; ".join(f"`{p['xml'][:40]}` -> `{p['html'][:40]}` ({p['n']})" for p in m["top_pairs"])
lines.append(f"| {m['part']} | {m['table'] + ': ' if m['table'] else ''}{m['key']} | {m['n']:,} | "
f"{m['docs']:,} | {pairs} |")
(out / "summary.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
print("\n".join(lines))
return 0
if __name__ == "__main__":
sys.exit(main())

102
scripts/04_ocr.py Normal file
View File

@@ -0,0 +1,102 @@
"""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())

143
scripts/05_ocr_qc.py Normal file
View File

@@ -0,0 +1,143 @@
"""OCR fidelity: does chandra read from the PDF what the publisher HTML prints?
python scripts/05_ocr_qc.py # after 04_ocr.py; every report whose pages are all read
ref = the publisher HTML (`rendered.parse_html`), hyp = chandra's blocks of the PDF (`rendered.parse_ocr`), compared
with `qc.exact` (whitespace collapsed, nothing else forgiven). The PDF is a render of the HTML, so the HTML is the
reference for everything printed, all 14 tables included. CER = character edits / reference characters, summed over
items; WER likewise over words. Missing items count as deletions, `*_extra` items (rows, columns, header lines,
fields, texts and tables that chandra read but the HTML does not print) as insertions. Character confusions are
counted on near misses only (edits at most `NEAR` of the reference characters): a cell read into the wrong row or
column is a structure error, not a character error.
Writes outputs/ocr_qc/{items.parquet, doc_metrics.csv, by_field.csv, by_column.csv, confusions.csv, examples.csv,
summary.json, summary.md}.
"""
from __future__ import annotations
import collections
import json
import sys
import pandas as pd
from rapidfuzz.distance import Levenshtein
from volve_dia import ocr, paths
from volve_dia.ddr import qc
from volve_dia.ddr.rendered import parse_html, parse_ocr
EXAMPLES = 5
NEAR = 0.25
CONTENT = ("header", "field", "text", "cell", "colhead") # what a reader of the report wants
def rates(g: pd.DataFrame) -> dict:
chars, words = int(g["chars"].sum()), int(g["words"].sum())
return {"n": len(g), "exact": int(g["exact"].sum()), "exact_rate": round(float(g["exact"].mean()), 4),
"chars": chars, "cer": round(g["edits"].sum() / chars, 5) if chars else None,
"wer": round(g["w_edits"].sum() / words, 5) if words else None}
def table(groups) -> pd.DataFrame:
return pd.DataFrame([{**dict(zip(("part", "table", "key"), k)), **rates(g)} for k, g in groups])
def pct(v) -> str:
return "" if v is None or pd.isna(v) else f"{v:.4%}"
def confusions(df: pd.DataFrame) -> pd.DataFrame:
"""Character substitutions, deletions and insertions of the items `hyp` read but got wrong."""
c = collections.Counter()
for r, h in zip(df["ref"], df["hyp"]):
for op in Levenshtein.editops(r, h):
c[(op.tag, r[op.src_pos] if op.tag != "insert" else "", h[op.dest_pos] if op.tag != "delete" else "")] += 1
return pd.DataFrame([{"op": t, "ref": a, "hyp": b, "n": n} for (t, a, b), n in c.most_common()])
def main() -> int:
cfg = ocr.load_config()
docs = pd.read_csv(paths.outputs_dir() / "ocr" / "ddr_docs.csv")
complete = docs[docs["ok"] == docs["n_pages"]]
out = paths.outputs_dir() / "ocr_qc"
out.mkdir(parents=True, exist_ok=True)
rows, metrics = [], []
for d in complete.to_dict("records"):
html = (paths.ddr_html_dir() / f"{d['report_id']}.html").read_text(encoding="utf-8")
blocks, _ = ocr.load_blocks(d["doc_sha256"], int(d["n_pages"]), cfg)
hyp = parse_ocr(blocks)
its = [{"doc": d["report_id"], **it} for it in qc.compare(parse_html(html), hyp)]
rows += its
g = pd.DataFrame(its)
content = g[g["part"].isin(CONTENT)]
metrics.append({"doc": d["report_id"], "pages": d["n_pages"], "blocks": len(blocks), **{
f"content_{k}": v for k, v in rates(content).items()},
"missing": int(g["hyp"].isna().sum()), "extra": int(g["part"].str.endswith("_extra").sum()),
"labels_wrong": int((~g.loc[g["part"].str.endswith("_label"), "exact"]).sum()),
"notes": " | ".join(hyp.notes), "looped": d["looped"], "length_capped": d["length_capped"],
"seconds": d["seconds"]})
if not rows:
print("no report is fully read yet: run scripts/04_ocr.py first")
return 1
df = pd.DataFrame(rows)
df.to_parquet(out / "items.parquet", index=False)
dm = pd.DataFrame(metrics)
dm.to_csv(out / "doc_metrics.csv", index=False)
fields = df[df["part"] == "field"].assign(key=lambda x: x["key"].map(qc.field_name))
by_field = table(fields.groupby(["part", "table", "key"], sort=False)).sort_values("cer", ascending=False)
by_field.to_csv(out / "by_field.csv", index=False)
cells = df[df["part"].isin(["cell", "colhead"])]
by_column = table(cells.groupby(["part", "table", "key"], sort=False)).sort_values(["table", "part", "key"])
by_column.to_csv(out / "by_column.csv", index=False)
near = df[~df["exact"] & df["hyp"].notna() & (df["chars"] > 0) & (df["edits"] <= NEAR * df["chars"])]
conf = confusions(near)
conf.to_csv(out / "confusions.csv", index=False)
examples = (df[~df["exact"]].assign(k=lambda x: x["key"].map(qc.field_name))
.groupby(["part", "table", "k"], sort=False).head(EXAMPLES)
[["doc", "part", "table", "key", "row", "ref", "hyp", "edits"]])
examples.to_csv(out / "examples.csv", index=False)
content = df[df["part"].isin(CONTENT)]
by_table = table((("cell", t, ""), g) for t, g in df[df["part"] == "cell"].groupby("table"))
notes = collections.Counter(n.split(":")[0] for s in dm["notes"] for n in s.split(" | ") if n)
summary = {
"docs": len(dm), "docs_partly_read": int(((docs["ok"] > 0) & (docs["ok"] < docs["n_pages"])).sum()),
"pages": int(dm["pages"].sum()),
"content": rates(content),
"by_part": {p: rates(g) for p, g in df.groupby("part")},
"cells_by_table": {r["table"]: {k: r[k] for k in ("n", "exact_rate", "cer")} for _, r in by_table.iterrows()},
"docs_content_exact": int((dm["content_exact"] == dm["content_n"]).sum()),
"doc_content_cer": {q: round(float(dm["content_cer"].quantile(q)), 5) for q in (0.5, 0.9, 1.0)},
"assemble_notes": dict(notes),
"near_misses": len(near),
"top_confusions": conf.head(15).to_dict("records"),
}
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
c = summary["content"]
lines = ["# OCR fidelity: publisher HTML vs chandra OCR of the PDF", "",
f"{summary['docs']} reports, {summary['pages']} pages. Content items (header, fields, texts, table "
f"cells and column heads): {c['n']:,}, exact {c['exact_rate']:.4f}, CER {pct(c['cer'])}, "
f"WER {pct(c['wer'])}.", "", "| part | items | exact rate | CER | WER |", "|---|---:|---:|---:|---:|"]
lines += [f"| {p} | {v['n']:,} | {v['exact_rate']:.4f} | {pct(v['cer'])} | {pct(v['wer'])} |"
for p, v in summary["by_part"].items()]
lines += ["", "## Table cells by table", "", "| table | cells | exact rate | CER |", "|---|---:|---:|---:|"]
lines += [f"| {t} | {v['n']:,} | {v['exact_rate']:.4f} | {pct(v['cer'])} |"
for t, v in sorted(summary["cells_by_table"].items(), key=lambda kv: -kv[1]["n"])]
lines += ["", "## Fields with errors", "", "| field | items | exact rate | CER |", "|---|---:|---:|---:|"]
lines += [f"| {r['key']} | {r['n']} | {r['exact_rate']:.4f} | {pct(r['cer'])} |"
for _, r in by_field[by_field["exact_rate"] < 1].iterrows()]
lines += ["", f"## Most common character errors (in {len(near):,} near misses)", "", "| op | ref | hyp | n |",
"|---|---|---|---:|"]
lines += [f"| {r['op']} | `{r['ref']}` | `{r['hyp']}` | {r['n']} |" for r in summary["top_confusions"]]
lines += ["", f"What `assemble` repaired: {summary['assemble_notes'] or 'nothing'}."]
(out / "summary.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
print("\n".join(lines))
return 0
if __name__ == "__main__":
sys.exit(main())

20
scripts/run_p0.sh Executable file
View File

@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Run the full P0 pipeline: data hash check → inventory → DDR XML parse → render QC → OCR pilot → OCR QC → unit tests.
# The OCR pilot sends nothing once its 47 pages are in the page cache (outputs/ocr/pages/); the full OCR run
# (scripts/04_ocr.py --all, ~5.3 h) is not part of P0: run it detached, see README.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
# Unconditional: the machine default is OMP/MKL/OPENBLAS_NUM_THREADS=40, and "${VAR:-4}" would keep that 40.
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4
# Log + runtime: the whole pipeline goes to logs/runs/<timestamp>_p0/, one subdirectory per step, one row per step in
# logs/index.csv (volve_dia/runlog.py).
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m volve_dia.runlog -n p0 -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m volve_dia.runlog -- "$@"; }
step "$PY" scripts/00_data_manifest.py --check
step "$PY" scripts/01_inventory.py
step "$PY" scripts/02_parse_ddr.py
step "$PY" scripts/03_render_qc.py
step "$PY" scripts/04_ocr.py --pilot
step "$PY" scripts/05_ocr_qc.py
step "$PY" -m pytest -q

8
scripts/runlog.sh Executable file
View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Run a command, saving log + runtime to logs/runs/<timestamp>_<name>/ and appending one row to logs/index.csv
# (details: volve_dia/runlog.py). Examples:
# scripts/runlog.sh scripts/02_parse_ddr.py # .py files are run with $PY
# scripts/runlog.sh -n ocr_full --note "full DDR corpus" -- scripts/04_ocr.py --all
# scripts/runlog.sh ls # most recent runs
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec "${PY:-$ROOT/.venv/bin/python}" -m volve_dia.runlog "$@"