File size: 3,568 Bytes
43e0718
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""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:]))