"""J2 second follow-up controls: build the image sets. A. Contrast: the first 300 crops of screen_set_v1.tsv (file order). List "stored" = the crops as stored (names unchanged, images are read from the KOHTD folder). List "stretch" = the same crops after contrast_stretch (own PNG copies; PNG so no new JPEG loss). The KOHTD images stay on the cluster. B. Handwriting fonts, no real ink: the same 200 Kazakh and Kyrgyz control words (the 40 px rows of control_words.tsv) rendered at height 40 px in Caveat and Bad Script (OFL), black on white. A word with a letter the font lacks is left out for that font and listed. usage: make_controls2_set.py SCREEN_SET KOHTD_IMG_DIR CONTROL_WORDS_TSV CONTRAST_STRETCH_PY FONT_CAVEAT FONT_BADSCRIPT OUT_DIR """ import importlib.util import os import sys import numpy as np from fontTools.ttLib import TTFont from PIL import Image, ImageDraw, ImageFont screen_set, kohtd_dir, words_tsv, cs_py, font_caveat, font_bad, out_dir = sys.argv[1:8] assert "screen_set_v1.tsv" in screen_set spec = importlib.util.spec_from_file_location("cs", cs_py) cs = importlib.util.module_from_spec(spec) spec.loader.exec_module(cs) os.makedirs(os.path.join(out_dir, "img_stretch"), exist_ok=True) os.makedirs(os.path.join(out_dir, "img_fonts"), exist_ok=True) # ---- A: contrast rows = [] with open(screen_set, encoding="utf-8", newline="") as f: f.readline() for line in f: rows.append(line.rstrip("\n").split("\t")) if len(rows) == 300: break assert len(rows) == 300 with open(os.path.join(out_dir, "contrast_stored_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f: f.write("crop_file\tform_id\tlabel\n") for c, form, lab in rows: f.write(f"{c}\t{form}\t{lab}\n") p1b, p99b, p1a, p99a = [], [], [], [] with open(os.path.join(out_dir, "contrast_stretch_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f: f.write("crop_file\tform_id\tlabel\n") for c, form, lab in rows: im = Image.open(os.path.join(kohtd_dir, c)).convert("RGB") out = cs.contrast_stretch(im) assert out.size == im.size and out.mode == "RGB" g0 = np.asarray(im.convert("L"), dtype=float) g1 = np.asarray(out.convert("L"), dtype=float) p1b.append(np.percentile(g0, 1)) p99b.append(np.percentile(g0, 99)) p1a.append(np.percentile(g1, 1)) p99a.append(np.percentile(g1, 99)) name = os.path.splitext(c)[0] + ".png" out.save(os.path.join(out_dir, "img_stretch", name)) f.write(f"{name}\t{form}\t{lab}\n") print("A: 300 crops; grey 1st/99th percentile mean before %.1f / %.1f, after %.1f / %.1f" % ( np.mean(p1b), np.mean(p99b), np.mean(p1a), np.mean(p99a))) print("A: crops whose 1st percentile was already below 30: %d; whose 99th was above 225: %d" % ( sum(1 for v in p1b if v < 30), sum(1 for v in p99b if v > 225))) # ---- B: handwriting fonts words = [] with open(words_tsv, encoding="utf-8", newline="") as f: f.readline() for line in f: crop, lang, h, word, sid = line.rstrip("\n").split("\t") if h == "40": words.append((crop, lang, word)) assert len(words) == 200 H = 40 FONTS = {"caveat": font_caveat, "badscript": font_bad} def render(word, path): size = int(round(0.62 * H)) font = ImageFont.truetype(path, size) l, t, r, b = font.getbbox(word) while (b - t) > H - 4 and size > 8: size -= 1 font = ImageFont.truetype(path, size) l, t, r, b = font.getbbox(word) pad = int(round(0.25 * H)) im = Image.new("RGB", ((r - l) + 2 * pad, H), (255, 255, 255)) ImageDraw.Draw(im).text((pad - l, (H - (b - t)) // 2 - t), word, font=font, fill=(0, 0, 0)) return im, size n = 0 with open(os.path.join(out_dir, "fonts_screen_set_v1.tsv"), "w", encoding="utf-8", newline="") as f: f.write("crop_file\tform_id\tlabel\n") for fname, path in FONTS.items(): cmap = TTFont(path).getBestCmap() left_out, widths = [], [] for crop, lang, word in words: if any(ord(ch) not in cmap for ch in word): left_out.append(word) continue im, size = render(word, path) name = f"{fname}_{os.path.splitext(crop)[0]}.png" im.save(os.path.join(out_dir, "img_fonts", name)) f.write(f"{name}\t{n}\t{word}\n") n += 1 widths.append(im.width) print(f"B: {fname}: rendered {len(widths)} of 200 words, left out for missing glyphs: {len(left_out)} {left_out[:10]}; width min/mean/max " f"{min(widths)}/{np.mean(widths):.0f}/{max(widths)}") print("B: total images", n)