Add an optional eight-way mirrored-print model, offline CLI and evaluated operating points
5c3729a verified Download evaluation/evaluate_reflection.py from foliokestrel/folio-orient: direct link, hf CLI and curl.
- Browser
- Download file 4.87 kB
-
https://huggingface.co/foliokestrel/folio-orient/resolve/main/evaluation/evaluate_reflection.py
- Command line
-
hf download hf://foliokestrel/folio-orient/evaluation/evaluate_reflection.py
-
curl -L -o evaluate_reflection.py https://huggingface.co/foliokestrel/folio-orient/resolve/main/evaluation/evaluate_reflection.py
4.87 kB
| """Evaluate eight recovery transforms on real source pages with synthetic orientation changes.""" | |
| import argparse | |
| from concurrent.futures import ProcessPoolExecutor | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import sys | |
| import numpy as np | |
| from PIL import Image, ImageOps | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from folio_orient import PageOrienter, text_patches, transpose_cw | |
| from reflect import ReflectionDetector, mean_votes | |
| _models = {} | |
| def sources(args): | |
| manifest = json.loads(args.historical_manifest.read_text()) | |
| rows = [ | |
| ("historical", args.historical / r["file"], r["book"], r["page_type"]) | |
| for r in manifest | |
| if r["split"] == args.split | |
| ] | |
| if args.split == "dev": | |
| return rows | |
| for r in json.loads((args.modern / "manifest.json").read_text()): | |
| if r["reason"] == "eligible": | |
| rows.append( | |
| ( | |
| "contemporary", | |
| args.modern / (r["page_hash"] + ".png"), | |
| r["category"], | |
| "print", | |
| ) | |
| ) | |
| for r in json.loads((args.newspapers / "manifest.json").read_text()): | |
| rows.append( | |
| ( | |
| "newspaper", | |
| args.newspapers / (r["page_id"] + ".png"), | |
| r["archive_part"], | |
| "print", | |
| ) | |
| ) | |
| return rows | |
| def run_page(task): | |
| (cohort, file, category, kind), model_path, mirror = task | |
| if model_path not in _models: | |
| _models[model_path] = ( | |
| ReflectionDetector(model_path) if mirror else PageOrienter(model_path) | |
| ) | |
| model = _models[model_path] | |
| with Image.open(file) as image: | |
| page = image.convert("L") | |
| digest = hashlib.sha256(("reflection-tilt|" + file.name).encode()).digest() | |
| tilt = (1.5 + int.from_bytes(digest[:4], "big") % 550 / 100) * ( | |
| -1 if digest[4] % 2 else 1 | |
| ) | |
| results = [] | |
| for angle in (0, tilt): | |
| tilted = ( | |
| page.rotate( | |
| angle, | |
| Image.Resampling.BICUBIC, | |
| expand=True, | |
| fillcolor=page.getpixel((0, 0)), | |
| ) | |
| if angle | |
| else page | |
| ) | |
| for turns in range(4): | |
| rotated = transpose_cw(tilted, (-90 * turns) % 360) | |
| for flipped in (False, True): | |
| observed = ImageOps.mirror(rotated) if flipped else rotated | |
| patches = text_patches(observed) | |
| votes = None | |
| if len(patches): | |
| if mirror: | |
| votes = model.votes(patches) | |
| else: | |
| # Test both handedness hypotheses with the same sampled | |
| # areas. Each four-way pass normalizes independently. | |
| paired = np.concatenate((patches, patches[..., ::-1])) | |
| logits = model.session.run(["logits"], {"patches": paired})[0] | |
| votes = np.concatenate( | |
| [mean_votes(part) for part in np.split(logits, 2)] | |
| ) | |
| results.append( | |
| dict( | |
| tilt=angle, | |
| target=turns + 4 * flipped, | |
| patches=len(patches), | |
| predicted=int(votes.argmax()) if votes is not None else None, | |
| agreement=float(votes.max()) if votes is not None else 0.0, | |
| ) | |
| ) | |
| return dict( | |
| cohort=cohort, file=file.name, category=category, page_type=kind, views=results | |
| ) | |
| if __name__ == "__main__": | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--historical", type=Path, required=True) | |
| p.add_argument("--historical-manifest", type=Path, required=True) | |
| p.add_argument("--modern", type=Path, required=True) | |
| p.add_argument("--newspapers", type=Path, required=True) | |
| p.add_argument("--model", type=Path, required=True) | |
| p.add_argument("--two-pass-baseline", action="store_true") | |
| p.add_argument("--workers", type=int, default=8) | |
| p.add_argument("output", type=Path) | |
| p.add_argument( | |
| "--split", | |
| choices=["test", "dev"], | |
| default="test", | |
| help="Dev runs on historical pages only", | |
| ) | |
| args = p.parse_args() | |
| rows = sources(args) | |
| with ProcessPoolExecutor(args.workers) as pool: | |
| result = list( | |
| pool.map( | |
| run_page, [(r, args.model, not args.two_pass_baseline) for r in rows] | |
| ) | |
| ) | |
| args.output.write_text( | |
| json.dumps( | |
| dict( | |
| model_sha256=hashlib.sha256(args.model.read_bytes()).hexdigest(), | |
| pages=result, | |
| ), | |
| indent=1, | |
| ) | |
| + "\n" | |
| ) | |