File size: 9,362 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
"""Builds the fixed learning-curve set curve_v1 (request of 21 Nov) and registers it in evalsets.json as a validation set.

curve_v1.tsv (shared manifest format) holds, drawn with seed 20261121 from VALIDATION manifests only:
  - all 500 rows of V1lm (kohtd_lmtune.tsv)
  - 50 rows per language-script from synth_hand_val
  - 20 rows per language-script from synth_typed_val
  - 20 rows per language-script from print_real_val   (a language-script that print_real_val lacks is skipped and listed)
  - 100 rows from synth_clutter_val
Each (part, language-script) draw is a function of the seed, the part name and the language only: a part that appears later
does not change a part drawn earlier. The builder can be re-run when a source manifest appears; it records every source file's
sha256 and which parts are missing in curve_v1_info.json ('complete' is true only when all five parts are present).
It refuses any source whose rows are not split == val and any source name that contains 'test' or 'train'.
Row ids, texts, groups and units are copied unchanged (KOHTD rows have unit word, the others line).

usage: python -I build_curve_set.py [--manifests DIR] [--registry evalsets.json] [--no-register] [--register-only]
The evaluation registry is rewritten from scratch by DATA's r5_registry.py: after that script runs, run this one with --register-only.
"""
import argparse
import csv
import hashlib
import json
import os
import sys
import time

import numpy as np

csv.field_size_limit(10 ** 9)
DATA = "/path/to/TURKIC_OCR_DATA"
R5 = DATA + "/data/processed/r5"
SEED = 20261121
HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"]
LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"]
PARTS = [  # name, manifest, per language quota (None: all rows; 'total:N' one draw of N)
    ("V1lm", "kohtd_lmtune.tsv", None),
    ("synth_hand_val", "synth_hand_val.tsv", 50),
    ("synth_typed_val", "synth_typed_val.tsv", 20),
    ("print_real_val", "print_real_val.tsv", 20),
    ("synth_clutter_val", "synth_clutter_val.tsv", "total:100"),
]


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


def read(path):
    with open(path, encoding="utf-8", newline="") as f:
        rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
        missing = [c for c in HDR if c not in (rd.fieldnames or [])]
        if missing:
            raise SystemExit("%s: the shared manifest columns %s are missing (header %s)" % (path, missing, rd.fieldnames))
        # extra columns (a slightly different producer) are ignored: the ten shared columns are kept
        return [{c: (r.get(c) or "") for c in HDR} for r in rd]


def draw(rows, k, part, lang):
    rows = sorted(rows, key=lambda r: r["id"])
    if k is None or k >= len(rows):
        return rows
    seed = int.from_bytes(hashlib.sha256(("%d|%s|%s" % (SEED, part, lang)).encode()).digest()[:8], "little")
    idx = sorted(np.random.default_rng(seed).choice(len(rows), size=k, replace=False).tolist())
    return [rows[i] for i in idx]


def build(man_dir):
    out_rows, info_parts, missing = [], [], []
    for part, fn, quota in PARTS:
        if "test" in fn or "train" in fn:
            raise SystemExit("refusing source %s" % fn)
        p = os.path.join(man_dir, fn)
        if not os.path.exists(p):
            missing.append(part)
            info_parts.append({"part": part, "manifest": p, "status": "missing at build time"})
            continue
        rows = read(p)
        bad = [r["id"] for r in rows if r["split"] != "val"]
        if bad:
            raise SystemExit("%s has %d rows that are not split val (first %s): refusing" % (fn, len(bad), bad[0]))
        chosen, short = [], {}
        if quota is None:
            chosen = draw(rows, None, part, "all")
        elif isinstance(quota, str):
            chosen = draw(rows, int(quota.split(":")[1]), part, "all")
            if len(chosen) < int(quota.split(":")[1]):
                short["all"] = len(chosen)
        else:
            by = {}
            for r in rows:
                by.setdefault(r["lang"], []).append(r)
            for lang in LANGS:
                if lang not in by:
                    short[lang] = 0
                    continue
                c = draw(by[lang], quota, part, lang)
                if len(c) < quota:
                    short[lang] = len(c)
                chosen += c
        langs = {}
        for r in chosen:
            langs[r["lang"]] = langs.get(r["lang"], 0) + 1
        out_rows += chosen
        info_parts.append({"part": part, "manifest": p, "manifest_sha256": sha(p), "source_rows": len(rows), "rows_drawn": len(chosen),
                           "per_language": langs, "short_languages": short, "status": "included"})
    return out_rows, info_parts, missing


def register(registry_path, man_path, rows, info):
    reg = json.load(open(registry_path, encoding="utf-8"))
    sets = [s for s in reg["sets"] if s.get("name") != "curve_v1"]
    langs = {}
    for r in rows:
        langs[r["lang"]] = langs.get(r["lang"], 0) + 1
    sets.append({
        "name": "curve_v1", "manifest": man_path, "split": "val", "locked": False, "status": "ready",
        "purpose": "Fixed learning-curve set: all 500 V1lm rows, 50 synth_hand_val rows, 20 synth_typed_val rows and 20 print_real_val rows per "
                   "language-script, 100 synth_clutter_val rows (seed 20261121). Scored at 25%, 50%, 75% and 100% of P_short to draw learning curves.",
        "n_rows": len(rows), "n_groups": len({r["group"] for r in rows}), "manifest_sha256": sha(man_path), "langs": langs,
        "unit": "word and line (per row)", "group_unit": "KOHTD form for the handwriting words, source page for synthetic lines, document for real print",
        "split_rule": "rows copied from validation manifests only", "complete": info["complete"], "missing_parts": info["missing_parts"],
        "owner": "EVALCODE", "built_utc": info["built_utc"],
        "note": "a part that was missing at build time is added by re-running build_curve_set.py; the manifest hash then changes"})
    reg["sets"] = sets
    tmp = registry_path + ".tmp%d" % os.getpid()
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(reg, f, ensure_ascii=False, indent=1)
    os.replace(tmp, registry_path)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--manifests", default=R5 + "/manifests")
    ap.add_argument("--registry", default=R5 + "/evalsets.json")
    ap.add_argument("--no-register", action="store_true")
    ap.add_argument("--register-only", action="store_true")
    ap.add_argument("--final", action="store_true", help="freeze: write curve_v1_frozen.json; later builds are refused")
    a = ap.parse_args()
    man_path = os.path.join(a.manifests, "curve_v1.tsv")
    info_path = os.path.join(os.path.dirname(a.manifests.rstrip("/")), "curve_v1_info.json")
    frozen_path = os.path.join(os.path.dirname(a.manifests.rstrip("/")), "curve_v1_frozen.json")
    if os.path.exists(frozen_path) and not a.register_only:
        sys.exit("curve_v1 is frozen (%s): it is never rebuilt after the first run starts, so every learning curve stays comparable" % frozen_path)
    if a.register_only:
        rows = read(man_path)
        info = json.load(open(info_path, encoding="utf-8"))
        register(a.registry, man_path, rows, info)
        print("registered curve_v1 (%d rows)" % len(rows))
        return
    rows, parts, missing = build(a.manifests)
    ids = [r["id"] for r in rows]
    if len(ids) != len(set(ids)):
        raise SystemExit("duplicate ids in the curve set")
    tmp = man_path + ".tmp%d" % os.getpid()
    with open(tmp, "w", encoding="utf-8", newline="") as f:
        f.write("\t".join(HDR) + "\n")
        for r in rows:
            f.write("\t".join(r[c] for c in HDR) + "\n")
    os.replace(tmp, man_path)
    info = {"name": "curve_v1", "built_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "seed": SEED, "rows": len(rows),
            "manifest": man_path, "manifest_sha256": sha(man_path), "parts": parts, "missing_parts": missing, "complete": not missing}
    with open(info_path, "w", encoding="utf-8") as f:
        json.dump(info, f, ensure_ascii=False, indent=1)
    print("curve_v1: %d rows; parts missing: %s; complete: %s" % (len(rows), missing, not missing))
    for p in parts:
        print(" ", p["part"], p.get("rows_drawn"), p.get("short_languages") or "", p["status"])
    if not a.no_register:
        register(a.registry, man_path, rows, info)
        print("registered in", a.registry)
    if a.final:
        fz = {"frozen_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "manifest": man_path, "manifest_sha256": info["manifest_sha256"],
              "rows": len(rows), "rows_by_part": {p["part"]: p.get("rows_drawn", 0) for p in parts}, "missing_parts_left_out_for_good": missing,
              "short_languages": {p["part"]: p.get("short_languages") for p in parts if p.get("short_languages")}}
        with open(frozen_path, "w", encoding="utf-8") as f:
            json.dump(fz, f, ensure_ascii=False, indent=1)
        print("FROZEN:", json.dumps(fz, ensure_ascii=False))


if __name__ == "__main__":
    main()