turkic-ocr-code / scripts /release2 /rel2_d5_prep.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
6.61 kB
"""RELEASE2 owner decisions D4 and D5 (25 Nov 2026), CPU part. Nothing is trained here.
D5: build the stage-2 detector training set without the 83 generated train pages that carry a personal-use font:
DATA/data/processed/r5_linedet_det/gen_d5/train/{images,labels} copies of the 3,916 remaining generated train pages (image + YOLO label)
DATA/data/processed/r5_linedet_det/gen_d5/pages_gen_train.tsv the page list of gen/pages_gen_train.tsv minus the 83 pages
DATA/data/processed/r5_linedet_det/yolo_all_d5.yaml School Notebooks train + gen_d5 train; validation unchanged
D4: count, over every generated TRAIN page behind a frozen training row, the pages that drew each personal-use font: fonts from the saved
page JSON when it exists, else from the regenerated page (job 55358).
Writes DATA/tmp/release2/d5/prep_report.json.
usage: CODE/.venv_gen/bin/python -I rel2_d5_prep.py EXCLUDED_PAGES_TSV"""
import csv
import hashlib
import json
import os
import re
import shutil
import sys
from collections import Counter, defaultdict
csv.field_size_limit(10 ** 9)
D = "/path/to/TURKIC_OCR_DATA"
DET = D + "/data/processed/r5_linedet_det"
R5 = D + "/data/processed/r5"
OUT = D + "/tmp/release2/d5"
os.makedirs(OUT, exist_ok=True)
RX_LINE = re.compile(r"^(hs|ts|cl)_(train|val|test)_(.+)_(\d{6})_(\d{2})$")
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()
excl = {}
with open(sys.argv[1], encoding="utf-8") as f:
for r in csv.DictReader(f, delimiter="\t"):
excl[r["id"]] = r
rep = dict(excluded_requested=len(excl))
# ---------------- D5 data
src_list = DET + "/gen/pages_gen_train.tsv"
with open(src_list, newline="", encoding="utf-8") as f:
rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
cols = rd.fieldnames
rows = list(rd)
ids = set(r["id"] for r in rows)
rep["gen_train_pages_before"] = len(rows)
rep["excluded_found_in_detector_list"] = sum(1 for i in excl if i in ids)
rep["excluded_missing_from_detector_list"] = sorted(i for i in excl if i not in ids)
keep = [r for r in rows if r["id"] not in excl]
rep["gen_train_pages_after"] = len(keep)
dst = DET + "/gen_d5"
if os.path.exists(dst):
sys.exit("exists: " + dst)
os.makedirs(dst + "/train/images")
os.makedirs(dst + "/train/labels")
miss = []
for r in keep:
img = DET + "/gen/train/images/%s.jpg" % r["id"]
lab = DET + "/gen/train/labels/%s.txt" % r["id"]
if not (os.path.exists(img) and os.path.exists(lab)):
miss.append(r["id"])
continue
shutil.copyfile(img, dst + "/train/images/%s.jpg" % r["id"])
shutil.copyfile(lab, dst + "/train/labels/%s.txt" % r["id"])
rep["missing_image_or_label"] = miss
with open(dst + "/pages_gen_train.tsv", "w", encoding="utf-8", newline="") as f:
f.write("\t".join(cols) + "\n")
for r in keep:
f.write("\t".join(r[c] for c in cols) + "\n")
with open(dst + "/excluded_pages_personal_fonts.tsv", "w", encoding="utf-8") as f:
f.write("id\tlanguage\tpersonal_use_fonts\tpage_licence_class\n")
for i in sorted(excl):
e = excl[i]
f.write("\t".join((i, e["language"], e["personal_use_fonts"], e["page_licence_class"])) + "\n")
yaml = "\n".join(["# RELEASE2 D5: stage-2 data without the 83 generated train pages that carry a personal-use font", "path: /", "train:",
" - " + DET + "/school2/train/images", " - " + dst + "/train/images", "val:",
" - " + DET + "/school2/val/images", " - " + DET + "/gen/val/images", "names:", " 0: text_line"]) + "\n"
open(DET + "/yolo_all_d5.yaml", "w").write(yaml)
rep["n_images_copied"] = len(os.listdir(dst + "/train/images"))
rep["n_labels_copied"] = len(os.listdir(dst + "/train/labels"))
rep["files"] = {p.replace(D, "DATA"): sha256_file(p) for p in (dst + "/pages_gen_train.tsv", dst + "/excluded_pages_personal_fonts.tsv", DET + "/yolo_all_d5.yaml")}
# no personal-use page may remain: check against the saved page JSONs of every kept page
left = 0
pages_meta = {}
with open(R5 + "/manifests/synth_pages_train.meta.tsv", newline="", encoding="utf-8") as f:
for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
pages_meta[r["id"]] = r["source"]
for r in keep:
jp = pages_meta.get(r["id"])
if jp is None:
rep.setdefault("kept_without_page_json", []).append(r["id"])
continue
pj = json.load(open(jp, encoding="utf-8"))
if any(x.get("licence_class") == "personal_use_only" for x in pj.get("fonts", [])):
left += 1
rep["kept_pages_with_personal_font"] = left
# ---------------- D4 counts over generated TRAIN pages behind frozen training rows
frozen_keys = set()
for kind in ("hand", "typed", "clutter"):
with open(R5 + "/frozen_mix_v1/synth_%s_train.tsv" % kind, newline="", encoding="utf-8") as f:
for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
m = RX_LINE.match(r["id"])
frozen_keys.add((r["lang"], "T" if m.group(1) == "ts" else "H", int(m.group(4))))
saved = {}
for pid, jp in pages_meta.items():
m = re.match(r"^pg_train_[a-z]+_(.+)_[lmh]_(\d{6})$", pid)
saved[(m.group(1), "H", int(m.group(2)))] = jp
per_font = Counter()
per_font_pop = Counter()
pages_with = Counter()
src_used = Counter()
with open(D + "/tmp/release2/regen/pages.jsonl", encoding="utf-8") as f:
for line in f:
if '"split": "train"' not in line:
continue
r = json.loads(line)
key = (r["lang"], r["pop"], r["idx"])
if key not in frozen_keys:
continue
if key in saved:
fonts = json.load(open(saved[key], encoding="utf-8")).get("fonts", [])
src_used["saved_page_json"] += 1
else:
fonts = (r.get("page") or {}).get("fonts") or []
src_used["regenerated_page"] += 1
pers = [x["id"] for x in fonts if x.get("licence_class") == "personal_use_only"]
for p in pers:
per_font[p] += 1
per_font_pop["%s|%s" % (p, r["pop"])] += 1
pages_with["%s|%s" % (r["pop"], "personal" if pers else "open")] += 1
rep["d4"] = dict(train_pages_behind_frozen_rows=len(frozen_keys), page_font_source=dict(src_used), pages_by_population_and_class=dict(pages_with),
pages_per_personal_font=dict(per_font), pages_per_personal_font_and_population=dict(per_font_pop))
json.dump(rep, open(OUT + "/prep_report.json", "w"), indent=1)
print(json.dumps({k: v for k, v in rep.items() if k != "files"}, indent=1)[:4000])