"""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 : 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 [--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()