"""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())