File size: 8,082 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
"""RELEASE2 owner decision D9 (25 Nov 2026): the generated-data package as Parquet shards with embedded images.

Input : DATA/release/rc1_data (labels/<kind>_<split>.jsonl, the images, SHA256SUMS, LICENSE, attribution/, excluded/, build_report.json)
Output: DATA/release/rc1_data_parquet/
          data/<kind>/<split>-NNNNN-of-MMMMM.parquet   one row per item; shards of at most about 400 MB of image bytes
          LICENSE, attribution/, excluded/ (copied unchanged), parquet_report.json, SHA256SUMS (datasheet.json is added by the finish job)
Columns: id, image (struct bytes + path, the Hugging Face Image layout), text, language, language_bcp47, script, kind, unit, split, font_id,
  font_licence_class, heldout_font, generator_version, seed (decimal string), page_id, line_id, page_type, strength, capture_mode, paper_kind,
  region_class, ink, crop_mode, text_licences (JSON list as string), record_json (the full label record), and for pages pagexml and
  page_json (the PageXML and generator JSON as strings). Hugging Face feature metadata is written in the schema (Value and Image only).
Checks: rows per (kind, split) equal the label files, total 206,619 expected; every image's sha256 equals rc1_data/SHA256SUMS; ids unique;
  every shard re-read after writing (row count and a sha256 of each image re-computed from the Parquet bytes).
usage: CODE/.venv_gen/bin/python -I rel2_parquet.py"""
import hashlib
import json
import os
import shutil
import sys
import time
from collections import Counter

import pyarrow as pa
import pyarrow.parquet as pq

D = "/path/to/TURKIC_OCR_DATA"
SRC = D + "/release/rc1_data"
OUT = D + "/release/rc1_data_parquet"
EXPECTED_TOTAL = 206619
SHARD_BYTES = 400 * 1024 * 1024
STR_COLS = ["id", "text", "language", "language_bcp47", "script", "kind", "unit", "split", "font_id", "font_licence_class", "generator_version", "seed",
            "page_id", "line_id", "page_type", "strength", "capture_mode", "paper_kind", "region_class", "ink", "crop_mode"]


def sha256_bytes(b):
    return hashlib.sha256(b).hexdigest()


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 schema(pages):
    fields = [pa.field("id", pa.string()), pa.field("image", pa.struct([pa.field("bytes", pa.binary()), pa.field("path", pa.string())]))]
    fields += [pa.field(c, pa.string()) for c in STR_COLS if c != "id"]
    fields += [pa.field("heldout_font", pa.int64()), pa.field("text_licences", pa.string()), pa.field("record_json", pa.string())]
    if pages:
        fields += [pa.field("pagexml", pa.string()), pa.field("page_json", pa.string())]
    feats = {f.name: ({"_type": "Image"} if f.name == "image" else {"dtype": "int64" if f.name == "heldout_font" else "string", "_type": "Value"}) for f in fields}
    meta = {b"huggingface": json.dumps({"info": {"features": feats}}).encode("utf-8")}
    return pa.schema(fields, metadata=meta)


def main():
    if os.path.exists(OUT):
        sys.exit("exists: " + OUT)
    t0 = time.time()
    sums = {}
    with open(SRC + "/SHA256SUMS", encoding="utf-8") as f:
        for line in f:
            h, p = line.rstrip("\n").split("  ", 1)
            sums[p] = h
    os.makedirs(OUT + "/data")
    rep = dict(started_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), source=SRC.replace(D, "DATA"), shards={}, rows={}, checks=Counter())
    seen = set()
    total = 0
    for kind in ("hand", "typed", "clutter", "pages"):
        for sp in ("train", "val", "test"):
            lab = "%s/labels/%s_%s.jsonl" % (SRC, kind, sp)
            recs = [json.loads(x) for x in open(lab, encoding="utf-8")]
            sch = schema(kind == "pages")
            # plan shards by image bytes
            groups, cur, cur_b = [], [], 0
            for r in recs:
                b = os.path.getsize(os.path.join(SRC, r["image"]))
                if cur and cur_b + b > SHARD_BYTES:
                    groups.append(cur)
                    cur, cur_b = [], 0
                cur.append(r)
                cur_b += b
            if cur:
                groups.append(cur)
            os.makedirs("%s/data/%s" % (OUT, kind), exist_ok=True)
            n_rows = 0
            for gi, g in enumerate(groups):
                cols = {f.name: [] for f in sch}
                for r in g:
                    if r["id"] in seen:
                        rep["checks"]["duplicate_id"] += 1
                    seen.add(r["id"])
                    img = open(os.path.join(SRC, r["image"]), "rb").read()
                    if sha256_bytes(img) != sums.get(r["image"]):
                        rep["checks"]["image_sha_mismatch"] += 1
                    else:
                        rep["checks"]["image_sha_ok"] += 1
                    cols["id"].append(r["id"])
                    cols["image"].append({"bytes": img, "path": os.path.basename(r["image"])})
                    for c in STR_COLS:
                        if c == "id":
                            continue
                        v = r.get(c)
                        cols[c].append(None if v is None else str(v))
                    hf = r.get("heldout_font")
                    cols["heldout_font"].append(int(hf) if isinstance(hf, (int, float)) else None)
                    cols["text_licences"].append(json.dumps(r.get("text_licences", []), ensure_ascii=False))
                    cols["record_json"].append(json.dumps(r, ensure_ascii=False, sort_keys=True))
                    if kind == "pages":
                        cols["pagexml"].append(open(os.path.join(SRC, r["pagexml"]), encoding="utf-8").read())
                        cols["page_json"].append(open(os.path.join(SRC, r["page_json"]), encoding="utf-8").read())
                tab = pa.table(cols, schema=sch)
                name = "data/%s/%s-%05d-of-%05d.parquet" % (kind, sp, gi, len(groups))
                pq.write_table(tab, os.path.join(OUT, name), compression="zstd", row_group_size=1000)
                # re-read check
                back = pq.read_table(os.path.join(OUT, name), columns=["id", "image"])
                ok = back.num_rows == len(g)
                imgs = back.column("image").to_pylist()
                ids_back = back.column("id").to_pylist()
                for rid, im, r in zip(ids_back, imgs, g):
                    if rid != r["id"] or sha256_bytes(im["bytes"]) != sums.get(r["image"]):
                        ok = False
                rep["checks"]["shard_reread_ok" if ok else "shard_reread_failed"] += 1
                rep["shards"][name] = dict(rows=len(g), bytes=os.path.getsize(os.path.join(OUT, name)))
                n_rows += len(g)
            rep["rows"]["%s_%s" % (kind, sp)] = dict(labels=len(recs), parquet=n_rows)
            total += n_rows
            print(kind, sp, len(recs), n_rows, "%.0f s" % (time.time() - t0), flush=True)
    rep["total_rows"] = total
    rep["expected_total"] = EXPECTED_TOTAL
    rep["total_ok"] = total == EXPECTED_TOTAL and all(v["labels"] == v["parquet"] for v in rep["rows"].values())
    for name in ("LICENSE", "build_report.json"):
        shutil.copyfile(os.path.join(SRC, name), os.path.join(OUT, name))
    for d in ("attribution", "excluded"):
        shutil.copytree(os.path.join(SRC, d), os.path.join(OUT, d))
    rep["checks"] = dict(rep["checks"])
    rep["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    rep["seconds"] = round(time.time() - t0, 1)
    json.dump(rep, open(OUT + "/parquet_report.json", "w"), indent=1)
    with open(OUT + "/SHA256SUMS", "w") as f:
        for root, _, files in os.walk(OUT):
            for fn in sorted(files):
                p = os.path.join(root, fn)
                rel = os.path.relpath(p, OUT)
                if rel == "SHA256SUMS":
                    continue
                f.write("%s  %s\n" % (sha256_file(p), rel))
    print(json.dumps(dict(total=total, ok=rep["total_ok"], checks=rep["checks"], shards=len(rep["shards"]))), flush=True)


if __name__ == "__main__":
    main()