Image Classification
ONNX
onnxruntime
document-orientation
deskew
ocr
image-preprocessing
cpu
folio-orient / text-layer /study /evaluate.py
foliokestrel's picture
Add a local searchable-PDF orientation reader, a stale OCR example, and verified results on 343 USGS and 553 Bengali archive pages
88248d0 verified
Raw History Blame Contribute Delete
5.21 kB
"""Score the frozen per-volume review lists and native display policies."""
import argparse
from collections import Counter
from contextlib import closing
from hashlib import sha256
import json
from pathlib import Path
import sys
from time import perf_counter
import pypdfium2 as pdfium
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from text_angle import estimate
from unblind import reference, rows
def checkpoints(book):
turns = [r for r in book if r["native_cw"]]
excluded = [r for r in book if r["exclusion"]]
results = []
for k in (5, 10, 20):
selected = [r for r in book if r["rank"] is not None and r["rank"] <= k]
found = sum(bool(r["native_cw"]) for r in selected)
results.append(dict(k=k, reviewed=len(selected), found=found, available=len(turns),
fraction_with_known_turn=found/len(selected) if selected else None,
recall=found/len(turns) if turns else None,
random_expected_found=len(selected)*len(turns)/len(book)))
return dict(pages=len(book), turns=[{f:r[f] for f in ("page","content","rank","exclusion")} for r in turns],
excluded=[{f:r[f] for f in ("page","exclusion","native_cw")} for r in excluded],
extra_reviews=len(excluded), extra_turns=sum(bool(r["native_cw"]) for r in excluded),
budgets=results)
def counts(group):
box = {}
for name in ("leave_as_is", "osd", "text"):
methods = [r[name] for r in group]
box[name] = dict(pages=len(group), accepted=sum(a["accepted"] for a in methods),
outcomes=Counter(a["outcome"] for a in methods))
both = [r for r in group if r["osd"]["accepted"] and r["text"]["accepted"]]
box["agreement"] = dict(both_accepted=len(both), conflict=sum(r["osd"]["predicted"] != r["text"]["predicted"] for r in both))
return box
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ("pdfs", "tessdata", "output"):
parser.add_argument(name, type=Path)
args = parser.parse_args()
from scan_tables import screen, ranked, exclusion_reason
from tesseract_backend import orientation
from native_report import outcome
refs = reference()
pages = []
timings = {}
ranks = {}
for source in rows("sources.jsonl"):
if source["issue"] is not None:
continue
book = source["series"]
path = args.pdfs / f"wsp{book}.pdf"
if sha256(path.read_bytes()).hexdigest() != source["sha256"]:
raise ValueError(f"Wrong revision: {path}")
book_refs = [r for r in refs if r["series"] == book]
elapsed = Counter()
with pdfium.PdfDocument(path) as doc:
assert len(doc) == len(book_refs) == source["pages"]
start = perf_counter()
records = screen(doc)
rank = {r["page"]: n for n,r in enumerate(ranked(records,len(doc)),1)}
elapsed["thumbnail_seconds"] = perf_counter()-start
book_rows = []
for ref, record in zip(book_refs, records):
number = ref["page"]
assert number == record["page"]
with closing(doc[number-1]) as page:
start = perf_counter()
layer = estimate(page)
elapsed["text_seconds"] += perf_counter()-start
start = perf_counter()
scale = min(3,1600/max(page.get_size()))
with closing(page.render(scale=scale)) as bitmap:
image = bitmap.to_pil().convert("RGB")
elapsed["osd_render_seconds"] += perf_counter()-start
start = perf_counter()
osd = orientation(image,args.tessdata,max(70,round(72*scale)))
elapsed["osd_seconds"] += perf_counter()-start
actions = dict(leave_as_is=dict(predicted=0,accepted=True),osd=osd,text=layer)
for action in actions.values():
action["outcome"] = outcome(ref["native_cw"],action["predicted"],action["accepted"])
book_rows.append(dict(**ref, rank=rank.get(number), exclusion=exclusion_reason(record),
vertical_score=record["score"], ink=record["ink"], **actions))
ranks[book] = checkpoints(book_rows)
pages.extend(book_rows)
timings[book] = elapsed
print(f"Scored Water-Supply Paper {book}, {len(book_rows)} pages",flush=True)
pages.sort(key=lambda r:(r["series"],r["page"]))
result = dict(all=counts(pages), review=ranks)
for field in ("series", "content"):
result[field] = {str(v): counts([r for r in pages if r[field] == v]) for v in sorted({r[field] for r in pages})}
args.output.mkdir(exist_ok=True,parents=True)
for name, data in (("results",result),("timings",timings)):
(args.output/(name+".json")).write_text(json.dumps(data,indent=2)+"\n")
(args.output/"pages.jsonl").write_text("".join(json.dumps(r)+"\n" for r in pages))
print(json.dumps(result["all"]),flush=True)
if __name__ == "__main__":
main()