File size: 7,492 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
"""R5 REF: builds everything the four reference runs read.  Reads ONLY kohtd_train.tsv and kohtd_val.tsv (never a test manifest, never a test image).

Outputs
  manifests (DATA/data/processed/r5/manifests/):  kohtd_rand_train.tsv, kohtd_rand_val.tsv, kohtd_rand_test.tsv
      replication split (amendment 3.3 D5 ii, clarification H1): crop-level random 70/15/15 split of the pool "all crops of the KOHTD train and
      validation forms of our split" (kohtd_train + kohtd_val), seed 20261121. Algorithm: pool sorted by id, numpy default_rng(seed).permutation(N),
      first int(0.70 N) -> train, next int(0.15 N) -> val, rest -> test.
  run folder (DATA/data/processed/r5/ref/):
      pool_ids.txt                one id per line, row order of flor_pool_u8.npy (pool sorted by id)
      flor_pool_u8.npy            uint8 [N, 1024, 128]: HTR-Flor preprocessing (data/preproc.py preprocess, input_size (1024, 128, 1)) of every pool crop
      charset_i.json, charset_ii.json   characters of the training labels of runs (i) and (ii) (case kept, sorted by code point)
      ppocr_{i,ii}_{train,val}.txt      PaddleOCR label lists (absolute image path TAB text)
      ppocr_dict_{i,ii}.txt            PaddleOCR character dictionaries (one character per line; the space is added by use_space_char)
      build_report.json           counts and sha256 of every output
Usage: python ref_build_data.py <htrflor_src_dir> <manifest_dir> <out_dir> [--workers 16] [--no_images]
Run on a compute node (it runs the pinned HTR-Flor preprocessing code).
"""
import argparse
import csv
import hashlib
import json
import multiprocessing
import os
import sys
import time
import unicodedata

import numpy as np

SEED = 20261121
INPUT_SIZE = (1024, 128, 1)
COLS = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"]


def sha256(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_manifest(path):
    with open(path, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))


def write_manifest(path, rows, split):
    with open(path, "w", encoding="utf-8", newline="") as f:
        f.write("\t".join(COLS) + "\n")
        for r in rows:
            r = dict(r)
            r["split"] = split
            f.write("\t".join(r[c] for c in COLS) + "\n")


_PP = None


def _init(src):
    global _PP
    sys.path.insert(0, src)
    from data import preproc as pp  # pinned HTR-Flor code
    _PP = pp


def _prep(path):
    try:
        return _PP.preprocess(path, input_size=INPUT_SIZE), None
    except Exception as e:  # unreadable image: zero array, counted in the report
        return np.zeros(INPUT_SIZE[:2], dtype=np.uint8), "%s: %s" % (path, e)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("src")
    ap.add_argument("manifests")
    ap.add_argument("out")
    ap.add_argument("--workers", type=int, default=16)
    ap.add_argument("--no_images", action="store_true")
    ap.add_argument("--limit", type=int, default=0, help="smoke test: use only the first LIMIT pool rows (the rand manifests are still the full ones only if LIMIT is 0)")
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    tr = read_manifest(os.path.join(a.manifests, "kohtd_train.tsv"))
    va = read_manifest(os.path.join(a.manifests, "kohtd_val.tsv"))
    assert all(r["split"] == "train" for r in tr) and all(r["split"] == "val" for r in va)
    pool = sorted(tr + va, key=lambda r: r["id"])
    ids = [r["id"] for r in pool]
    assert len(set(ids)) == len(ids), "duplicate ids in pool"
    n = len(pool)
    rep = {"seed": SEED, "pool_rows": n, "train_rows": len(tr), "val_rows": len(va), "forms_in_pool": len({r["group"] for r in pool})}

    # ---- replication split (H1)
    perm = np.random.default_rng(SEED).permutation(n)
    n_tr, n_va = int(0.70 * n), int(0.15 * n)
    parts = {"train": perm[:n_tr], "val": perm[n_tr:n_tr + n_va], "test": perm[n_tr + n_va:]}
    mdir = a.manifests if not a.limit else os.path.join(a.out, "smoke_manifests")
    os.makedirs(mdir, exist_ok=True)
    rand_rows = {}
    for k, idx in parts.items():
        rows = [pool[i] for i in sorted(idx.tolist())]
        rand_rows[k] = rows
        p = os.path.join(mdir, "kohtd_rand_%s.tsv" % k)
        write_manifest(p, rows, k)
        rep["rand_" + k] = {"rows": len(rows), "forms": len({r["group"] for r in rows}), "path": p, "sha256": sha256(p)}
    # forms shared by the three parts (a crop-level split puts every form into all of them)
    rep["rand_forms_in_all_three_parts"] = len(set.intersection(*[{r["group"] for r in v} for v in rand_rows.values()]))

    # ---- run folders: character sets, PaddleOCR lists
    runs = {"i": (tr, va), "ii": (rand_rows["train"], rand_rows["val"])}
    for tag, (trn, val) in runs.items():
        chars = sorted({c for r in trn for c in unicodedata.normalize("NFC", r["text"])})
        assert "¶" not in chars and "¤" not in chars, "reserved HTR-Flor token in labels"
        assert all(c not in "\n\r\t" for c in chars)
        p = os.path.join(a.out, "charset_%s.json" % tag)
        json.dump({"run": tag, "n_chars": len(chars), "chars": "".join(chars), "source": "all characters of the training labels (NFC, case kept), sorted by code point"}, open(p, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
        with open(os.path.join(a.out, "ppocr_dict_%s.txt" % tag), "w", encoding="utf-8", newline="") as f:
            for c in chars:
                if c != " ":
                    f.write(c + "\n")
        for nm, rows in (("train", trn), ("val", val)):
            with open(os.path.join(a.out, "ppocr_%s_%s.txt" % (tag, nm)), "w", encoding="utf-8", newline="") as f:
                for r in rows:
                    f.write(r["image"] + "\t" + unicodedata.normalize("NFC", r["text"]) + "\n")
        rep["charset_" + tag] = len(chars)
    with open(os.path.join(a.out, "pool_ids.txt"), "w", encoding="utf-8") as f:
        f.write("\n".join(ids) + "\n")

    # ---- preprocessed pool array (pinned HTR-Flor preprocessing)
    fails = []
    if not a.no_images:
        m = a.limit or n
        arr_path = os.path.join(a.out, "flor_pool_u8.npy")
        arr = np.lib.format.open_memmap(arr_path, mode="w+", dtype=np.uint8, shape=(m,) + INPUT_SIZE[:2])
        t0 = time.time()
        with multiprocessing.Pool(a.workers, initializer=_init, initargs=(a.src,)) as pool_mp:
            for i, (img, err) in enumerate(pool_mp.imap(_prep, [r["image"] for r in pool[:m]], chunksize=64)):
                arr[i] = img
                if err:
                    fails.append(err)
                if i % 20000 == 0:
                    print("preprocessed", i, "of", m, "%.0fs" % (time.time() - t0), flush=True)
        arr.flush()
        del arr
        rep["array"] = {"path": arr_path, "shape": [m] + list(INPUT_SIZE[:2]), "seconds": round(time.time() - t0, 1), "unreadable_images": len(fails), "unreadable_examples": fails[:5]}
    for fn in sorted(os.listdir(a.out)):
        p = os.path.join(a.out, fn)
        if os.path.isfile(p) and fn != "build_report.json":
            rep.setdefault("sha256", {})[fn] = sha256(p)
    json.dump(rep, open(os.path.join(a.out, "build_report.json"), "w"), indent=1)
    print(json.dumps({k: v for k, v in rep.items() if k != "sha256"}, indent=1)[:3000])


if __name__ == "__main__":
    main()