File size: 2,084 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
"""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 <mix yaml> --out <codec_union.json>
"""
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()