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>
This commit is contained in:
281
volve_dia/ocr_hub.py
Normal file
281
volve_dia/ocr_hub.py
Normal file
@@ -0,0 +1,281 @@
|
||||
"""Import an OCR of the Volve PDF pages that was run outside this repository and exported from the internal Dataset
|
||||
Hub as one COCO file (`configs/ocr_hub.yaml`).
|
||||
|
||||
The export holds one PNG per distinct page image and, per image, chandra's blocks: category (= chandra's own label),
|
||||
pixel box ``[x, y, w, h]``, inner HTML (`text`) and `attributes.reading_order`. It does not say which PDF and page an
|
||||
image is: images are named by the sha256 of the PNG, identical PNGs are stored once (a blank page, or a second page
|
||||
that holds the same rows in two reports), and the renderer is not PyMuPDF, so no pixel or hash matches ours.
|
||||
|
||||
Each PDF page is therefore matched to an image by content, in two stages:
|
||||
|
||||
1. text: the PDF text layer and the OCR text are split into tokens (dates and depths kept whole), every image is
|
||||
scored by a hashed TF-IDF cosine, and the best `prefilter` images are re-scored by an idf-weighted token F1. The
|
||||
best `top_k` are the candidates. A page with no text layer gets the images with no text as candidates;
|
||||
2. image: the page is rendered at `thumb_dpi` in grey and correlated with each candidate image shrunk by
|
||||
2**`thumb_shrink`. A candidate shows the page if the correlation reaches `min_corr`; among those within `tie_eps`
|
||||
of the best correlation the highest text F1 wins (`select`), because two reports that differ only in a date
|
||||
correlate equally. A DDR page with no such candidate (short pages whose OCR text differs from the text layer) is
|
||||
searched by image against every image of the export (coarse correlation, best `fallback_top_k` re-scored) and
|
||||
is `missing` if that fails too.
|
||||
|
||||
A check that does not take part in the choice: every ISO date of the page's text layer (the period of page 1) must
|
||||
occur in the chosen OCR text.
|
||||
|
||||
The winner is written in chandra's page format (``<div data-bbox="x0 y0 x1 y1" data-label="...">``, box normalised
|
||||
to 0-1000) to ``outputs/ocr/hub/pages/<doc sha256[:16]>/pNNNN.json`` with its provenance and match scores, so the
|
||||
blocks parse with `ocr.html_blocks` exactly as a page read through the service. Hub pages are kept apart from the
|
||||
service cache because the prompt, renderer and settings that produced them are not recorded in the export.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
from html import unescape
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from . import ocr
|
||||
from .paths import REPO_ROOT, outputs_dir
|
||||
|
||||
CONFIG = REPO_ROOT / "configs" / "ocr_hub.yaml"
|
||||
_TAG = re.compile(r"<[^>]+>")
|
||||
_TOKEN = re.compile(r"[A-Za-z0-9]+(?:[-:./][A-Za-z0-9]+)*")
|
||||
_DATE = re.compile(r"\b(?:19|20)\d\d-[01]\d-[0-3]\d\b")
|
||||
_DIM = 1 << 14
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HubConfig:
|
||||
dir: Path
|
||||
prefilter: int
|
||||
top_k: int
|
||||
thumb_dpi: int
|
||||
thumb_shrink: int
|
||||
min_corr: float
|
||||
tie_eps: float
|
||||
fallback_top_k: int
|
||||
min_text_f1: float
|
||||
f1_min_tokens: int
|
||||
|
||||
|
||||
def load_config(path: Path = CONFIG) -> HubConfig:
|
||||
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
|
||||
raw["dir"] = REPO_ROOT / raw["dir"]
|
||||
return HubConfig(**raw)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- the export
|
||||
|
||||
@dataclass
|
||||
class Export:
|
||||
file: Path # the COCO json
|
||||
sha256: str
|
||||
images: dict[int, dict] # id -> {file_name, width, height}
|
||||
blocks: dict[int, list[dict]] # image id -> annotations in reading order
|
||||
categories: dict[int, str]
|
||||
orphans: list[str] # PNG files with no image record
|
||||
|
||||
|
||||
def load_export(hub_dir: Path) -> Export:
|
||||
files = sorted((hub_dir / "annotations").rglob("*.json"))
|
||||
if len(files) != 1:
|
||||
raise FileNotFoundError(f"expected one COCO json under {hub_dir / 'annotations'}, found {len(files)}")
|
||||
data = json.loads(files[0].read_text(encoding="utf-8"))
|
||||
cats = {c["id"]: c["name"] for c in data["categories"]}
|
||||
images = {im["id"]: im for im in data["images"]}
|
||||
blocks: dict[int, list[dict]] = collections.defaultdict(list)
|
||||
for a in data["annotations"]:
|
||||
blocks[a["image_id"]].append(a)
|
||||
for v in blocks.values():
|
||||
v.sort(key=lambda a: ((a.get("attributes") or {}).get("reading_order", 0), a["id"]))
|
||||
named = {im["file_name"] for im in images.values()}
|
||||
orphans = sorted(f"images/{p.name}" for p in (hub_dir / "images").glob("*.png") if f"images/{p.name}" not in named)
|
||||
return Export(files[0], ocr.sha256_file(files[0]), images, dict(blocks), cats, orphans)
|
||||
|
||||
|
||||
def page_content(anns: list[dict], cats: dict[int, str], width: float, height: float) -> str:
|
||||
"""chandra's page answer for the blocks of one image: one ``<div>`` per block, box normalised to 0-1000."""
|
||||
out = []
|
||||
for a in anns:
|
||||
x, y, w, h = a["bbox"]
|
||||
box = " ".join(str(round(v)) for v in (1000 * x / width, 1000 * y / height,
|
||||
1000 * (x + w) / width, 1000 * (y + h) / height))
|
||||
out.append(f'<div data-bbox="{box}" data-label="{cats[a["category_id"]]}">\n{a.get("text") or ""}\n</div>')
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- text stage
|
||||
|
||||
def tokens(text: str) -> list[str]:
|
||||
return _TOKEN.findall(unescape(_TAG.sub(" ", text)).lower())
|
||||
|
||||
|
||||
def iso_dates(text: str) -> set[str]:
|
||||
return set(_DATE.findall(text))
|
||||
|
||||
|
||||
def _hashed_tfidf(docs: list[list[str]], idf: np.ndarray) -> np.ndarray:
|
||||
m = np.zeros((len(docs), _DIM), np.float32)
|
||||
for i, toks in enumerate(docs):
|
||||
for h, n in collections.Counter(zlib.crc32(t.encode()) % _DIM for t in toks).items():
|
||||
m[i, h] = (1 + np.log(n)) * idf[h]
|
||||
norm = np.linalg.norm(m, axis=1)
|
||||
norm[norm == 0] = 1
|
||||
return m / norm[:, None]
|
||||
|
||||
|
||||
class TextIndex:
|
||||
"""Token statistics of the pages (document frequencies) and the images, for the text stage."""
|
||||
|
||||
def __init__(self, page_toks: list[list[str]], image_toks: list[list[str]]):
|
||||
n = self.n = len(page_toks)
|
||||
df_hash = collections.Counter()
|
||||
self.df_tok = collections.Counter()
|
||||
for toks in page_toks:
|
||||
df_hash.update({zlib.crc32(t.encode()) % _DIM for t in toks})
|
||||
self.df_tok.update(set(toks))
|
||||
idf = np.full(_DIM, np.log(n + 1) + 1, np.float32)
|
||||
for h, c in df_hash.items():
|
||||
idf[h] = np.log((n + 1) / (c + 1)) + 1
|
||||
self.sim = _hashed_tfidf(page_toks, idf) @ _hashed_tfidf(image_toks, idf).T
|
||||
self.page_counts = [collections.Counter(t) for t in page_toks]
|
||||
self.img_counts = [collections.Counter(t) for t in image_toks]
|
||||
self.page_weight = [self._weight(c) for c in self.page_counts]
|
||||
self.img_weight = [self._weight(c) for c in self.img_counts]
|
||||
self.empty = [i for i, t in enumerate(image_toks) if not t]
|
||||
|
||||
def _weight(self, c: collections.Counter) -> float:
|
||||
return sum(k * (np.log((self.n + 1) / (self.df_tok.get(t, 0) + 1)) + 1) for t, k in c.items())
|
||||
|
||||
def f1(self, j: int, i: int) -> float:
|
||||
"""idf-weighted token-multiset F1 of page j and image i (1 if both have no text)."""
|
||||
den = self.page_weight[j] + self.img_weight[i]
|
||||
return 2 * self._weight(self.page_counts[j] & self.img_counts[i]) / den if den else 1.0
|
||||
|
||||
def candidates(self, j: int, prefilter: int, top_k: int) -> list[tuple[int, float]]:
|
||||
if not self.page_counts[j]:
|
||||
return [(i, 1.0) for i in self.empty][:top_k]
|
||||
scored = [(int(i), self.f1(j, int(i))) for i in np.argsort(-self.sim[j])[:prefilter]]
|
||||
scored.sort(key=lambda s: -s[1])
|
||||
return scored[:top_k]
|
||||
|
||||
|
||||
def text_candidates(page_toks: list[list[str]], image_toks: list[list[str]], prefilter: int,
|
||||
top_k: int) -> list[list[tuple[int, float]]]:
|
||||
"""For every page, up to `top_k` (image index, idf-weighted token F1), best first."""
|
||||
ix = TextIndex(page_toks, image_toks)
|
||||
return [ix.candidates(j, prefilter, top_k) for j in range(len(page_toks))]
|
||||
|
||||
|
||||
def select(scored: list[tuple[float, float, int]], min_corr: float, tie_eps: float,
|
||||
min_f1: float = 0.0) -> tuple[float, float, int] | None:
|
||||
"""Pick the image of a page from its candidates (corr, text F1, image index).
|
||||
|
||||
The image correlation decides whether a candidate shows the page at all; it cannot tell apart two reports that
|
||||
differ only in a date or a number (their thumbnails correlate equally). So among the candidates that reach
|
||||
`min_corr` and `min_f1` and lie within `tie_eps` of the best correlation, the one with the highest text F1 wins
|
||||
(then the higher correlation). `min_f1` keeps a page with a text layer from taking the image of another report
|
||||
with the same layout (a first page of another day). None if no candidate passes."""
|
||||
ok = [s for s in scored if s[0] >= min_corr and s[1] >= min_f1]
|
||||
if not ok:
|
||||
return None
|
||||
top = max(s[0] for s in ok)
|
||||
return max((s for s in ok if s[0] >= top - tie_eps), key=lambda s: (s[1], s[0]))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- image stage
|
||||
|
||||
def _grey(pix) -> np.ndarray:
|
||||
import pymupdf
|
||||
|
||||
if pix.n != 1 or pix.alpha:
|
||||
pix = pymupdf.Pixmap(pymupdf.csGRAY, pix)
|
||||
return np.frombuffer(pix.samples, np.uint8).reshape(pix.h, pix.stride)[:, : pix.w].copy()
|
||||
|
||||
|
||||
def image_thumb(path: Path, shrink: int) -> np.ndarray:
|
||||
import pymupdf
|
||||
|
||||
pix = pymupdf.Pixmap(str(path))
|
||||
if pix.alpha:
|
||||
pix = pymupdf.Pixmap(pix, 0)
|
||||
pix.shrink(shrink)
|
||||
return _grey(pix)
|
||||
|
||||
|
||||
def page_thumb(doc, page: int, dpi: int) -> np.ndarray:
|
||||
import pymupdf
|
||||
|
||||
return _grey(doc[page - 1].get_pixmap(dpi=dpi, colorspace=pymupdf.csGRAY))
|
||||
|
||||
|
||||
COARSE = (146, 103) # a 50 dpi A4 page, or a 1653 x 2339 image shrunk by 4, averaged over 4 x 4 blocks
|
||||
|
||||
|
||||
def coarse(a: np.ndarray, f: int = 4) -> np.ndarray:
|
||||
"""A thumbnail averaged over f x f blocks into the fixed shape COARSE (cropped or padded with white), flattened,
|
||||
centred and scaled to unit norm, so that a dot product of two is their correlation."""
|
||||
h, w = COARSE[0] * f, COARSE[1] * f
|
||||
b = np.full((h, w), 255, np.float32)
|
||||
b[: min(h, a.shape[0]), : min(w, a.shape[1])] = a[:h, :w]
|
||||
v = b.reshape(COARSE[0], f, COARSE[1], f).mean(axis=(1, 3)).ravel()
|
||||
v -= v.mean()
|
||||
n = float(np.linalg.norm(v))
|
||||
return v / n if n > 0 else v
|
||||
|
||||
|
||||
def correlation(a: np.ndarray, b: np.ndarray) -> float:
|
||||
"""Pearson correlation of two grey thumbnails over their common top-left area (sizes differ by a pixel)."""
|
||||
h, w = min(a.shape[0], b.shape[0]), min(a.shape[1], b.shape[1])
|
||||
x = a[:h, :w].astype(np.float32).ravel()
|
||||
y = b[:h, :w].astype(np.float32).ravel()
|
||||
x -= x.mean()
|
||||
y -= y.mean()
|
||||
den = float(np.sqrt((x @ x) * (y @ y)))
|
||||
return float(x @ y / den) if den > 0 else float(np.array_equal(a[:h, :w], b[:h, :w]))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- page records
|
||||
|
||||
def cache_dir() -> Path:
|
||||
return outputs_dir() / "ocr" / "hub" / "pages"
|
||||
|
||||
|
||||
def page_file(doc_sha256: str, page: int) -> Path:
|
||||
return cache_dir() / doc_sha256[:16] / f"p{page:04d}.json"
|
||||
|
||||
|
||||
def write_page(rec: dict) -> None:
|
||||
f = page_file(rec["doc_sha256"], rec["page"])
|
||||
f.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = f.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
tmp.replace(f)
|
||||
|
||||
|
||||
def load_blocks(doc_sha256: str, n_pages: int) -> tuple[list[ocr.Block], list[dict]]:
|
||||
"""Blocks of a document from the hub import, in page and reading order, like `ocr.load_blocks`."""
|
||||
blocks: list[ocr.Block] = []
|
||||
records = []
|
||||
for page in range(1, n_pages + 1):
|
||||
f = page_file(doc_sha256, page)
|
||||
if not f.is_file():
|
||||
records.append({"page": page, "status": "missing"})
|
||||
continue
|
||||
rec = json.loads(f.read_text(encoding="utf-8"))
|
||||
records.append({k: v for k, v in rec.items() if k != "content"})
|
||||
if rec["status"] == "ok":
|
||||
blocks += ocr.html_blocks(rec["content"], page)
|
||||
return blocks, records
|
||||
|
||||
|
||||
def content_sha256(content: str) -> str:
|
||||
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||
Reference in New Issue
Block a user