File size: 8,674 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""Probe P2 (design 'probe_P2_fixed_model'): does a fixed model start deleting marks when it reads augmented lines?

The existing A1 long2x recognizer (96 px, DATA/checkpoints/r5/linedet_ext/A1/long2x.pt) reads kohtd_val and synth_hand_val
(validation only) after: resize to H, apply ONE op, (resize back to H if the height changed), resize to 96 (linedet image path).
Conditions (one per op slot, policy and height; slot 6 'keep' = the control):
  plain96                 the linedet image path alone
  control_H{H}            resize to H and back to 96, no op
  {typ|safe}_H{H}_s{k}    policy op k (0-5) at H; safe_H32_s3 is the identity (no thickening at 32 px) and is not run
  typnat_H{H}_s{k}        TrOCR-native order: typical op k on the native crop, then resize to H, then to 96; for k = 4 the
                          downscale bottleneck is one third of the H px line, (W_H // 3, H // 3), as TrOCR's fixed one third
                          of its model input, sampled NEAREST from the native crop, then BICUBIC up to H
Magnitudes: z1, z2 from default_rng([20261126, 4545, condition index, row index]) (same row draws in every condition index
order of the list below). Writes <out>/<condition>/<set>.tsv (id, ref, hyp; NFC), <out>/<condition>/<set>.done and
<out>/DONE; finished conditions are skipped on a rerun. rq2_metrics.py scores them against their controls.
"""
import argparse
import datetime
import json
import os
import sys

import numpy as np

CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
CKPT = DATA + "/checkpoints/r5/linedet_ext/A1/long2x.pt"
SETS = {"kohtd_val": DATA + "/data/processed/r5/manifests/kohtd_val.tsv",
        "synth_hand_val": DATA + "/data/processed/r5/frozen_eval_v1/synth_hand_val.tsv"}


def conditions():
    c = ["plain96", "control_H32", "control_H64"]
    for H in (32, 64):
        for pol in ("typ", "safe"):
            for k in range(6):
                if pol == "safe" and H == 32 and k == 3:
                    continue
                c.append("%s_H%d_s%d" % (pol, H, k))
    for H in (32, 64):
        for k in range(6):
            c.append("typnat_H%d_s%d" % (H, k))
    return c


class P2DS:
    def __init__(self, rows, cond, cond_idx, spec96):
        from rq2.aug import Policy
        self.rows, self.cond, self.ci, self.spec = rows, cond, cond_idx, spec96
        self.pol = None
        if cond.startswith(("typ_", "safe_", "typnat_")):
            name, h, s = cond.split("_")
            self.H = int(h[1:])
            self.slot = int(s[1:])
            self.order = "native" if name == "typnat" else "ours"
            self.pol = "typical" if name in ("typ", "typnat") else "safe"
        elif cond.startswith("control_H"):
            self.H = int(cond.split("_H")[1])
        else:
            self.H = None
        self.Policy = Policy

    def __len__(self):
        return len(self.rows)

    def __getitem__(self, i):
        import torch
        from PIL import Image
        from linedet import data as D
        from rq2.aug import resize_to_height
        r = self.rows[i]
        im = Image.open(r["image"]).convert("RGB")
        op = "none"
        if self.H is not None:
            if self.pol is None:
                im = resize_to_height(im, self.H)
            else:
                rng = np.random.default_rng([20261126, 4545, self.ci, i])
                z1, z2 = float(rng.random()), float(rng.random())
                if self.order == "ours":
                    im = resize_to_height(im, self.H)
                    im, op, _ = self.Policy(self.pol, self.H).apply(im, self.slot, z1, z2)
                    im = resize_to_height(im, self.H)
                elif self.slot == 4:
                    # TrOCR's downscale resizes the SOURCE crop to a fixed one third of the model input (128 x 128 for 384 x 384),
                    # then up to the input: here NEAREST from the native crop to (W_H // 3, H // 3), BICUBIC up to (W_H, H)
                    W_H = max(int(im.size[0] * self.H / im.size[1]), 1)
                    im = im.resize((max(1, W_H // 3), max(1, self.H // 3)), Image.NEAREST).resize((W_H, self.H), Image.BICUBIC)
                    op = "down_up_third_native"
                else:
                    im, op, _ = self.Policy(self.pol, im.size[1]).apply(im, self.slot, z1, z2)
                    im = resize_to_height(im, self.H)
        t = D.pil_tensor(im, self.spec, None)           # resize to 96 (Lanczos), pad, invert: the linedet path
        return {"image": t, "target": torch.zeros(0, dtype=torch.int32), "text": r["text"], "gid": i, "op": op}


def collate(batch):
    from linedet import data as D
    out = D.collate(batch)
    out["op"] = [b["op"] for b in batch]
    return out


def main():
    if any(x.startswith("--test_pass") for x in sys.argv[1:]):
        print("REFUSED: validation only")
        sys.exit(3)
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=DATA + "/outputs/rq2/probe_p2")
    ap.add_argument("--ckpt", default=CKPT)
    ap.add_argument("--limit", type=int, default=0, help="smoke only: first N rows per set")
    ap.add_argument("--only_conditions", default="")
    ap.add_argument("--bs", type=int, default=32)
    ap.add_argument("--workers", type=int, default=3)
    ap.add_argument("--device", default="cuda")
    a = ap.parse_args()
    import torch
    from torch.utils.data import DataLoader
    from rq2 import geom
    geom.check_pinned(include_data=False)
    from linedet import data as D
    from linedet.common import read_manifest, to_report_text, write_tsv
    from linedet.models import build_arm_for_inference
    from linedet.predict import greedy_strings, _EvBS
    from kraken.lib.codec import PytorchCodec
    spec = D.SPECS["A1"]
    assert spec.height == 96 and spec.subsampling == 8, "P2 uses the unchanged 96 px geometry"
    dev = torch.device(a.device)
    ck = torch.load(a.ckpt, map_location="cpu", weights_only=False)
    codec = PytorchCodec(ck["codec_c2l"])
    arm = build_arm_for_inference("A1", codec)
    arm.load_inference_state(ck["state"])
    arm.to(dev)
    arm.eval()
    os.makedirs(a.out, exist_ok=True)
    conds = conditions()
    if a.only_conditions:
        keep = set(a.only_conditions.split(","))
        conds = [c for c in conds if c in keep]
    meta = {"written_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "checkpoint": a.ckpt,
            "checkpoint_sha256": geom.sha256_file(a.ckpt), "samples_seen": ck.get("samples_seen"), "conditions": conds,
            "limit": a.limit, "sets": {}, "decoding": "greedy CTC", "scope": "probe P2: a fixed 96 px CTC recognizer (A1 long2x)"}
    for set_name, man in SETS.items():
        rows = [r for r in read_manifest(man) if r.get("unit") != "page"]
        if any(r.get("split") not in ("val", "validation") for r in rows):
            raise SystemExit("REFUSED: %s has non-validation rows" % set_name)
        if a.limit:
            rows = rows[:a.limit]
        meta["sets"][set_name] = len(rows)
        order = D.eval_order([(r["image"], r["text"], "") for r in rows])
        for ci, c in enumerate(conditions()):
            if c not in conds:
                continue
            od = os.path.join(a.out, c)
            done = os.path.join(od, set_name + ".done")
            if os.path.exists(done):
                continue
            ds = P2DS(rows, c, ci, spec)
            loader = DataLoader(ds, batch_sampler=_EvBS(order, a.bs), num_workers=a.workers, collate_fn=collate,
                                prefetch_factor=4 if a.workers else None)
            hyps = [None] * len(rows)
            ops = {}
            for batch in loader:
                lp, ol = arm.infer(batch["image"], batch["seq_lens"], dev)
                res = greedy_strings(lp.cpu().numpy(), ol.cpu().numpy(), codec.l2c_single)
                for j, gid in enumerate(batch["gid"]):
                    hyps[gid] = to_report_text(res[j][0])
                for o in batch["op"]:
                    ops[o] = ops.get(o, 0) + 1
            write_tsv(os.path.join(od, set_name + ".tsv"), ["id", "ref", "hyp"], [(r["id"], r["text"], h) for r, h in zip(rows, hyps)])
            with open(done, "w") as f:
                json.dump({"rows": len(rows), "ops": ops}, f)
            print(c, set_name, "done", ops, flush=True)
    json.dump(meta, open(os.path.join(a.out, "meta.json"), "w"), indent=1)
    if set(conds) == set(conditions()):
        with open(os.path.join(a.out, "DONE"), "w") as f:
            f.write(datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + "\n")


if __name__ == "__main__":
    main()