File size: 17,479 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
"""Scores every prediction file under --preds that has no up-to-date score file.

usage: python -I score.py --preds DATA/outputs/r5/preds --registry DATA/data/processed/r5/evalsets.json --out DATA/outputs/r5/scores
         [--workers 16] [--B 10000] [--ktrain DATA/data/processed/r5/p2/ktrain_manifest.json]
         [--test-pass --gate-file DATA/outputs/r5/RULE/test_pass_started.txt]

Layout read:  <preds>/<arm>/<checkpoint>/<evalset>.tsv  (columns id, ref, hyp, optional conf, conf_min, hit_cap, n_tokens),
              optional <evalset>.raw.jsonl (VLM raw outputs) and <checkpoint>/meta.json.
Layout written: <out>/<arm>/<checkpoint>/<evalset>.json (one score file), <out>/summary.tsv (validation figures),
              <out>/summary_columns.json, <out>/run_log.json, <out>/_label_repairs/<evalset>.tsv (references changed by the
              look-alike repair, rule 0.6(c)).
Locked sets (registry 'locked' true or split 'test'): refused, before any manifest or prediction file of the set is opened, unless
BOTH --test-pass is given AND the gate file exists. The gate file is created on the cluster when the single scoring
pass starts (records/R5/RULE/test_pass_started.txt lives on the laptop; copy it to the gate path).
Incremental: a score file is kept when its stored incremental key (sha256 over the prediction file, raw file, manifest, side file,
K_train, look-alike table, scorer code, B, seed and confidence definition) is unchanged. A prediction file modified in the last
--settle seconds is skipped (still being written).
"""
import os

for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ.setdefault(_v, "1")
import argparse  # noqa: E402
import concurrent.futures  # noqa: E402
import hashlib  # noqa: E402
import json  # noqa: E402
import multiprocessing  # noqa: E402
import sys  # noqa: E402
import time  # noqa: E402
import traceback  # noqa: E402

HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.normpath(os.path.join(HERE, "..", "..", "src"))
sys.path.insert(0, SRC)

DATA = "/path/to/TURKIC_OCR_DATA"
R5 = DATA + "/data/processed/r5"
DEFAULT_GATE = DATA + "/outputs/r5/RULE/test_pass_started.txt"
SKIP_WORDS = ("smoke", "tmp", "scratch")
_KT = {}


def utc():
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for blk in iter(lambda: f.read(1 << 20), b""):
            h.update(blk)
    return h.hexdigest()


def companion_files(manifest):
    base = os.path.splitext(manifest)[0]
    out = {}
    for suffix, nm in (("_p2", "registry_P2"), ("_p2b", "registry_P2b")):
        p = base + suffix + ".tsv"
        if os.path.exists(p):
            out[nm] = p
    return out


def incremental_key(job, extra):
    parts = [job["pred_sha"], job.get("raw_sha") or "-", job["manifest_sha"], job.get("side_sha") or "-", extra["ktrain_sha"],
             extra["lookalike_sha"], extra["code_sha"], str(extra["B"]), str(extra["seed"]), job.get("conf_def") or "-",
             ",".join(sorted("%s=%s" % kv for kv in job.get("companion_sha", {}).items())), "locked" if job["locked"] else "open"]
    return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()


def run_job(job, extra):
    """Worker: scores one prediction file and writes its JSON atomically. Returns a short status dict."""
    t0 = time.time()
    try:
        from r5eval import ioutil, ktrain as ktmod, scoreset, stats
        mrows = ioutil.read_manifest(job["manifest"])
        preds, header, ragged, dup = ioutil.read_preds(job["pred"])
        raw = ioutil.read_raw_jsonl(job["raw"]) if job.get("raw") else None
        side = ioutil.read_meta_tsv(job["side"]) if job.get("side") else None
        meta = json.load(open(job["meta"], encoding="utf-8")) if job.get("meta") else {}
        kt = None
        # K_train (millions of keys) is loaded only for sets that have word crops of handwriting; the replication split has no unseen-word slice
        need_kt = any(r["unit"] == "word" and r["kind"] in ("hand_real", "hand_synth") for r in mrows) and "rand" not in job["stem"] \
            and "rand" not in str(job["entry"].get("name", ""))
        if need_kt and extra.get("ktrain") and os.path.exists(extra["ktrain"]):
            if "kt" not in _KT:
                _KT["kt"] = ktmod.load(extra["ktrain"], verify=False)
            kt = _KT["kt"]
        comp = {}
        for nm, p in job.get("companion", {}).items():
            comp[nm] = {r["id"] for r in ioutil.read_manifest(p)}
        res = scoreset.score_set(job["arm"], job["ckpt"], job["stem"], job["entry"], mrows, preds, header, ragged, dup, raw, side, kt,
                                 comp, meta, B=extra["B"], seed=extra["seed"])
        repairs = res.pop("_repairs", [])
        res["schema"] = "r5eval-score-1"
        res["registry_name"] = job["entry"].get("name")
        res["locked"] = job["locked"]
        res["test_pass"] = bool(job["locked"])
        res["scored_utc"] = utc()
        res["inputs"] = {"pred_path": job["pred"], "pred_sha256": job["pred_sha"], "raw_path": job.get("raw"), "raw_sha256": job.get("raw_sha"),
                         "manifest_path": job["manifest"], "manifest_sha256": job["manifest_sha"], "side_path": job.get("side"),
                         "side_sha256": job.get("side_sha"), "meta_path": job.get("meta"), "companion": job.get("companion_sha"),
                         "incremental_key": job["key"]}
        res["scorer"] = {"version": extra["version"], "code_sha256": extra["code_sha"], "frozen_sha256": extra["frozen"],
                         "lookalike_sha256": extra["lookalike_sha"], "ktrain_sha256": extra["ktrain_sha"] if kt is not None else None,
                         "B": extra["B"], "seed": extra["seed"]}
        ioutil.write_json_atomic(job["out"], res)
        if repairs:
            d = os.path.join(extra["out_root"], "_label_repairs")
            os.makedirs(d, exist_ok=True)
            with open(os.path.join(d, job["stem"] + ".tsv"), "w", encoding="utf-8", newline="") as f:
                f.write("id\tbefore\tafter\n")
                for i, a, b in repairs:
                    f.write("%s\t%s\t%s\n" % (i, a, b))
        return {"job": job["out"], "status": res.get("status"), "seconds": round(time.time() - t0, 1)}
    except Exception:  # noqa: BLE001
        return {"job": job["out"], "status": "error", "error": traceback.format_exc()[-1500:], "seconds": round(time.time() - t0, 1)}


def score_pages(a, reg, gate_open, extra, plog):
    """Page prediction files <page_preds>/<pipeline>/<checkpoint>/<evalset>.jsonl (format in r5eval/pages.py). Same gate as the crops."""
    from r5eval import ioutil, pages
    for pipe in sorted(os.listdir(a.page_preds)):
        pp = os.path.join(a.page_preds, pipe)
        if not os.path.isdir(pp) or pipe.startswith("_") or any(w in pipe for w in SKIP_WORDS):
            continue
        for ck in sorted(os.listdir(pp)):
            cp = os.path.join(pp, ck)
            if not os.path.isdir(cp) or ck.startswith("_") or any(w in ck for w in SKIP_WORDS):
                continue
            for fn in sorted(os.listdir(cp)):
                if not fn.endswith(".jsonl"):
                    continue
                stem = fn[:-6]
                entry = reg.find(stem)
                if entry is None:
                    plog["unmatched"].append(os.path.join(cp, fn))
                    continue
                if reg.is_locked(entry) and not gate_open:
                    plog["refused_locked"].append({"pipeline": pipe, "checkpoint": ck, "set": stem})
                    continue
                path = os.path.join(cp, fn)
                if time.time() - os.path.getmtime(path) < a.settle:
                    continue
                man = entry.get("manifest")
                if not man or not os.path.exists(man):
                    plog["errors"].append({"set": stem, "error": "manifest missing"})
                    continue
                key = hashlib.sha256("|".join([sha256_file(path), sha256_file(man), extra["code_sha"], str(a.B), str(a.seed)]).encode()).hexdigest()
                out = os.path.join(a.out, "pages", pipe, ck, stem + ".json")
                if not a.force and os.path.exists(out):
                    try:
                        if json.load(open(out, encoding="utf-8")).get("incremental_key") == key:
                            plog["up_to_date"] += 1
                            continue
                    except ValueError:
                        pass
                try:
                    rows = [r for r in ioutil.read_manifest(man) if r["unit"] == "page"]
                    res = pages.score_page_file(path, rows, B=a.B, seed=a.seed)
                    res.update({"schema": "r5eval-pagescore-1", "pipeline": pipe, "checkpoint": ck, "evalset": stem, "registry_name": entry.get("name"),
                                "locked": reg.is_locked(entry), "incremental_key": key, "scored_utc": utc(), "pred_path": path})
                    ioutil.write_json_atomic(out, res)
                    plog["scored"].append(out)
                    print("page file scored", out, flush=True)
                except Exception:  # noqa: BLE001
                    plog["errors"].append({"set": stem, "error": traceback.format_exc()[-1200:]})


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--page-preds", default=DATA + "/outputs/r5/page_preds", help="folder of page prediction JSONL files (may not exist yet)")
    ap.add_argument("--preds", required=True)
    ap.add_argument("--registry", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--workers", type=int, default=1)
    ap.add_argument("--B", type=int, default=10000)
    ap.add_argument("--seed", type=int, default=20261121)
    ap.add_argument("--ktrain", default=R5 + "/p2/ktrain_manifest.json")
    ap.add_argument("--test-pass", action="store_true")
    ap.add_argument("--gate-file", default=DEFAULT_GATE)
    ap.add_argument("--settle", type=float, default=20.0, help="skip prediction files modified within this many seconds")
    ap.add_argument("--only-arm", default="")
    ap.add_argument("--only-set", default="")
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--max-files", type=int, default=0)
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()

    import r5eval
    from r5eval import frozen, ioutil, lookalike, scoreset, summary

    reg = ioutil.load_registry(a.registry)
    gate_open = bool(a.test_pass) and os.path.exists(a.gate_file)
    log = {"started_utc": utc(), "registry": a.registry, "registry_sha256": sha256_file(a.registry), "test_pass_flag": bool(a.test_pass),
           "gate_file": a.gate_file, "gate_open": gate_open, "scored": [], "up_to_date": 0, "refused_locked": [], "unmatched": [],
           "in_flight": [], "errors": [], "skipped_dirs": []}
    if a.test_pass and not gate_open:
        print("REFUSED: --test-pass given but the gate file %s does not exist; locked sets stay closed" % a.gate_file)
    extra = {"B": a.B, "seed": a.seed, "ktrain": a.ktrain, "code_sha": r5eval.code_sha256(), "version": r5eval.VERSION,
             "frozen": frozen.FROZEN_SHA256, "out_root": a.out,
             "lookalike_sha": sha256_file(lookalike.table_path())}
    kt_sha = "-"
    if os.path.exists(a.ktrain):
        try:
            kt_sha = json.load(open(a.ktrain, encoding="utf-8")).get("ktrain_sha256", "-")
        except ValueError:
            kt_sha = "-"
    extra["ktrain_sha"] = kt_sha
    man_sha = {}
    jobs = []
    if os.path.isdir(a.preds):
        for arm in sorted(os.listdir(a.preds)):
            ap_ = os.path.join(a.preds, arm)
            if not os.path.isdir(ap_) or arm.startswith("_") or any(w in arm for w in SKIP_WORDS):
                if os.path.isdir(ap_):
                    log["skipped_dirs"].append(ap_)
                continue
            if a.only_arm and arm != a.only_arm:
                continue
            for ck in sorted(os.listdir(ap_)):
                cp = os.path.join(ap_, ck)
                if not os.path.isdir(cp) or ck.startswith("_") or any(w in ck for w in SKIP_WORDS):
                    if os.path.isdir(cp):
                        log["skipped_dirs"].append(cp)
                    continue
                meta_p = os.path.join(cp, "meta.json")
                for fn in sorted(os.listdir(cp)):
                    if not fn.endswith(".tsv"):
                        continue
                    stem = fn[:-4]
                    if a.only_set and stem != a.only_set:
                        continue
                    entry = reg.find(stem)
                    if entry is None:
                        log["unmatched"].append(os.path.join(cp, fn))
                        continue
                    locked = reg.is_locked(entry)
                    if locked and not gate_open:
                        log["refused_locked"].append({"arm": arm, "checkpoint": ck, "set": stem})
                        continue
                    pred = os.path.join(cp, fn)
                    if time.time() - os.path.getmtime(pred) < a.settle:
                        log["in_flight"].append(pred)
                        continue
                    man = entry.get("manifest")
                    if not man or not os.path.exists(man):
                        log["errors"].append({"set": stem, "error": "manifest missing: %s" % man})
                        continue
                    if man not in man_sha:
                        man_sha[man] = sha256_file(man)
                    raw = os.path.join(cp, stem + ".raw.jsonl")
                    raw = raw if os.path.exists(raw) else None
                    side = os.path.splitext(man)[0] + ".meta.tsv"
                    side = side if os.path.exists(side) else None
                    comp = companion_files(man) if locked else {}
                    meta = {}
                    if os.path.exists(meta_p):
                        try:
                            meta = json.load(open(meta_p, encoding="utf-8"))
                        except ValueError:
                            meta = {}
                    _, conf_def = scoreset.detect_conf_kind(meta)
                    job = {"arm": arm, "ckpt": ck, "stem": stem, "entry": entry, "pred": pred, "pred_sha": sha256_file(pred),
                           "raw": raw, "raw_sha": sha256_file(raw) if raw else None, "manifest": man, "manifest_sha": man_sha[man],
                           "side": side, "side_sha": sha256_file(side) if side else None, "meta": meta_p if os.path.exists(meta_p) else None,
                           "companion": comp, "companion_sha": {k: sha256_file(v) for k, v in comp.items()}, "locked": locked,
                           "conf_def": hashlib.sha256(conf_def.encode("utf-8")).hexdigest() if conf_def else None,
                           "out": os.path.join(a.out, arm, ck, stem + ".json")}
                    job["key"] = incremental_key(job, extra)
                    if not a.force and os.path.exists(job["out"]):
                        try:
                            old = json.load(open(job["out"], encoding="utf-8"))
                            if old.get("inputs", {}).get("incremental_key") == job["key"]:
                                log["up_to_date"] += 1
                                continue
                        except ValueError:
                            pass
                    jobs.append(job)
    if a.max_files:
        jobs = jobs[:a.max_files]
    print("%d files to score, %d up to date, %d locked sets refused, %d unmatched, %d in flight" % (
        len(jobs), log["up_to_date"], len(log["refused_locked"]), len(log["unmatched"]), len(log["in_flight"])), flush=True)
    if a.dry_run:
        for j in jobs:
            print("would score", j["out"])
    elif jobs:
        os.makedirs(a.out, exist_ok=True)
        if a.workers > 1:
            ctx = multiprocessing.get_context("spawn")
            with concurrent.futures.ProcessPoolExecutor(max_workers=a.workers, mp_context=ctx) as ex:
                futs = [ex.submit(run_job, j, extra) for j in jobs]
                for fu in concurrent.futures.as_completed(futs):
                    r = fu.result()
                    (log["errors"] if r["status"] == "error" else log["scored"]).append(r)
                    print(r["status"], r["job"], r["seconds"], flush=True)
        else:
            for j in jobs:
                r = run_job(j, extra)
                (log["errors"] if r["status"] == "error" else log["scored"]).append(r)
                print(r["status"], r["job"], r["seconds"], flush=True)
    log["pages"] = {"scored": [], "up_to_date": 0, "refused_locked": [], "unmatched": [], "errors": []}
    if not a.dry_run and a.page_preds and os.path.isdir(a.page_preds):
        score_pages(a, reg, gate_open, extra, log["pages"])
    if not a.dry_run:
        os.makedirs(a.out, exist_ok=True)
        rows = summary.write_summary(a.out, a.preds, os.path.join(a.out, "summary.tsv"))
        log["summary_rows"] = len(rows)
        log["finished_utc"] = utc()
        with open(os.path.join(a.out, "run_log.json"), "w", encoding="utf-8") as f:
            json.dump(log, f, indent=1)
    print("done: scored %d, errors %d" % (len(log["scored"]), len(log["errors"])))
    return 1 if log["errors"] else 0


if __name__ == "__main__":
    sys.exit(main())