"""Union codec: the base model codec (kraken PP-OCRv6, identical for medium and small, sha256 946b0384...) plus every character of the mix_v1 training labels that it lacks (kraken's `resize union`: new labels are appended after the base labels, so the base labels keep their meaning). All five arms use this one codec. Labels are NFD. Usage: python -m linedet.make_codec --mix --out """ import argparse import unicodedata from collections import Counter from kraken.lib.codec import PytorchCodec from . import data as D from .common import LD_OUT, load_json, save_json, utcnow def main(): ap = argparse.ArgumentParser() ap.add_argument("--mix", required=True) ap.add_argument("--base", default=LD_OUT + "/base_models/base_medium_codec.json") ap.add_argument("--out", default=LD_OUT + "/codec_union.json") a = ap.parse_args() base = PytorchCodec(load_json(a.base)) comps = D.load_components(D.load_mix(a.mix), "train") cnt = Counter() per_comp = {} for c in comps: cc = Counter() for _, t, _ in c["items"]: cc.update(t) per_comp[c["name"]] = len(cc) cnt.update(cc) missing = sorted(ch for ch in cnt if ch not in base.c2l) union = base.add_labels(missing) if missing else base added = [{"char": ch, "codepoint": "U+%04X" % ord(ch), "name": unicodedata.name(ch, "?"), "train_count": cnt[ch], "label": union.c2l[ch][0]} for ch in missing] save_json(a.out, {"c2l": union.c2l, "base_size": len(base), "base_max_label": base.max_label, "union_size": len(union), "union_max_label": union.max_label, "n_added": len(missing), "added": added, "train_alphabet_size": len(cnt), "alphabet_by_component": per_comp, "mix": a.mix, "created": utcnow()}) print("base %d entries; train alphabet %d characters; added %d; union %d entries (max label %d)" % ( len(base), len(cnt), len(missing), len(union), union.max_label)) for d in added: print(d) if __name__ == "__main__": main()