`` 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'
\n{a.get("text") or ""}\n
')
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()