File size: 13,958 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
"""R5 REF, run (iii) of the reference arms (clarification H5): the 150,016 mix_v1 training samples that R1 and R2 are trained on.

The sampler is a verbatim copy of the numpy part of LINEDET's CODE/src/linedet/data.py (sha256 of that file when copied:
1c585b404c6047cc0908e3d0da6815b8d417459624bcfcd3e39a7152fa1d143f): _leaf_list, load_mix, MixStream. Only load_components differs: it keeps NFC text
(the reference arms are not kraken models, which use NFD) and reads no images. Same seed as every arm (20261121), same batch size 32 and pool size
2048 as LINEDET's batches, so the multiset of drawn samples is the one the line arms see at the start of their stream (their P_short stream).

Eligibility (rejection sampling, order of the stream kept; the first 150,016 eligible draws are used):
  R1 (HTR-Flor): non-empty (the pinned CTC loss, keras ctc_batch_cost, raises an error on an empty target: smoke test of 21 Nov) and the encoded label
      (repeated-letter separators included) must fit the 128 output frames: encoded length <= 128.
  R2 (PaddleOCR PP-OCRv3 recogniser): the recipe's label rules: non-empty and fewer than 24 characters (max_text_length 25; the SAR label needs length < 24).
The drawn order is then shuffled once with numpy RandomState(20261121) because HTR-Flor and PaddleOCR train on randomly ordered batches (LINEDET's batches are
sorted by label length inside a pool).
Writes into <out>: mix_iii_R1.tsv, mix_iii_R2.tsv (image, text, kind, component), ppocr_iii_train.txt, ppocr_iii_val.txt (500 crops of V1lm, only to satisfy
PaddleOCR's evaluation dataset; not used), ppocr_dict_iii.txt, charset_iii.json, mix_iii_stats.json.
Usage: python ref_make_mix_lists.py <mix_v1.yaml> <out_dir> [--n 150016] [--seed 20261121]
Reads only 'train' rows of the manifests named in the mix. Text only (no images are opened).
"""
import argparse
import hashlib
import json
import os
import re
import sys
import unicodedata
from itertools import groupby

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import ref_common as rc  # noqa: E402

_WS = re.compile(r"\s+")

# ---------------------------------------------------------------------------------- verbatim copy of linedet/data.py (sampler part)
_COMP_KEYS = ("components", "sources", "mix", "parts", "entries", "streams", "groups", "shares")
_MEMBER_KEYS = ("members", "items", "sources", "manifests", "components", "children")
_MAN_KEYS = ("manifest", "path", "file", "tsv")
_SHARE_KEYS = ("share", "weight", "fraction", "probability", "p", "proportion")


def _leaf_list(node, parent_share, name_prefix, out):
    """Flatten a (possibly nested) mix description into leaf components (manifest, share, filter)."""
    if isinstance(node, str):
        out.append({"name": name_prefix or node, "manifest": node, "share": parent_share, "filter": None})
        return
    man = next((node[k] for k in _MAN_KEYS if k in node), None)
    share = next((node[k] for k in _SHARE_KEYS if k in node), None)
    share = parent_share if share is None else (parent_share * float(share) if parent_share != 1.0 or name_prefix else float(share))
    name = node.get("name", name_prefix or (os.path.basename(man) if isinstance(man, str) else "component"))
    flt = node.get("filter") or node.get("where")
    members = next((node[k] for k in _MEMBER_KEYS if k in node and isinstance(node[k], list)), None)
    if members is not None:
        have = [isinstance(m, dict) and any(k in m for k in _SHARE_KEYS) for m in members]
        if not any(have):
            for m in members:
                _leaf_list(m, share / len(members), name, out)
        else:
            tot = sum(float(next(m[k] for k in _SHARE_KEYS if k in m)) for m, h in zip(members, have) if h)
            for m, h in zip(members, have):
                sh = float(next(m[k] for k in _SHARE_KEYS if k in m)) / tot * share if h else 0.0
                _leaf_list(dict(m, **{k: 1.0 for k in _SHARE_KEYS if k in m}), sh, name, out)
        return
    if isinstance(man, list):
        for m in man:
            _leaf_list(m, share / len(man), name, out)
        return
    if man is None:
        raise ValueError("component without a manifest: %s" % node)
    out.append({"name": name, "manifest": man, "share": share, "filter": flt})


def load_mix(path):
    import yaml
    d = yaml.safe_load(open(path, encoding="utf-8"))
    comps = None
    if isinstance(d, list):
        comps = d
    else:
        for k in _COMP_KEYS:
            if k in d:
                comps = d[k]
                break
    if comps is None:
        raise ValueError("cannot find the component list in %s; keys: %s" % (path, list(d.keys())))
    if isinstance(comps, dict):
        comps = [dict(v, name=k) if isinstance(v, dict) else {"name": k, "share": v} for k, v in comps.items()]
    out = []
    for c in comps:
        _leaf_list(c, 1.0, "", out)
    tot = sum(c["share"] for c in out)
    if tot <= 0:
        raise ValueError("shares sum to zero in %s" % path)
    for c in out:
        c["share"] = c["share"] / tot
    return out


class MixStream:
    """Deterministic endless stream of batches. Sample s belongs to pool s // pool_size. Pool p draws its component
    counts from a multinomial over the shares; inside a component the items are read in seeded epoch permutations
    (no repeats inside an epoch). Pools are sorted by label length, cut into batches, batches shuffled.
    Everything is a function of (seed, pool index), so resuming at a sample count reproduces the same batches."""

    def __init__(self, comps, batch_size, seed, pool_size=2048):
        self.comps = comps
        self.bs = batch_size
        self.seed = seed
        self.pool_size = max(pool_size // batch_size, 1) * batch_size
        self.shares = np.array([c["share"] for c in comps], dtype=np.float64)
        self.shares = self.shares / self.shares.sum()
        self.offsets = np.cumsum([0] + [len(c["items"]) for c in comps])
        self.lens = np.concatenate([[len(it[1]) for it in c["items"]] for c in comps]).astype(np.int32)
        self._perm_cache = {}

    def _counts(self, p):
        rng = np.random.default_rng([self.seed, 7, p])
        return rng.multinomial(self.pool_size, self.shares)

    def _perm(self, i, e):
        key = (i, e)
        if key not in self._perm_cache:
            if len(self._perm_cache) > 4 * len(self.comps):
                self._perm_cache.clear()
            n = len(self.comps[i]["items"])
            self._perm_cache[key] = np.random.default_rng([self.seed, 1000 + i, e]).permutation(n)
        return self._perm_cache[key]

    def cursors_at(self, p):
        cur = np.zeros(len(self.comps), dtype=np.int64)
        for q in range(p):
            cur += self._counts(q)
        return cur

    def batches(self, start_sample=0):
        p = start_sample // self.pool_size
        skip_batches = (start_sample % self.pool_size) // self.bs
        cur = self.cursors_at(p)
        while True:
            counts = self._counts(p)
            gids = []
            for i, n in enumerate(counts):
                n_i = len(self.comps[i]["items"])
                for c in range(cur[i], cur[i] + n):
                    gids.append(int(self.offsets[i] + self._perm(i, c // n_i)[c % n_i]))
            cur += counts
            rng = np.random.default_rng([self.seed, 11, p])
            gids = np.array(gids)
            noise = rng.random(len(gids))
            order = np.lexsort((noise, self.lens[gids] + rng.integers(0, 3, len(gids))))
            gids = gids[order]
            nb = len(gids) // self.bs
            bl = [gids[k * self.bs:(k + 1) * self.bs].tolist() for k in range(nb)]
            perm = rng.permutation(nb)
            for j, k in enumerate(perm):
                if j < skip_batches:
                    continue
                yield bl[k]
            skip_batches = 0
            p += 1
# ---------------------------------------------------------------------------------- end of the copy


def nfc(s):
    return _WS.sub(" ", unicodedata.normalize("NFC", s)).strip()


def encoded_len(text):
    """Length of the HTR-Flor target: the pinned Tokenizer inserts a separator between equal neighbouring letters."""
    groups = ["".join(g) for _, g in groupby(text)]
    return sum(2 * len(x) - 1 if len(x) > 1 else 1 for x in groups)


def load_components(mix_comps):
    comps = []
    for c in mix_comps:
        rows = rc.read_manifest(c["manifest"])
        items = []
        flt = c.get("filter") or {}
        for r in rows:
            if r.get("unit") == "page":
                continue
            if r.get("split") and r["split"] != "train":
                continue
            ok = True
            for col, vals in flt.items():
                vals = vals if isinstance(vals, (list, tuple)) else [vals]
                if r.get(col) not in vals:
                    ok = False
                    break
            if not ok:
                continue
            t = nfc(r["text"])
            if not t and r.get("kind") != "clutter":
                continue
            items.append((r["image"], t, r.get("kind", "")))
        if not items:
            raise ValueError("component %s has no usable rows" % c["name"])
        comps.append({"name": c["name"], "share": c["share"], "items": items})
    return comps


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("mix")
    ap.add_argument("out")
    ap.add_argument("--n", type=int, default=150016)
    ap.add_argument("--seed", type=int, default=20261121)
    ap.add_argument("--max_draw", type=int, default=2000000)
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    mix = load_mix(a.mix)
    comps = load_components(mix)
    flat = [(ci, it) for ci, c in enumerate(comps) for it in c["items"]]
    stream = MixStream(comps, 32, a.seed)
    stats = {"mix_yaml": a.mix, "mix_yaml_sha256": hashlib.sha256(open(a.mix, "rb").read()).hexdigest(), "seed": a.seed, "target": a.n,
             "components": [{"name": c["name"], "share": c["share"], "train_items": len(c["items"])} for c in comps]}
    sel = {"R1": [], "R2": []}
    skip = {"R1": {"empty_label": 0, "too_long_for_128_frames": 0}, "R2": {"empty_label": 0, "label_24_or_more_characters": 0}}
    drawn = 0
    by_comp = {"R1": {}, "R2": {}}
    for batch in stream.batches(0):
        for gid in batch:
            drawn += 1
            ci, (img, text, kind) = flat[gid]
            # R1
            if len(sel["R1"]) < a.n:
                if not text:
                    skip["R1"]["empty_label"] += 1     # the pinned CTC loss (keras ctc_batch_cost) raises "Labels length is zero" for an empty target (smoke test, 21 Nov)
                elif encoded_len(text) > 128:
                    skip["R1"]["too_long_for_128_frames"] += 1
                else:
                    sel["R1"].append((img, text, kind, comps[ci]["name"]))
                    by_comp["R1"][comps[ci]["name"]] = by_comp["R1"].get(comps[ci]["name"], 0) + 1
            # R2
            if len(sel["R2"]) < a.n:
                if not text:
                    skip["R2"]["empty_label"] += 1
                elif len(text) >= 24:
                    skip["R2"]["label_24_or_more_characters"] += 1
                else:
                    sel["R2"].append((img, text, kind, comps[ci]["name"]))
                    by_comp["R2"][comps[ci]["name"]] = by_comp["R2"].get(comps[ci]["name"], 0) + 1
        if (len(sel["R1"]) >= a.n and len(sel["R2"]) >= a.n) or drawn > a.max_draw:
            break
    stats["drawn_from_stream"] = drawn
    stats["skipped"] = skip
    stats["selected"] = {k: len(v) for k, v in sel.items()}
    stats["selected_per_component"] = by_comp
    for k in sel:
        if len(sel[k]) < a.n:
            stats["WARNING_" + k] = "only %d of %d eligible samples found within %d draws" % (len(sel[k]), a.n, drawn)
    # character set: every character of every training label of the mix (NFC, case kept)
    chars = sorted({ch for c in comps for it in c["items"] for ch in it[1]})
    json.dump({"run": "iii", "n_chars": len(chars), "chars": "".join(chars), "source": "all characters of the train rows of the mix_v1 manifests (NFC, case kept), sorted by code point"},
              open(os.path.join(a.out, "charset_iii.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    with open(os.path.join(a.out, "ppocr_dict_iii.txt"), "w", encoding="utf-8", newline="") as f:
        for ch in chars:
            if ch != " " and ch not in "\n\r\t":
                f.write(ch + "\n")
    rs = np.random.RandomState(a.seed)
    for k in ("R1", "R2"):
        rows = sel[k][:a.n]
        order = rs.permutation(len(rows))
        rows = [rows[i] for i in order]
        with open(os.path.join(a.out, "mix_iii_%s.tsv" % k), "w", encoding="utf-8", newline="") as f:
            f.write("image\ttext\tkind\tcomponent\n")
            for r in rows:
                f.write("\t".join(x.replace("\t", " ").replace("\n", " ") for x in r) + "\n")
        if k == "R2":
            with open(os.path.join(a.out, "ppocr_iii_train.txt"), "w", encoding="utf-8", newline="") as f:
                for r in rows:
                    f.write(r[0] + "\t" + r[1] + "\n")
        kinds = {}
        for r in rows:
            kinds[r[2]] = kinds.get(r[2], 0) + 1
        stats["kind_counts_" + k] = kinds
    lm = rc.read_manifest(rc.MANIFESTS + "/kohtd_lmtune.tsv")
    with open(os.path.join(a.out, "ppocr_iii_val.txt"), "w", encoding="utf-8", newline="") as f:
        for r in lm:
            f.write(r["image"] + "\t" + nfc(r["text"]) + "\n")
    stats["charset_size"] = len(chars)
    json.dump(stats, open(os.path.join(a.out, "mix_iii_stats.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    print(json.dumps({k: v for k, v in stats.items() if k not in ("components", "selected_per_component")}, ensure_ascii=False, indent=1))


if __name__ == "__main__":
    main()