File size: 13,621 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 263 264 265 266 267 268 269 270 271 272 273 274 | """RELEASE2 job A: read-only facts for the licence audit and the data package.
Runs on a ZEN4 node with CODE/.venv_gen/bin/python (fontTools is installed there).
Writes everything under DATA/tmp/release2/facts/. Reads only generated (synth_*) manifests;
no real-data test manifest is opened. Real print: only the train and val manifests (ids, docs).
Outputs
fonts_names.json per font file in CODE/src/pagesynth/assets/fonts: sha256, size, name-table records
raw_fonts.json per folder of DATA/data/raw/fonts: files with sha256, first lines of the licence file
code_mtimes.json mtimes (UTC) of the generator code and of the stage-1 part files
licence_files/ copies of README/LICENSE-like files of the base models and the raw data sets (read later as data)
meta_counts.json counts per manifest: language x licence class, source-document kinds, confidence, sizes
dropped_at_freeze.json ids in the pre-freeze train manifests that are not in frozen_mix_v1
saved_pages_fonts.json per saved page (synth_pages_*): fonts with licence classes, page licence class
"""
import csv
import datetime as dt
import glob
import hashlib
import json
import os
import shutil
import sys
from collections import Counter, defaultdict
csv.field_size_limit(10 ** 9)
D = "/path/to/TURKIC_OCR_DATA"
C = "/path/to/TURKIC_OCR_CODE"
OUT = D + "/tmp/release2/facts"
R5 = D + "/data/processed/r5"
os.makedirs(OUT, exist_ok=True)
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 utc(ts):
return dt.datetime.fromtimestamp(ts, dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def dump(name, obj):
with open(os.path.join(OUT, name), "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=1, sort_keys=True)
print("wrote", name, flush=True)
# ---------------- (a) fonts
def fonts_facts():
from fontTools.ttLib import TTFont
res = []
for p in sorted(glob.glob(C + "/src/pagesynth/assets/fonts/*")):
if not os.path.isfile(p):
continue
rec = dict(file=os.path.basename(p), bytes=os.path.getsize(p), sha256=sha256_file(p), names={})
try:
f = TTFont(p, lazy=True)
for r in f["name"].names:
if r.nameID not in (0, 1, 2, 4, 5, 7, 8, 9, 11, 12, 13, 14):
continue
try:
s = r.toUnicode()
except Exception:
continue
key = str(r.nameID)
# prefer Windows platform records; keep the first one seen otherwise
if key not in rec["names"] or r.platformID == 3:
rec["names"][key] = s[:3000]
except Exception as e: # recorded, not hidden
rec["error"] = repr(e)[:300]
res.append(rec)
dump("fonts_names.json", res)
raw = {}
for d in sorted(glob.glob(D + "/data/raw/fonts/*")):
if not os.path.isdir(d):
continue
ent = dict(files=[])
for p in sorted(glob.glob(d + "/*")):
e = dict(name=os.path.basename(p), bytes=os.path.getsize(p), sha256=sha256_file(p))
if os.path.basename(p).upper().startswith(("OFL", "LICENSE", "LICENCE")):
with open(p, encoding="utf-8", errors="replace") as f:
e["first_lines"] = [next(f, "").rstrip("\n") for _ in range(8)]
ent["files"].append(e)
raw[os.path.basename(d)] = ent
dump("raw_fonts.json", raw)
# ---------------- (b) mtimes
def mtimes():
res = dict(code={}, parts_stage1={}, manifests={}, venv_gen_newest=None)
for p in sorted(glob.glob(C + "/src/pagesynth/**/*", recursive=True)):
if os.path.isfile(p) and not p.endswith(".pyc") and "/assets/fonts/" not in p:
res["code"][p.replace(C, "CODE")] = utc(os.path.getmtime(p))
parts = [p for p in glob.glob(R5 + "/synth/_parts/*.tsv")]
if parts:
ms = sorted((os.path.getmtime(p), os.path.basename(p)) for p in parts)
res["parts_stage1"] = dict(n=len(parts), first=[utc(ms[0][0]), ms[0][1]], last=[utc(ms[-1][0]), ms[-1][1]])
for p in sorted(glob.glob(R5 + "/manifests/synth_*.tsv") + glob.glob(R5 + "/frozen_mix_v1/synth_*.tsv") + glob.glob(R5 + "/frozen_eval_v1/synth_*.tsv")):
res["manifests"][p.replace(D, "DATA")] = dict(mtime=utc(os.path.getmtime(p)), bytes=os.path.getsize(p), sha256=sha256_file(p))
newest = (0, "")
for p in glob.glob(C + "/.venv_gen/lib/python*/site-packages/*"):
m = os.path.getmtime(p)
if m > newest[0]:
newest = (m, os.path.basename(p))
res["venv_gen_newest"] = [utc(newest[0]), newest[1]]
pyc = glob.glob(C + "/src/pagesynth/**/__pycache__/*.pyc", recursive=True)
res["pyc"] = {p.replace(C, "CODE"): utc(os.path.getmtime(p)) for p in sorted(pyc)}
dump("code_mtimes.json", res)
# ---------------- (c) licence-like files
def licence_files():
dst = os.path.join(OUT, "licence_files")
os.makedirs(dst, exist_ok=True)
names = ("README", "LICENSE", "LICENCE", "COPYING", "NOTICE", "CITATION", "TERMS", "DATASHEET", "MODEL_CARD")
roots = {}
for m in ("paddleocr_vl_1_6", "qwen3_vl_2b"):
roots["hf_" + m] = D + "/hf_cache/j2_models/" + m
for r in ("kohtd", "hkr_words_kaggle_scispecai", "school_notebooks_ru", "chd", "ailabykt_sakha_mono", "naf", "doclaynet_v1_2_test",
"sheriyeva", "zenodo_ppocrv6_medium_21788410", "kenlm_0_3_0_sdist", "r5_print", "more_real_print", "localdoc_az_htr", "rukopys_test"):
roots["raw_" + r] = D + "/data/raw/" + r
for v in ("ultralytics-8.4.216.dist-info", "kenlm-0.3.0.dist-info", "kraken-7.2.dist-info"):
roots["venv_kraken_" + v] = C + "/.venv_kraken/lib/python3.12/site-packages/" + v
roots["pagesynth_naturalearth"] = C + "/src/pagesynth/assets/naturalearth"
index = {}
for key, root in roots.items():
found = []
if not os.path.isdir(root):
index[key] = dict(root=root.replace(D, "DATA").replace(C, "CODE"), exists=False)
continue
for dirpath, dirnames, filenames in os.walk(root):
depth = dirpath[len(root):].count(os.sep)
if depth > 4:
dirnames[:] = []
continue
dirnames[:] = [x for x in dirnames if x not in ("blobs",)]
for fn in filenames:
up = fn.upper()
if up.startswith(names) or up.endswith((".MD", ".CFF")) or fn in ("METADATA", "terms_of_use.html", "dataset_infos.json"):
p = os.path.join(dirpath, fn)
try:
real = os.path.realpath(p)
sz = os.path.getsize(real)
except OSError:
continue
if sz > 3_000_000:
found.append(dict(path=p.replace(D, "DATA").replace(C, "CODE"), bytes=sz, copied=False))
continue
rel = os.path.relpath(p, root).replace(os.sep, "__")
os.makedirs(os.path.join(dst, key), exist_ok=True)
shutil.copyfile(real, os.path.join(dst, key, rel))
found.append(dict(path=p.replace(D, "DATA").replace(C, "CODE"), bytes=sz, sha256=sha256_file(real), copied_as=key + "/" + rel))
index[key] = dict(root=root.replace(D, "DATA").replace(C, "CODE"), exists=True, files=found)
dump("licence_files_index.json", index)
# ---------------- (d) meta counts
def doc_kinds(sd):
if not sd:
return "none"
ks = sorted(set(x.split(":")[0] for x in sd.split("|") if x))
return "+".join(ks)
def meta_counts():
files = {}
for kind in ("hand", "typed", "clutter"):
files["%s_train_frozen" % kind] = R5 + "/frozen_mix_v1/synth_%s_train.meta.tsv" % kind
files["%s_train_prefreeze" % kind] = R5 + "/manifests/synth_%s_train.meta.tsv" % kind
for sp in ("val", "test"):
files["%s_%s" % (kind, sp)] = R5 + "/frozen_eval_v1/synth_%s_%s.meta.tsv" % (kind, sp)
files["pages_train"] = R5 + "/manifests/synth_pages_train.meta.tsv"
for sp in ("val", "test"):
files["pages_%s" % sp] = R5 + "/frozen_eval_v1/synth_pages_%s.meta.tsv" % sp
res = {}
ids = {}
for key, p in files.items():
c = dict(n=0, by_lang=Counter(), lang_licence=Counter(), lang_fontlic=Counter(), lang_dockinds=Counter(), lang_conf=Counter(),
lang_heldout=Counter(), font_ids=Counter(), source_doc_len_ge_1990=0, ambiguous_3ids=0, missing_image=0, image_bytes=0,
crop_mode=Counter(), unit=Counter(), kind=Counter(), empty_text=0, lang_region=Counter(), generator_version=Counter())
idl = []
with open(p, newline="", encoding="utf-8") as f:
rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
for r in rd:
c["n"] += 1
lg = r["lang"]
idl.append((r["id"], lg))
c["by_lang"][lg] += 1
c["lang_licence"]["%s|%s" % (lg, r.get("licence_class", ""))] += 1
c["lang_fontlic"]["%s|%s" % (lg, r.get("font_licence_class", ""))] += 1
c["lang_dockinds"]["%s|%s" % (lg, doc_kinds(r.get("source_doc", "")))] += 1
c["lang_conf"]["%s|%s" % (lg, r.get("source_doc_confidence", ""))] += 1
c["lang_heldout"]["%s|%s" % (lg, r.get("heldout_font", ""))] += 1
c["lang_region"]["%s|%s" % (lg, r.get("region_class", ""))] += 1
c["font_ids"][r.get("font_id", "")] += 1
c["crop_mode"][r.get("crop_mode", "")] += 1
c["unit"][r.get("unit", "")] += 1
c["kind"][r.get("kind", "")] += 1
c["generator_version"][r.get("source", "").split(":")[0] if r.get("unit") == "line" else "page"] += 1
if not r.get("text"):
c["empty_text"] += 1
sd = r.get("source_doc", "")
if len(sd) >= 1990:
c["source_doc_len_ge_1990"] += 1
if r.get("source_doc_confidence") == "ambiguous" and sd.count("|") >= 2:
c["ambiguous_3ids"] += 1
ip = r["image"]
try:
c["image_bytes"] += os.path.getsize(ip)
except OSError:
c["missing_image"] += 1
res[key] = {k: (dict(v) if isinstance(v, Counter) else v) for k, v in c.items()}
res[key]["file"] = p.replace(D, "DATA")
ids[key] = idl
print(key, c["n"], flush=True)
dump("meta_counts.json", res)
dropped = {}
for kind in ("hand", "typed", "clutter"):
fz = set(i for i, _ in ids["%s_train_frozen" % kind])
dropped[kind] = [dict(id=i, lang=l) for i, l in ids["%s_train_prefreeze" % kind] if i not in fz]
pre = set(x for x, _ in ids["%s_train_prefreeze" % kind]) # built once (the first version rebuilt it per id: quadratic)
extra = [i for i in fz if i not in pre]
dropped[kind + "_in_frozen_not_prefreeze"] = extra
dump("dropped_at_freeze.json", dropped)
# val/test frozen vs manifests equality
eq = {}
for kind in ("hand", "typed", "clutter", "pages"):
for sp in ("val", "test"):
for suf in (".tsv", ".meta.tsv"):
a = R5 + "/frozen_eval_v1/synth_%s_%s%s" % (kind, sp, suf)
b = R5 + "/manifests/synth_%s_%s%s" % (kind, sp, suf)
eq["synth_%s_%s%s" % (kind, sp, suf)] = sha256_file(a) == sha256_file(b)
for kind in ("hand", "typed", "clutter"):
a = R5 + "/frozen_mix_v1/synth_%s_train.tsv" % kind
b = R5 + "/manifests/synth_%s_train.tsv" % kind
eq["synth_%s_train.tsv frozen==manifests" % kind] = sha256_file(a) == sha256_file(b)
dump("frozen_equality.json", eq)
# ---------------- (e) saved pages
def saved_pages():
out = {}
summary = Counter()
for sp in ("train", "val", "test"):
p = R5 + "/manifests/synth_pages_%s.tsv" % sp
with open(p, newline="", encoding="utf-8") as f:
for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
jp = r["source"]
try:
with open(jp, encoding="utf-8") as g:
pj = json.load(g)
except Exception as e:
out[r["id"]] = dict(error=repr(e)[:200])
summary["%s|error" % sp] += 1
continue
fonts = pj.get("fonts", [])
pers = [x["id"] for x in fonts if x.get("licence_class") == "personal_use_only"]
out[r["id"]] = dict(split=sp, lang=r["lang"], licence_class=pj.get("licence_class"), fonts=fonts, personal=pers,
n_lines=len(pj.get("lines", [])), n_regions=len(pj.get("regions", [])), page_id=pj.get("page_id"),
gen=pj.get("generator_version"), include_personal=(pj.get("info") or {}).get("include_personal_fonts"))
summary["%s|%s|%s" % (sp, r["lang"], pj.get("licence_class"))] += 1
dump("saved_pages_fonts.json", dict(summary=dict(summary), pages=out))
if __name__ == "__main__":
steps = sys.argv[1:] or ["fonts", "mtimes", "licence", "meta", "pages"]
for s in steps:
dict(fonts=fonts_facts, mtimes=mtimes, licence=licence_files, meta=meta_counts, pages=saved_pages)[s]()
print("done", flush=True)
|