"""Import the Dataset Hub OCR export (configs/ocr_hub.yaml) as page records of the DDR PDFs, outputs/ocr/hub/. python scripts/04_ocr_hub.py Every PDF page under the Volve root (the 3,066 DDR pages and the other PDFs, so that every image is accounted for) is matched to an image of the export by text, then by image (`volve_dia.ocr_hub`). Only DDR pages are written as page records. Writes outputs/ocr/hub/{pages/, match.csv, candidates.csv, service_vs_hub.csv, summary.json} and outputs/ocr/hub_docs.csv (one row per report, the columns of ddr_docs.csv). The summary checks the dates of every dated page against its OCR text and how much the choice depends on `tie_eps`. DDR pages the export does not hold are written with status `missing` and listed in the summary. """ from __future__ import annotations import json import shutil import sys import time from pathlib import Path import pandas as pd from rapidfuzz.distance import Levenshtein from volve_dia import ocr, ocr_hub, paths def pdf_pages(root: Path) -> pd.DataFrame: import pymupdf rows = [] for p in sorted(q for q in root.rglob("*") if q.suffix.lower() == ".pdf"): sha = ocr.sha256_file(p) with pymupdf.open(p) as doc: for k, page in enumerate(doc, 1): rows.append({"file": str(p.relative_to(root)), "doc_sha256": sha, "page": k, "n_pages": doc.page_count, "text": page.get_text()}) df = pd.DataFrame(rows) df["ddr"] = df["file"].str.startswith(str(paths.ddr_pdf_dir().relative_to(root)) + "/") return df def page_text(content: str) -> str: return "\n".join(b.text for b in ocr.html_blocks(content, 1)) def main() -> int: t0 = time.time() hc = ocr_hub.load_config() exp = ocr_hub.load_export(hc.dir) root = paths.volve_root() pages = pdf_pages(root) print(f"[hub] export {exp.file.name}: {len(exp.images)} images, {sum(map(len, exp.blocks.values()))} blocks, " f"{len(exp.orphans)} PNGs without a record; {len(pages)} PDF pages ({int(pages['ddr'].sum())} DDR)", flush=True) ids = sorted(exp.images) contents = [ocr_hub.page_content(exp.blocks.get(i, []), exp.categories, exp.images[i]["width"], exp.images[i]["height"]) for i in ids] img_toks = [ocr_hub.tokens(c) for c in contents] img_dates = [ocr_hub.iso_dates(" ".join(t)) for t in img_toks] page_toks = [ocr_hub.tokens(t) for t in pages["text"]] ix = ocr_hub.TextIndex(page_toks, img_toks) print(f"[hub] text index done ({time.time() - t0:.0f} s)", flush=True) import numpy as np import pymupdf thumbs: dict[int, object] = {} def thumb(i: int): if i not in thumbs: thumbs[i] = ocr_hub.image_thumb(hc.dir / exp.images[ids[i]]["file_name"], hc.thumb_shrink) return thumbs[i] coarse_all = None def by_image(j: int, pt) -> list[tuple[int, float]]: """Fallback: the best images of the whole export by coarse correlation, with their text F1.""" nonlocal coarse_all if coarse_all is None: coarse_all = np.stack([ocr_hub.coarse(ocr_hub.image_thumb(hc.dir / exp.images[i]["file_name"], hc.thumb_shrink)) for i in ids]) print(f"[hub] coarse thumbnails of all images ({time.time() - t0:.0f} s)", flush=True) return [(int(i), ix.f1(j, int(i))) for i in np.argsort(-(coarse_all @ ocr_hub.coarse(pt)))[:hc.fallback_top_k]] page_thumbs = {} rows, cand_rows = [], [] open_doc = (None, None) for j, r in enumerate(pages.itertuples(index=False)): if open_doc[0] != r.file: if open_doc[1] is not None: open_doc[1].close() open_doc = (r.file, pymupdf.open(root / r.file)) pt = ocr_hub.page_thumb(open_doc[1], r.page, hc.thumb_dpi) cands = ix.candidates(j, hc.prefilter, hc.top_k) stage = "text" min_f1 = hc.min_text_f1 if len(page_toks[j]) >= hc.f1_min_tokens else 0.0 scored = [(ocr_hub.correlation(pt, thumb(i)), f1, i) for i, f1 in cands] best = ocr_hub.select(scored, hc.min_corr, hc.tie_eps, min_f1) if best is None and r.ddr: stage = "image" seen = {s[2] for s in scored} scored += [(ocr_hub.correlation(pt, thumb(i)), f1, i) for i, f1 in by_image(j, pt) if i not in seen] best = ocr_hub.select(scored, hc.min_corr, hc.tie_eps, min_f1) scored.sort(reverse=True) if r.ddr: cand_rows += [{"file": r.file, "page": r.page, "image_id": ids[i], "corr": round(c, 4), "text_f1": round(f1, 4)} for c, f1, i in scored] if best is None: if r.ddr: page_thumbs[j] = pt stage = "none" best = scored[0] if scored else (0.0, 0.0, -1) others = [s[0] for s in scored if s[2] != best[2]] dates = ocr_hub.iso_dates(r.text) rows.append({"file": r.file, "doc_sha256": r.doc_sha256, "page": r.page, "n_pages": r.n_pages, "ddr": r.ddr, "pdf_tokens": len(page_toks[j]), "image_id": ids[best[2]] if best[2] >= 0 else None, "image_file": exp.images[ids[best[2]]]["file_name"] if best[2] >= 0 else None, "corr": round(best[0], 4), "corr_other": round(max(others), 4) if others else None, "text_f1": round(best[1], 4), "text_f1_max": round(max((s[1] for s in scored), default=0.0), 4), "stage": stage, "matched": stage != "none", "pdf_dates": len(dates), "dates_agree": (dates <= img_dates[best[2]]) if dates and stage != "none" else None}) if j % 500 == 0: print(f"[hub] {j}/{len(pages)} pages ({time.time() - t0:.0f} s)", flush=True) if open_doc[1] is not None: open_doc[1].close() m = pd.DataFrame(rows) cand = pd.DataFrame(cand_rows) # Orphan PNGs (no record, so no OCR text): which unmatched DDR page do they show? orphan_rows = [] for name in exp.orphans: ot = ocr_hub.image_thumb(hc.dir / name, hc.thumb_shrink) best = max(((ocr_hub.correlation(pt, ot), j) for j, pt in page_thumbs.items()), default=(0.0, -1)) orphan_rows.append({"image_file": name, "corr": round(best[0], 4), "file": pages["file"].iat[best[1]] if best[1] >= 0 else None, "page": int(pages["page"].iat[best[1]]) if best[1] >= 0 else None}) orphans = pd.DataFrame(orphan_rows, columns=["image_file", "corr", "file", "page"]) out = paths.outputs_dir() / "ocr" / "hub" out.mkdir(parents=True, exist_ok=True) m.to_csv(out / "match.csv", index=False) cand.to_csv(out / "candidates.csv", index=False) # How much does the choice depend on tie_eps? Re-select every DDR page for a grid of values and check the dates. id_dates = dict(zip(ids, img_dates)) page_dates = {(f, p): ocr_hub.iso_dates(t) for f, p, t in pages[pages["ddr"]][["file", "page", "text"]].values} floor = {(f, p): hc.min_text_f1 if t >= hc.f1_min_tokens else 0.0 for f, p, t in m[m["ddr"]][["file", "page", "pdf_tokens"]].values} sens = [] for eps in (0.0, 0.002, 0.005, 0.01, 0.02, 0.05): picks = {k: ocr_hub.select(list(zip(g["corr"], g["text_f1"], g["image_id"])), hc.min_corr, eps, floor[k]) for k, g in cand.groupby(["file", "page"])} final = dict(zip(zip(m["file"], m["page"]), m["image_id"].where(m["matched"]))) dated = [k for k, d in page_dates.items() if d and picks.get(k)] sens.append({"tie_eps": eps, "matched": sum(v is not None for v in picks.values()), "differs_from_used": sum((v[2] if v else None) != final.get(k) for k, v in picks.items() if not (v is None and pd.isna(final.get(k)))), "dated_pages": len(dated), "dates_disagree": sum(not page_dates[k] <= id_dates[picks[k][2]] for k in dated)}) # Page records of the DDR pages. shutil.rmtree(ocr_hub.cache_dir(), ignore_errors=True) by_id = dict(zip(ids, contents)) ddr = m[m["ddr"]] shared = ddr[ddr["matched"]].groupby("image_id")["file"].transform("size") for r in ddr.assign(shared=shared).itertuples(index=False): rec = {"doc_sha256": r.doc_sha256, "file": r.file, "page": r.page, "n_pages": r.n_pages, "source": "hub", "export_file": exp.file.name, "export_sha256": exp.sha256, "status": "ok" if r.matched else "missing", "blank_pdf_page": r.pdf_tokens == 0, "image_file": r.image_file if r.matched else None, "match": {"stage": r.stage, "corr": r.corr, "corr_other": r.corr_other, "text_f1": r.text_f1, "text_f1_max": r.text_f1_max, "dates_agree": None if pd.isna(r.dates_agree) else bool(r.dates_agree), "pages_sharing_image": int(r.shared) if r.matched else 0}} if r.matched: rec["content"] = by_id[r.image_id] rec["content_sha256"] = ocr_hub.content_sha256(rec["content"]) ocr_hub.write_page(rec) docs = (ddr.assign(report_id=ddr["file"].map(lambda f: Path(f).stem), ok=ddr["matched"].astype(int), missing=(~ddr["matched"]).astype(int)) .groupby(["report_id", "doc_sha256", "n_pages"], as_index=False)[["ok", "missing"]].sum()) for col in ("failed", "skipped", "looped", "length_capped", "prompt_tokens", "completion_tokens"): docs[col] = 0 docs["seconds"] = 0.0 docs = docs[["report_id", "doc_sha256", "n_pages", "ok", "failed", "skipped", "missing", "looped", "length_capped", "seconds", "prompt_tokens", "completion_tokens"]] docs.to_csv(paths.outputs_dir() / "ocr" / "hub_docs.csv", index=False) # The same pages read through the service (the pilot): how far apart are the two OCRs? cfg = ocr.load_config() comp = [] for r in ddr[ddr["matched"]].itertuples(index=False): rec = ocr.cached(r.doc_sha256, r.page, cfg) if rec is None or rec["status"] != "ok": continue a, b = page_text(rec["content"]), page_text(by_id[r.image_id]) comp.append({"file": r.file, "page": r.page, "service_chars": len(a), "hub_chars": len(b), "edits": Levenshtein.distance(a, b), "identical": a == b, "service_blocks": len(ocr.html_blocks(rec["content"], 1)), "hub_blocks": len(ocr.html_blocks(by_id[r.image_id], 1))}) comp = pd.DataFrame(comp) comp.to_csv(out / "service_vs_hub.csv", index=False) used = set(m.loc[m["matched"], "image_id"]) nonblank = ddr[ddr["pdf_tokens"] > 0] same_text = ddr[ddr["matched"]].groupby("image_id")["pdf_tokens"].nunique() summary = { "export_file": exp.file.name, "export_sha256": exp.sha256, "images": len(ids), "blocks": sum(map(len, exp.blocks.values())), "orphan_pngs": len(exp.orphans), "pdf_pages": len(m), "ddr_pages": len(ddr), "ddr_pages_matched": int(ddr["matched"].sum()), "ddr_blank_pages": int((ddr["pdf_tokens"] == 0).sum()), "ddr_blank_pages_matched": int(ddr.loc[ddr["pdf_tokens"] == 0, "matched"].sum()), "ddr_text_pages_missing": nonblank.loc[~nonblank["matched"], ["file", "page", "corr"]].to_dict("records"), "ddr_reports": len(docs), "ddr_reports_complete": int((docs["ok"] == docs["n_pages"]).sum()), "other_pages_matched": int(m.loc[~m["ddr"], "matched"].sum()), "other_pages": int((~m["ddr"]).sum()), "images_used": len(used), "images_unused": len(ids) - len(used), "images_shared_by_ddr_pages": int((ddr[ddr["matched"]].groupby("image_id").size() > 1).sum()), "shared_images_with_different_token_counts": int((same_text > 1).sum()), "ddr_corr_quantiles": {q: round(float(ddr.loc[ddr["matched"], "corr"].quantile(q)), 4) for q in (0.0, 0.01, 0.5)}, "ddr_stage": ddr["stage"].value_counts().to_dict(), "ddr_ties_within_eps": int((ddr["matched"] & (ddr["corr_other"] >= ddr["corr"] - hc.tie_eps)).sum()), "ddr_text_f1_below_candidate_max": int((ddr["matched"] & (ddr["text_f1"] < ddr["text_f1_max"])).sum()), "ddr_dated_pages": int(ddr["dates_agree"].notna().sum()), "ddr_dates_disagree": ddr.loc[ddr["dates_agree"] == False, # noqa: E712 ["file", "page", "image_id", "stage", "corr", "text_f1"]].to_dict("records"), "ddr_rejected_by_text_f1": int((~ddr["matched"] & (ddr["corr"] >= hc.min_corr)).sum()), "tie_eps_sensitivity": sens, "orphans": orphans.to_dict("records"), "service_vs_hub": {"pages": len(comp), "identical_pages": int(comp["identical"].sum()) if len(comp) else 0, "char_edit_rate": round(comp["edits"].sum() / comp["service_chars"].sum(), 5) if len(comp) else None}, "seconds": round(time.time() - t0, 1), } (out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") print(json.dumps(summary, indent=1, ensure_ascii=False)) return 0 if __name__ == "__main__": sys.exit(main())