turkic-ocr-code / scripts /j2 /make_control_set.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
3.66 kB
"""J2 positive control: 200 printed words (100 Kazakh + 100 Kyrgyz, Cyrillic) rendered in PT Sans (OFL 1.1), black on white, at
heights 40 px and 80 px = 400 images. Words come from the DISPLAY sentence banks that pagesynth uses.
(There is no Russian bank in pagesynth_text; the plan allows Kazakh + Kyrgyz then.)
Word choice: whitespace tokens of the display sentences with punctuation stripped from both ends; keep tokens that are
all letters, 3 to 12 characters, every letter in the Cyrillic block, every glyph in the font; ascending sha256 of
"J2-control-v1:<lang>:<word>"; first 100 per language. Writes the list in the screen-set format
(positive_control_screen_set_v1.tsv: crop_file, form_id, label) and the images.
usage: make_control_set.py BANK_KK BANK_KY FONT_TTF OUT_DIR
"""
import hashlib
import os
import sys
import unicodedata
from fontTools.ttLib import TTFont
from PIL import Image, ImageDraw, ImageFont
bank = {"kk": sys.argv[1], "ky": sys.argv[2]}
font_path, out_dir = sys.argv[3], sys.argv[4]
os.makedirs(os.path.join(out_dir, "img"), exist_ok=True)
cmap = TTFont(font_path).getBestCmap()
STRIP = "\"'«»„“”‘’.,;:!?()[]{}-–—…/\\"
def ok_word(w):
if not (3 <= len(w) <= 12):
return False
for ch in w:
if not ch.isalpha() or not ("Ѐ" <= ch <= "ӿ") or ord(ch) not in cmap:
return False
return True
words = {}
for lang, path in bank.items():
seen = {}
with open(path, encoding="utf-8") as f:
for line in f:
parts = line.rstrip("\n").split("\t")
if len(parts) < 2:
continue
sid, sent = parts[0], parts[1]
for tok in sent.split():
w = unicodedata.normalize("NFC", tok.strip(STRIP))
if ok_word(w) and w not in seen:
seen[w] = sid
ranked = sorted(seen, key=lambda w: hashlib.sha256(f"J2-control-v1:{lang}:{w}".encode("utf-8")).hexdigest())
words[lang] = [(w, seen[w]) for w in ranked[:100]]
print(lang, "candidate words", len(seen), "chosen", len(words[lang]))
def render(word, H):
size = int(round(0.62 * H))
font = ImageFont.truetype(font_path, size)
asc, desc = font.getmetrics()
l, t, r, b = font.getbbox(word)
pad = int(round(0.25 * H))
W = (r - l) + 2 * pad
im = Image.new("RGB", (W, H), (255, 255, 255))
d = ImageDraw.Draw(im)
y = (H - (asc + desc)) // 2
d.text((pad - l, y), word, font=font, fill=(0, 0, 0))
return im
rows, sizes = [], []
idx = 0
for H in (40, 80):
for lang in ("kk", "ky"):
for i, (w, sid) in enumerate(words[lang], 1):
name = f"{lang}_h{H}_{i:03d}.png"
im = render(w, H)
assert im.height == H and im.mode == "RGB"
im.save(os.path.join(out_dir, "img", name))
rows.append((name, str(idx), w, lang, H, sid))
sizes.append((H, im.width))
idx += 1
with open(os.path.join(out_dir, "positive_control_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f:
f.write("crop_file\tform_id\tlabel\n")
for name, i, w, lang, H, sid in rows:
f.write(f"{name}\t{i}\t{w}\n")
with open(os.path.join(out_dir, "control_words.tsv"), "w", encoding="utf-8", newline="") as f:
f.write("crop_file\tlang\theight\tword\tsource_sentence_id\n")
for name, i, w, lang, H, sid in rows:
f.write(f"{name}\t{lang}\t{H}\t{w}\t{sid}\n")
for H in (40, 80):
ws = [w for h, w in sizes if h == H]
print("height", H, "images", len(ws), "width min/mean/max", min(ws), sum(ws) / len(ws), max(ws))
print("font", os.path.basename(font_path), "images", len(rows))