Files
Volve-DIA/scripts/05_ocr_qc.py
lamlvh 17916650a5 Add M1: OCR hub import, WITSML, labels T1-T3, T4 questions, trial raters, draft protocol
- OCR: match the colleague's full-set Dataset Hub export to the DDRs by content
  (3,059/3,066 pages) and QC it against the HTML (CER 2.40%, exact 0.9181).
- WITSML parser and formation tops: 21 DDR wellbores with time logs, 1,384
  reports; WITSML 15/9-F-15 S is DDR 15/9-F-15.
- Deterministic labels T1-T3 (configs/labels.yaml), 1,662 T4 questions with SQL,
  pandas and raw-XML answers in full agreement.
- Trial label validation by three blind LLM raters (not an author or expert audit)
  and rater agreement script; draft protocol_v1 (not locked): split by well.
- Literature notes and BibTeX; docs, report and run_m1.sh synchronised.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 08:34:35 +00:00

159 lines
8.3 KiB
Python

"""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
python scripts/05_ocr_qc.py --source hub # after 04_ocr_hub.py: the Dataset Hub OCR export
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/ (outputs/ocr_qc_hub/ with --source hub): items.parquet, doc_metrics.csv, by_field.csv,
by_column.csv, confusions.csv, examples.csv, summary.json, summary.md.
"""
from __future__ import annotations
import argparse
import collections
import json
import sys
import pandas as pd
from rapidfuzz.distance import Levenshtein
from volve_dia import ocr, ocr_hub, 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()])
SOURCES = {"service": ("ddr_docs.csv", "ocr_qc", "chandra OCR of the PDF (OCR service)"),
"hub": ("hub_docs.csv", "ocr_qc_hub", "chandra OCR of the PDF (Dataset Hub export)")}
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--source", choices=sorted(SOURCES), default="service")
args = ap.parse_args()
docs_csv, out_name, title = SOURCES[args.source]
cfg = ocr.load_config()
def load(sha: str, n: int):
return ocr_hub.load_blocks(sha, n) if args.source == "hub" else ocr.load_blocks(sha, n, cfg)
docs = pd.read_csv(paths.outputs_dir() / "ocr" / docs_csv)
complete = docs[docs["ok"] == docs["n_pages"]]
out = paths.outputs_dir() / out_name
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, _ = load(d["doc_sha256"], int(d["n_pages"]))
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 = {
"source": args.source, "docs": len(dm), "docs_not_complete": int((docs["ok"] < docs["n_pages"]).sum()),
"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 = [f"# OCR fidelity: publisher HTML vs {title}", "",
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())