"""Select reproducible successes and counterexamples from the complete held-out comparison.""" from hashlib import sha256 from io import BytesIO import json from pathlib import Path import sys from PIL import Image import pyarrow.parquet as pq from folio_orient import transpose_cw, visible_page def select(evaluation): arms = {} for arm in ("original", "control", "manuscript"): arms[arm] = { (r["id"], r["injected"]): r for r in map( json.loads, (evaluation / (arm + "-full.jsonl")).read_text().splitlines(), ) } keys = sorted(arms["manuscript"]) assert all(set(a) == set(keys) for a in arms.values()) def correct(r): return ( r["truth"] is not None and r["predicted"] == r["truth"] and r["agreement"] >= 0.70 ) chosen = {} for k in keys: new, old = arms["manuscript"][k], arms["original"][k] if ( new["content"] == "handwritten entries or prose" and new["truth"] != 0 and correct(new) and not correct(old) ): chosen["recovered"] = k break for k in keys: r = arms["manuscript"][k] if ( r["truth"] is not None and r["predicted"] != r["truth"] and r["agreement"] >= 0.70 ): chosen["wrong-turn"] = k break if "wrong-turn" not in chosen: for k in keys: r = arms["manuscript"][k] if r["truth"] is not None and r["predicted"] != r["truth"]: chosen["referred-error"] = k break for k in keys: r = arms["manuscript"][k] if ( r["truth"] is None and r["predicted"] not in (None, 0) and r["agreement"] >= 0.70 ): chosen["indeterminate"] = k break return { name: {a: rows[k] for a, rows in arms.items()} for name, k in chosen.items() } def write(evaluation, bench, references, out): choices = select(evaluation) refs = {r["id"]: r for r in map(json.loads, references.read_text().splitlines())} for part in ("validation", "test"): for batch in pq.ParquetFile(bench / "data" / (part + ".parquet")).iter_batches( batch_size=2, columns=["id", "image"] ): for row in batch.to_pylist(): for name, scan in choices.items(): data = scan["manuscript"] if row["id"] != data["id"]: continue raw = row["image"]["bytes"] ref = refs[row["id"]] assert sha256(raw).hexdigest() == ref["image_sha256"] with Image.open(BytesIO(raw)) as im: source = visible_page(im) transpose_cw(source, data["injected"]).save(out / (name + ".png")) scan["source_image"] = ref["source_image"] scan["source_sha256"] = ref["image_sha256"] assert all((out / (s + ".png")).exists() for s in choices) (out / "examples.json").write_text(json.dumps(choices, indent=2) + "\n") print( { k: ( v["manuscript"]["truth"], v["manuscript"]["predicted"], v["manuscript"]["agreement"], ) for k, v in choices.items() } ) if __name__ == "__main__": write(*(Path(p) for p in sys.argv[1:]))