turkic-ocr-code / scripts /r5_showcase /showcase_kzb_prep.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
3.85 kB
"""Showcase: one page of the Kazakh Real-Document OCR Benchmark, handwritten subset (DATA/data/raw/kz_benchmark_hw), for the page pipeline.
The page is drawn with a fixed seed among pages 0001-0030, whose references the dataset card describes as drafted by a vision-language
model and then corrected by hand (pages 0031-0150: model-drafted, re-read by Gemini, checked by a human). Only the chosen row of data.csv
is kept; no other reference is printed or written. The photograph is turned upright with its EXIF orientation (Pillow ImageOps.exif_transpose),
saved at full resolution for the crops (PNG), and resized to a longer side of 1280 px with cv2.INTER_AREA for the detector (as linedet.det_prep
does for School Notebooks pages, JPEG quality 95). True lines = the reference's lines (line breaks of the page), white space collapsed,
empty lines dropped. The page has no line boxes.
usage: showcase_kzb_prep.py --root DIR --out DIR [--skip N]
"""
import argparse
import csv
import json
import os
import sys
import unicodedata
import cv2
import numpy as np
from PIL import Image, ImageOps
csv.field_size_limit(10 ** 9)
ap = argparse.ArgumentParser()
ap.add_argument("--root", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--skip", type=int, default=0, help="take the (skip+1)-th page of the seeded order (privacy fallback)")
a = ap.parse_args()
sub = os.path.join(a.root, "real_handwritten_data")
cands = ["images/%04d.jpg" % i for i in range(1, 31)]
rng = np.random.default_rng(20261125)
order = [cands[i] for i in rng.permutation(len(cands))]
want = order[a.skip]
row = None
with open(os.path.join(sub, "data.csv"), encoding="utf-8", newline="") as f:
for r in csv.DictReader(f):
if r["image_path"] == want:
row = r
break
assert row is not None, want
os.makedirs(a.out, exist_ok=True)
pid = "kzb_hw_" + os.path.basename(want)[:-4]
im = ImageOps.exif_transpose(Image.open(os.path.join(sub, want))).convert("RGB")
full = os.path.join(a.out, pid + "_full.png")
im.save(full)
w, h = im.size
s = 1280.0 / max(w, h)
nw, nh = int(round(w * s)), int(round(h * s))
arr = cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR)
small = cv2.resize(arr, (nw, nh), interpolation=cv2.INTER_AREA)
det = os.path.join(a.out, pid + ".jpg")
cv2.imwrite(det, small, [cv2.IMWRITE_JPEG_QUALITY, 95])
ref = [" ".join(unicodedata.normalize("NFC", ln).split()) for ln in row["text"].split("\n")]
ref = [x for x in ref if x]
cols = ["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note", "reading_image"]
with open(os.path.join(a.out, "pages_kzb.tsv"), "w", encoding="utf-8") as f:
f.write("\t".join(cols) + "\n")
f.write("\t".join([pid, det, str(nw), str(nh), "%.6f" % s, "0", "[]", "[]", "[]", json.dumps(ref, ensure_ascii=False),
"references model-drafted, corrected by hand (dataset card, pages 0001-0030)", full]) + "\n")
sel = dict(seed=20261125, handwritten=[], typed=[], real=[dict(id=pid, lang="kk", kind="kz_benchmark_handwritten_photo",
source="Kazakh Real-Document OCR Benchmark, handwritten subset, " + want,
note="references model-drafted, corrected by hand (dataset card)")])
json.dump(sel, open(os.path.join(a.out, "selection_kzb.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(dict(id=pid, image_path=want, seed_order_position=a.skip, photo_size=[w, h], detector_size=[nw, nh], scale=s, n_ref_lines=len(ref),
ref_chars=sum(len(x) for x in ref), exif_transposed=True),
open(os.path.join(a.out, "kzb_page.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(pid, want, (w, h), (nw, nh), len(ref), flush=True)