Image Classification
ONNX
onnxruntime
document-orientation
deskew
ocr
image-preprocessing
cpu
folio-orient / evaluation /ocr_impact.py
foliokestrel's picture
Add installable offline CLI, lossless PDF quarter-turns, fast mode, edge-matched padding and reproducible OCR and DocLayNet evaluations
a4cdb00 verified
Raw History Blame Contribute Delete
5.3 kB
"""Paired historical OCR comparison on 68 source pages, one injected view each."""
import argparse
from concurrent.futures import ProcessPoolExecutor
from functools import lru_cache
import hashlib
import json
from pathlib import Path
import sys
import tempfile
from time import perf_counter
import unicodedata
from urllib.request import urlretrieve
import pyarrow.parquet as pq
import tesserocr
from rapidfuzz.distance import Levenshtein
from PIL import Image
LANGS = {
"birdsofgreatbrit02butl": "eng",
"conchologiaiconi05reev": "eng",
"daschitinskelett00prel": "deu",
"histoirenaturell10cuvi": "fra",
"pisciumquerelaee00sche": "lat",
"trudyrusskagoent161881russ": "fra+deu",
}
TESS_REV = "87416418657359cb625c412a48b6e1d6d41c29bd"
BHL_REV = "b7bda5fac0471d6d2237360abc799c6d13559465"
def norm(s):
return " ".join(unicodedata.normalize("NFKC", s).casefold().split())
@lru_cache(1)
def orienter(source):
sys.path.insert(0, str(source))
from folio_orient import PageOrienter
return PageOrienter(source / "model.onnx")
def page_score(task):
source, scans, tessdata, row, reference, turn = task
model = orienter(source)
from folio_orient import transpose_cw, correct
rng = int.from_bytes(hashlib.sha256(row["file"].encode()).digest()[:4], "big")
tilt = (1.5 + rng % 550 / 100) * (-1 if rng % 2 else 1)
im = Image.open(scans / row["file"]).convert("L")
tilted = im.rotate(
tilt, Image.Resampling.BICUBIC, expand=True, fillcolor=im.getpixel((0, 0))
)
observed = transpose_cw(tilted, (-turn) % 360)
t = perf_counter()
est = model.estimate(observed)
corrected = correct(observed, est)
prep_time = perf_counter() - t
quarter = correct(observed, {**est, "deskew_cw": None})
conditions = [
("source", im, tesserocr.PSM.AUTO),
("injected", observed, tesserocr.PSM.AUTO),
("builtin_osd", observed, tesserocr.PSM.AUTO_OSD),
("quarter_only", quarter, tesserocr.PSM.AUTO),
(
"white_padding",
correct(observed, est, fillcolor="white"),
tesserocr.PSM.AUTO,
),
("folio", corrected, tesserocr.PSM.AUTO),
]
results = {}
for name, page, psm in conditions:
# Fresh engine prevents adaptive recognition memory from leaking across conditions.
with tesserocr.PyTessBaseAPI(
path=str(tessdata), lang=LANGS[row["book"]], psm=psm
) as api:
api.SetImage(page)
api.SetSourceResolution(200)
tick = perf_counter()
recognized = norm(api.GetUTF8Text())
seconds = perf_counter() - tick
results[name] = dict(
edits=Levenshtein.distance(reference, recognized),
seconds=seconds,
characters=len(recognized),
)
return dict(
file=row["file"],
book=row["book"],
lang=LANGS[row["book"]],
target_cw=turn,
tilt_ccw=tilt,
reference_chars=len(reference),
estimate=est,
prep_seconds=prep_time,
conditions=results,
)
def main(args):
with tempfile.TemporaryDirectory() as folder:
tmp = Path(folder)
for lang in ("eng", "fra", "deu", "lat", "osd"):
urlretrieve(
f"https://raw.githubusercontent.com/tesseract-ocr/tessdata_fast/{TESS_REV}/{lang}.traineddata",
tmp / (lang + ".traineddata"),
)
metapath = tmp / "metadata.parquet"
urlretrieve(
f"https://huggingface.co/datasets/finebooks/bhl-impact-gt/resolve/{BHL_REV}/metadata.parquet",
metapath,
)
table = pq.read_table(metapath, columns=["file_name", "text"])
refs = {
Path(r["file_name"]).stem: norm(r["text"] or "") for r in table.to_pylist()
}
rows = json.loads((args.source / "evaluation/pages.json").read_text())
rows = [r for r in rows if r["split"] == "test" and r["page_type"] == "print"]
ranked = sorted(
rows,
key=lambda r: hashlib.sha256(("ocr-v1|" + r["file"]).encode()).digest(),
)
jobs = []
for i, r in enumerate(ranked):
ref = refs[Path(r["file"]).stem]
if ref:
jobs.append((args.source, args.scans, tmp, r, ref, i % 4 * 90))
with ProcessPoolExecutor(args.workers) as pool:
scores = list(pool.map(page_score, jobs))
data = dict(
tesseract=tesserocr.tesseract_version(),
tessdata_revision=TESS_REV,
results=scores,
)
args.output.write_text(json.dumps(data, indent=1) + "\n")
total = sum(r["reference_chars"] for r in scores)
for name in scores[0]["conditions"]:
print(
name,
len(scores),
total,
sum(r["conditions"][name]["edits"] for r in scores) / total,
flush=True,
)
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("scans", type=Path)
p.add_argument("output", type=Path)
p.add_argument("--workers", type=int, default=4)
args = p.parse_args()
args.source = Path(__file__).resolve().parents[1]
main(args)