File size: 13,072 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
"""RELEASE2 job B: regenerate every stage-1 generated page that contributed a released row, and check it.

Why: a line crop records the font of its own line only. A page can also carry other text (the page writer's hand on a
typed worksheet, figure labels, marks). To know whether any font of personal-use licence touched a crop's page, the page's
full font list is needed; it is stored only for the 4,599 pages saved whole. The generator is deterministic (every page is a
function of seed tag, split, population, language and page index), so the pages can be rebuilt exactly.

How: the production driver CODE/src/pagesynth/produce_r5.py is imported unchanged and its work() function is called for
each page index, with the same settings as production (seed tag r5v1, font policy of the split, the split's text bank,
pages_save from the stage-1 chunk list). cv2.imwrite is replaced by an in-memory JPEG encoder that records the sha256 of
the bytes it would have written; nothing is written into the data tree (out_root is a scratch folder; page JSON files of
saved pages are written there and compared byte for byte with the stored ones). GEN.attempt_page is wrapped to capture the
page JSON (fonts, licence class, attempt) and the bank's list of drawn sentences (document ids only).

Checks per row of the released manifests (frozen train, frozen val/test, pages): the regenerated row must exist and every
column except the image path must be equal; the regenerated crop bytes must equal the stored file (sha256).

usage: CODE/.venv_gen/bin/python -I rel2_regen.py --out DIR --workers 16 [--only-split train] [--only-lang kk] [--limit N]
"""
import argparse
import csv
import hashlib
import json
import multiprocessing as mp
import os
import re
import sys
import time
from collections import Counter, defaultdict

os.environ.setdefault("OMP_NUM_THREADS", "1")
CODE_GEN = "/path/to/TURKIC_OCR_CODE/src/pagesynth"
D = "/path/to/TURKIC_OCR_DATA"
R5 = D + "/data/processed/r5"
TEXT_ROOT = R5 + "/pagesynth_text_split"
CHUNKS = D + "/tmp/r5_chunks_stage1.tsv"
os.environ["PAGESYNTH_FONTS"] = CODE_GEN + "/assets/fonts"
sys.path.insert(0, CODE_GEN)
csv.field_size_limit(10 ** 9)

import cv2  # noqa: E402
cv2.setNumThreads(1)
import produce_r5 as P5  # noqa: E402  (the production driver, unchanged)

LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"]
RX_LINE = re.compile(r"^(hs|ts|cl)_(train|val|test)_(.+)_(\d{6})_(\d{2})$")
RX_PAGE = re.compile(r"^pg_(train|val|test)_[a-z]+_(.+)_[lmh]_(\d{6})$")

_ORIG_IMWRITE = cv2.imwrite
HASHES = {}
CAPTURE = {}


def fake_imwrite(path, img, params=None):
    ok, buf = cv2.imencode(".jpg", img, params or [])
    if not ok:
        raise RuntimeError("imencode failed for %s" % path)
    b = buf.tobytes()
    HASHES[path] = (hashlib.sha256(b).hexdigest(), len(b))
    return True


_ORIG_ATTEMPT = P5.GEN.attempt_page


def wrapped_attempt(*args, **kw):
    img, pj, qa, failures = _ORIG_ATTEMPT(*args, **kw)
    CAPTURE["pj"] = pj
    CAPTURE["failures"] = failures
    return img, pj, qa, failures


P5.cv2.imwrite = fake_imwrite
P5.GEN.attempt_page = wrapped_attempt


def regen_one(task):
    idx, = task
    HASHES.clear()
    CAPTURE.clear()
    lang = P5.G["args"].lang
    _, rows, sec, fail = P5.work((idx,))
    pj = CAPTURE.get("pj")
    drawn = list(dict.fromkeys(src for src, _s in (P5.G["banks"][lang].drawn or [])))
    page = None
    if pj is not None:
        page = dict(page_id=pj.get("page_id"), attempt=(pj.get("info") or {}).get("attempt"), fonts=pj.get("fonts"), licence_class=pj.get("licence_class"),
                    include_personal=(pj.get("info") or {}).get("include_personal_fonts"), writer=(pj.get("info") or {}).get("writer"),
                    page_type=(pj.get("info") or {}).get("page_type"), n_lines=len(pj.get("lines", [])))
    out_rows = []
    for r in rows:
        rr = {c: str(r.get(c, "")).replace("\t", " ").replace("\n", " ") for c in P5.COLS}
        h = HASHES.get(r.get("image"))
        rr["_sha256"], rr["_bytes"] = (h if h else ("", 0))
        out_rows.append(rr)
    return idx, page, drawn, out_rows, round(sec, 3), fail, [list(map(str, f)) for f in (CAPTURE.get("failures") or [])]


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def load_manifest(path):
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", required=True)
    ap.add_argument("--workers", type=int, default=16)
    ap.add_argument("--only-split", default="")
    ap.add_argument("--only-lang", default="")
    ap.add_argument("--limit", type=int, default=0, help="at most N pages per group (smoke test)")
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    scratch = os.path.join(a.out, "scratch_out_root")
    os.makedirs(scratch, exist_ok=True)
    if len(P5.F.REGISTRY) != 73:
        sys.exit("font registry holds %d fonts, expected 73" % len(P5.F.REGISTRY))

    # released rows (generated only): frozen train, frozen val/test, pages; plus the pre-freeze train rows (dropped at the freeze)
    sources = {}
    for kind in ("hand", "typed", "clutter"):
        sources[("train", kind)] = R5 + "/frozen_mix_v1/synth_%s_train.meta.tsv" % kind
        sources[("train_prefreeze", kind)] = R5 + "/manifests/synth_%s_train.meta.tsv" % kind
        for sp in ("val", "test"):
            sources[(sp, kind)] = R5 + "/frozen_eval_v1/synth_%s_%s.meta.tsv" % (kind, sp)
    sources[("train", "pages")] = R5 + "/manifests/synth_pages_train.meta.tsv"
    for sp in ("val", "test"):
        sources[(sp, "pages")] = R5 + "/frozen_eval_v1/synth_pages_%s.meta.tsv" % sp
    want = defaultdict(set)          # (split, lang, pop) -> page indices
    ref = {}                         # id -> manifest row
    for (sp, kind), p in sources.items():
        for r in load_manifest(p):
            if r["id"] in ref:
                continue
            ref[r["id"]] = r
            m = RX_LINE.match(r["id"])
            if m:
                pref, split, lang, idx = m.group(1), m.group(2), m.group(3), int(m.group(4))
                pop = "T" if pref == "ts" else "H"
            else:
                m = RX_PAGE.match(r["id"])
                if not m:
                    print("unparsed id", r["id"], flush=True)
                    continue
                split, rest, idx = m.group(1), m.group(2), int(m.group(3))
                lang, pop = r["lang"], "H"
            want[(split, lang, pop)].add(idx)
    psave = {}
    with open(CHUNKS, encoding="utf-8") as f:
        for lang, split, pop, start, n, ps in csv.reader(f, delimiter="\t"):
            psave[(split, lang, pop)] = max(psave.get((split, lang, pop), 0), int(ps))
    print("released or pre-freeze rows", len(ref), "groups", len(want), "pages", sum(len(v) for v in want.values()), flush=True)

    pages_out = open(os.path.join(a.out, "pages.jsonl"), "w", encoding="utf-8")
    mism_out = open(os.path.join(a.out, "row_mismatches.jsonl"), "w", encoding="utf-8")
    seen_ids = set()
    stat = Counter()
    col_mism = Counter()
    per_group = {}
    sample_writes = 0
    t0 = time.time()
    for split in ("train", "val", "test"):
        if a.only_split and split != a.only_split:
            continue
        for lang in LANGS:
            if a.only_lang and lang != a.only_lang:
                continue
            for pop in ("H", "T"):
                idxs = sorted(want.get((split, lang, pop), ()))
                if not idxs:
                    continue
                if a.limit:
                    idxs = idxs[: a.limit]
                tg = time.time()
                P5.G.clear()
                P5.G["args"] = argparse.Namespace(lang=lang, split=split, pop=pop, pages_save=psave.get((split, lang, pop), 0))
                P5.G["out_root"] = scratch
                P5.G["seed"] = int(P5.sha_int(P5.CFG["seed_tag"], split, pop) % (2 ** 31))
                P5.set_font_policy(split)
                banks = P5.GEN.load_banks(os.path.join(TEXT_ROOT, split), [lang], filename="sentences.tsv")
                if banks[lang].vocab.source == "bank-fallback":
                    sys.exit("label vocabulary missing for %s %s" % (split, lang))
                P5.G["banks"] = banks
                g = Counter()
                ctx = mp.get_context("fork")
                with ctx.Pool(a.workers) as pool:
                    for idx, page, drawn, rows, sec, fail, failures in pool.imap(regen_one, [(i,) for i in idxs], chunksize=2):
                        g["pages"] += 1
                        if page is None:
                            g["page_failed"] += 1
                        rec = dict(split=split, lang=lang, pop=pop, idx=idx, page=page, drawn_docs=drawn, failures=failures,
                                   row_ids=[r["id"] for r in rows], seconds=sec)
                        pages_out.write(json.dumps(rec, ensure_ascii=False) + "\n")
                        for r in rows:
                            rid = r["id"]
                            if rid not in ref:
                                g["regen_row_not_in_manifests"] += 1
                                continue
                            seen_ids.add(rid)
                            m = ref[rid]
                            bad = []
                            for c in P5.COLS:
                                if c == "image":
                                    continue
                                va, vb = r.get(c, ""), m.get(c, "")
                                if c == "source" and r.get("unit") == "page":
                                    va, vb = os.path.basename(va), os.path.basename(vb)
                                if va != vb:
                                    bad.append(c)
                            orig = m["image"]
                            try:
                                hs = sha256_file(orig)
                            except OSError:
                                hs = "missing"
                            same_bytes = (hs == r["_sha256"])
                            if r.get("unit") == "page":
                                # page JSON written to scratch by work(): compare bytes with the stored JSON
                                jp_new = os.path.join(scratch, "pages", split, lang, os.path.basename(m["source"]))
                                try:
                                    same_json = sha256_file(jp_new) == sha256_file(m["source"])
                                except OSError:
                                    same_json = False
                                g["page_json_equal" if same_json else "page_json_differs"] += 1
                            if not same_bytes and sample_writes < 20:
                                sample_writes += 1
                            g["rows_checked"] += 1
                            g["rows_cols_equal" if not bad else "rows_cols_differ"] += 1
                            g["bytes_equal" if same_bytes else "bytes_differ"] += 1
                            for c in bad:
                                col_mism[c] += 1
                            if bad or not same_bytes:
                                mism_out.write(json.dumps(dict(id=rid, cols=bad, bytes_equal=same_bytes,
                                                               regen={c: r.get(c, "") for c in bad}, stored={c: m.get(c, "") for c in bad}), ensure_ascii=False) + "\n")
                per_group["%s|%s|%s" % (split, lang, pop)] = dict(g, seconds=round(time.time() - tg, 1), pages_save=psave.get((split, lang, pop), 0))
                stat.update(g)
                print(split, lang, pop, dict(g), "%.0f s" % (time.time() - tg), flush=True)
                pages_out.flush()
                mism_out.flush()
    pages_out.close()
    mism_out.close()
    # rows of the manifests that no regenerated page produced
    scope = [rid for rid in ref if (not a.only_split or ref[rid]["split"] == a.only_split) and (not a.only_lang or ref[rid]["lang"] == a.only_lang)]
    missing = [rid for rid in scope if rid not in seen_ids]
    res = dict(written_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), seconds=round(time.time() - t0, 1), workers=a.workers,
               limit=a.limit, only_split=a.only_split, only_lang=a.only_lang, generator_version=P5.GEN.VERSION, fonts_in_registry=len(P5.F.REGISTRY),
               totals=dict(stat), column_mismatch_counts=dict(col_mism), manifest_rows_in_scope=len(scope),
               manifest_rows_not_regenerated=len(missing) if not a.limit else "n/a (limit)", missing_examples=missing[:50] if not a.limit else [], per_group=per_group)
    with open(os.path.join(a.out, "regen_summary.json"), "w", encoding="utf-8") as f:
        json.dump(res, f, indent=1, ensure_ascii=False)
    print(json.dumps(res["totals"]), flush=True)


if __name__ == "__main__":
    main()