File size: 4,871 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
"""Choose the showcase pages (validation only) with a fixed seed.

Handwritten: one generated validation page per language from pages_gen_val.tsv. Page kinds are spread over the ten languages:
every kind once, the four most frequent kinds of the list (notebook, mixed, worksheet, diagram) a second time; the ten kinds are
shuffled with the seed and assigned to the languages in LANGS order. Within (language, kind) a medium-strength page is drawn
with the seed; if there is none, a light page, else a heavy one.
Typed: one population-T ("_T" twin) validation page per language, from the production part files val_<lang>_T_0_150.tsv
(rows of kind typed_synth carry page_id, page_type and strength). Kind: worksheet for every language; a medium page is drawn
with the seed. (Version 1 of this rule gave two languages a table page; the two table pages rebuilt in the first run held
13.7 % and 21.3 % printed reference characters, the rest hand-filled cells, so they did not show typed text; version 2,
this one, uses worksheets only. The permutation draw of version 1 is kept so that the random stream is unchanged.)
usage: select_pages.py DATA_DIR OUT_JSON
"""
import csv
import json
import os
import sys

import numpy as np

csv.field_size_limit(10 ** 9)
SEED = 20261125
LANGS = ["kk", "ky", "uz_latn", "uz_cyrl", "tr", "az", "tt", "ba", "tk", "sah"]
KINDS = ["notebook", "worksheet", "table", "diagram", "map", "mixed"]
D = sys.argv[1]
rng = np.random.default_rng(SEED)


def parse_gen_id(pid):
    # pg_val_<kind>_<lang>_<s>_<idx>
    rest = pid[len("pg_val_"):]
    kind = next(k for k in KINDS if rest.startswith(k + "_"))
    rest = rest[len(kind) + 1:]
    lang = next(l for l in sorted(LANGS, key=len, reverse=True) if rest.startswith(l + "_"))
    s, idx = rest[len(lang) + 1:].split("_")
    return kind, lang, s, int(idx)


rows = list(csv.DictReader(open(os.path.join(D, "pages_gen_val.tsv"), encoding="utf-8"), delimiter="\t", quoting=csv.QUOTE_NONE))
avail = {}
for r in rows:
    k, l, s, i = parse_gen_id(r["id"])
    avail.setdefault((l, k), {}).setdefault(s, []).append(r["id"])
counts = {"%s|%s" % lk: {s: len(v) for s, v in d.items()} for lk, d in sorted(avail.items())}

kind_list = KINDS + ["notebook", "mixed", "worksheet", "diagram"]
order = rng.permutation(len(kind_list))
assign = {lang: kind_list[j] for lang, j in zip(LANGS, order)}
hand = []
for lang in LANGS:
    k = assign[lang]
    d = avail.get((lang, k), {})
    for s in ("m", "l", "h"):
        if d.get(s):
            cand = sorted(d[s])
            pid = cand[int(rng.integers(0, len(cand)))]
            hand.append(dict(lang=lang, kind=k, strength=s, id=pid, candidates_same_strength=len(cand)))
            break
    else:
        hand.append(dict(lang=lang, kind=k, strength=None, id=None, note="no page of this kind for this language"))

# typed
tkinds = ["worksheet"] * 10
torder = rng.permutation(len(tkinds))
tassign = {lang: tkinds[j] for lang, j in zip(LANGS, torder)}
typed = []
tcounts = {}
for lang in LANGS:
    pages = {}
    with open(os.path.join(D, "parts", "val_%s_T_0_150.tsv" % lang), encoding="utf-8") as f:
        for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
            if r["kind"] != "typed_synth":
                continue
            idx = int(r["id"].split("_")[-2])
            pages.setdefault(r["page_id"], dict(page_id=r["page_id"], page_type=r["page_type"], strength=r["strength"], idx=idx, crops=[]))
            pages[r["page_id"]]["crops"].append(dict(id=r["id"], text=r["text"], crop_mode=r["crop_mode"], line_id=r["line_id"]))
    tc = {}
    for p in pages.values():
        tc["%s|%s" % (p["page_type"], p["strength"])] = tc.get("%s|%s" % (p["page_type"], p["strength"]), 0) + 1
    tcounts[lang] = tc
    k = tassign[lang]
    chosen = None
    for s in ("medium", "light", "heavy"):
        cand = sorted((p for p in pages.values() if p["page_type"] == k and p["strength"] == s), key=lambda p: p["idx"])
        if cand:
            chosen = cand[int(rng.integers(0, len(cand)))]
            break
    typed.append(dict(lang=lang, kind=k, strength=chosen["strength"], idx=chosen["idx"], page_id=chosen["page_id"],
                      production_crops=chosen["crops"]))

out = dict(seed=SEED, rule=__doc__.strip(), hand_kind_assignment=assign, typed_kind_assignment=tassign, handwritten=hand, typed=typed,
           gen_val_counts_lang_kind_strength=counts, typed_val_counts=tcounts,
           real=[dict(id="school_val_30", source="School Notebooks RU validation page (already in the deck)")])
json.dump(out, open(sys.argv[2], "w", encoding="utf-8"), ensure_ascii=False, indent=1)
for h in hand:
    print("H", h["lang"], h["kind"], h["strength"], h["id"], h.get("candidates_same_strength"))
for t in typed:
    print("T", t["lang"], t["kind"], t["strength"], t["idx"], t["page_id"], len(t["production_crops"]))