Buckets:
| """Рендерим синтетические строки на диск один раз, всеми ядрами. | |
| Дальше обучение не упирается в CPU и можно гонять несколько архитектур подряд. | |
| """ | |
| import io, json, os, random, sys, time | |
| import numpy as np | |
| from multiprocessing import Pool | |
| from PIL import Image, ImageDraw, ImageFont | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from synth import degrade | |
| from PIL import ImageFilter, ImageDraw | |
| def screen_render(im, pyr, rng): | |
| """Экранный текст, а не печать: низкий контраст, сглаживание, фон с градиентом. | |
| В синтетике были только тёмные чернила на бумаге — скриншоты и слайды | |
| модель не видела вовсе. | |
| """ | |
| a = np.asarray(im).astype(np.float32) | |
| h, w = a.shape | |
| # текст не чёрный, а средне-серый; фон не белый | |
| ink = pyr.uniform(0.22, 0.52) | |
| paper = pyr.uniform(0.80, 0.97) | |
| a = a / 255.0 | |
| a = ink + a * (paper - ink) | |
| # мягкий градиент/текстура фона | |
| g = np.linspace(0, 1, w)[None, :] * pyr.uniform(-0.06, 0.06) \ | |
| + np.linspace(0, 1, h)[:, None] * pyr.uniform(-0.05, 0.05) | |
| a = np.clip(a + g, 0, 1) | |
| im = Image.fromarray((a * 255).astype(np.uint8)) | |
| # субпиксельное сглаживание даёт лёгкое размытие по горизонтали | |
| if pyr.random() < 0.7: | |
| im = im.filter(ImageFilter.GaussianBlur(pyr.uniform(0.3, 0.9))) | |
| return im | |
| def legible(im, min_sharp=6.0, min_contrast=45.0): | |
| """Осталось ли на строке что распознавать. | |
| degrade имеет свою защиту от пересветки, но shakal её обходит: цепочка | |
| пересжатий с апскейлом легко стирает текст полностью, а учить на пустых | |
| картинках — только шуметь. | |
| """ | |
| a = np.asarray(im.convert("L"), dtype=np.float32) | |
| if a.size == 0: return False | |
| sharp = float(np.abs(np.diff(a, axis=1)).mean()) | |
| contrast = float(np.percentile(a, 92) - np.percentile(a, 4)) | |
| return sharp >= min_sharp and contrast >= min_contrast | |
| def shakal(im, pyr): | |
| """«Шакалирование»: пересохранения, апскейл с потерянных пикселей.""" | |
| w, h = im.size | |
| if pyr.random() < 0.75: # потеря разрешения и обратный апскейл | |
| k = pyr.uniform(0.28, 0.62) | |
| im = im.resize((max(8, int(w * k)), max(6, int(h * k))), Image.BILINEAR) | |
| im = im.resize((w, h), pyr.choice([Image.BILINEAR, Image.BICUBIC, Image.NEAREST])) | |
| for _ in range(pyr.randint(1, 3)): # цепочка пересжатий | |
| b = io.BytesIO() | |
| im.convert("L").save(b, "JPEG", quality=pyr.randint(18, 55)) | |
| b.seek(0); im = Image.open(b).convert("L") | |
| return im | |
| def underline(draw, x0, y0, x1, y1, pyr, fill): | |
| """Подчёркивание — в заголовках слипается с буквами и ломает распознавание.""" | |
| off = int((y1 - y0) * pyr.uniform(0.02, 0.16)) | |
| th = max(1, int((y1 - y0) * pyr.uniform(0.03, 0.09))) | |
| yy = y1 + off | |
| draw.rectangle([x0, yy, x1, yy + th], fill=fill) | |
| def draw_tracked(draw, xy, text, font, fill, track): | |
| """Рендер с изменённым межбуквенным интервалом (трекинг). | |
| Отдельная ось от ширины: форма глифов сохраняется, меняются промежутки.""" | |
| x, y = xy | |
| for ch in text: | |
| draw.text((x, y), ch, font=font, fill=fill) | |
| x += draw.textlength(ch, font=font) * track | |
| return x | |
| def typeface_aug(im, pyr): | |
| """Размножаем гарнитуры по осям, по которым они реально различаются: | |
| наклон, ширина, толщина штриха. Применяется ДО деградации, в разрешении рендера.""" | |
| w, h = im.size | |
| # 1) толщина штриха: узкий/жирный вариант той же гарнитуры | |
| r = pyr.random() | |
| if r < 0.22: im = im.filter(ImageFilter.MinFilter(3)) # жирнее | |
| elif r < 0.40: im = im.filter(ImageFilter.MaxFilter(3)) # тоньше | |
| # 2) ширина: узкое/широкое начертание | |
| sx = pyr.uniform(0.80, 1.22) | |
| if abs(sx - 1.0) > 0.02: | |
| im = im.resize((max(8, int(w * sx)), h), Image.BICUBIC); w = im.size[0] | |
| # 3) наклон: имитация курсива/обратного наклона | |
| sh = pyr.uniform(-0.10, 0.28) if pyr.random() < 0.45 else 0.0 | |
| if abs(sh) > 0.01: | |
| dx = int(abs(sh) * h) | |
| im2 = Image.new("L", (w + dx, h), 255) | |
| im2.paste(im, (dx if sh < 0 else 0, 0)) | |
| im = im2.transform(im2.size, Image.AFFINE, (1, -sh, 0 if sh > 0 else dx * 0, 0, 1, 0), | |
| resample=Image.BICUBIC, fillcolor=255) | |
| return im | |
| ROOT = os.path.dirname(os.path.abspath(__file__)) | |
| H = 48 | |
| STYLE = {"bold","italic","light","medium","semibold","extrabold","regular","roman","condensed", | |
| "cond","thin","black","negreta","sc","caption","mono","oblique","book","heavy","demi", | |
| "extralight","ultralight","narrow","expanded"} | |
| DECOR = ("rubik ","press start","tiny5","lobster","oi","yeseva","snell","bradley", | |
| "copperplate","marmelad","gabriela") | |
| def family(n): | |
| t = n.replace("-", " ").split() | |
| while len(t) > 1 and t[-1].lower() in STYLE: t.pop() | |
| return " ".join(t) | |
| G = {} | |
| def init(manifest, corpus, held, out): | |
| allf = json.load(open(manifest)) | |
| for f in allf: f["fam"] = family(f["name"]) | |
| keep = [f for f in allf if f["fam"] not in held] | |
| body = [f for f in keep if not any(d in f["fam"].lower() for d in DECOR)] | |
| decor = [f for f in keep if f not in body] | |
| G["fonts"] = body*9 + decor | |
| G["lines"] = [l for l in open(corpus).read().split("\n") if 25 <= len(l) <= 170] | |
| G["out"] = out | |
| def one(i): | |
| pyr = random.Random(i*7919 + 13); rng = np.random.default_rng(i*7919 + 13) | |
| for _ in range(6): | |
| text = G["lines"][pyr.randrange(len(G["lines"]))] | |
| # --- режим строки --- | |
| # "title" — короткий заголовок: другой регистр, часто подчёркнут и по центру. | |
| # В корпусе заглавные спец-буквы почти не встречаются (Ҕ — 93 раза на 25 млн), | |
| # поэтому регистр добавляем искусственно, иначе модель их не выучит. | |
| mode = pyr.choices(["body", "title", "screen"], weights=[0.62, 0.16, 0.22])[0] | |
| if mode == "title": | |
| words = text.split() | |
| text = " ".join(words[:pyr.randint(1, 5)]) | |
| r = pyr.random() | |
| if r < 0.34: text = text.upper() | |
| elif r < 0.62: text = " ".join(w.capitalize() for w in text.split()) | |
| else: | |
| if len(text) > 72: | |
| cut = pyr.randint(28, 72) | |
| text = text[:cut].rsplit(" ", 1)[0] | |
| text = text.strip() | |
| if not text: continue | |
| f = G["fonts"][pyr.randrange(len(G["fonts"]))] | |
| dom = "news1940" if (mode == "body" and pyr.random() < 0.5) else "book" | |
| size = pyr.randint(26, 52) if mode != "body" else ( | |
| pyr.randint(20, 34) if dom == "news1940" else pyr.randint(26, 46)) | |
| try: ft = ImageFont.truetype(os.path.join(ROOT, f["path"]), size, index=f["idx"]) | |
| except Exception: continue | |
| pad = pyr.randint(4, 14); tmp = Image.new("L", (8, 8), 255) | |
| b = ImageDraw.Draw(tmp).textbbox((0, 0), text, font=ft) | |
| W, Ht = b[2]-b[0]+2*pad, b[3]-b[1]+2*pad | |
| if W < 16 or W > 3000 or Ht < 8: continue | |
| if mode == "title": Ht += int(size * 0.35) # место под подчёркивание | |
| im = Image.new("L", (W, Ht), 255) | |
| d = ImageDraw.Draw(im) | |
| fill = int(rng.integers(0, 50)) | |
| tx, ty = pad-b[0], pad-b[1] | |
| d.text((tx, ty), text, font=ft, fill=fill) | |
| if mode == "title" and pyr.random() < 0.55: | |
| underline(d, tx, ty, tx + (b[2]-b[0]), ty + (b[3]-b[1]), pyr, fill) | |
| if os.environ.get("TYPEFACE_AUG", "1") == "1": | |
| im = typeface_aug(im, pyr) | |
| clean = im.copy() | |
| for attempt in range(4): | |
| im = clean.copy() | |
| hard = attempt < 2 # с третьей попытки — без шакалирования | |
| if mode == "screen": | |
| im = screen_render(im, pyr, rng) | |
| if hard and pyr.random() < 0.75: im = shakal(im, pyr) | |
| th = pyr.uniform(14, 44) | |
| else: | |
| im = degrade(im, dom, rng) | |
| if hard and pyr.random() < 0.18: im = shakal(im, pyr) | |
| th = pyr.uniform(13, 46) if dom == "news1940" else pyr.uniform(20, 50) | |
| if legible(im): break | |
| k = th/im.height | |
| if k < 0.98: | |
| im = im.resize((max(8, int(im.width*k)), max(8, int(im.height*k))), Image.BOX) | |
| if mode != "screen" and pyr.random() < (0.9 if dom == "news1940" else 0.35): | |
| a = np.asarray(im).astype(np.float32) | |
| lo, hi = np.percentile(a, pyr.uniform(2, 14)), np.percentile(a, pyr.uniform(70, 92)) | |
| if hi-lo > 12: | |
| im = Image.fromarray((np.clip((a-lo)/(hi-lo), 0, 1)**pyr.uniform(0.5, 2.0)*255).astype(np.uint8)) | |
| im = im.resize((max(8, int(im.width*H/im.height)), H), Image.BILINEAR) | |
| if im.width > 1400: im = im.crop((0, 0, 1400, H)) | |
| sub = f"{i//5000:04d}" | |
| dd = os.path.join(G["out"], sub); os.makedirs(dd, exist_ok=True) | |
| name = f"{sub}/{i:08d}.jpg" | |
| im.save(os.path.join(G["out"], name), quality=pyr.randint(78, 96)) | |
| return {"f": name, "t": text} | |
| return None | |
| if __name__ == "__main__": | |
| import argparse | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--n", type=int, required=True); ap.add_argument("--out", required=True) | |
| ap.add_argument("--manifest", required=True); ap.add_argument("--corpus", required=True) | |
| ap.add_argument("--held", default=""); ap.add_argument("--procs", type=int, default=96) | |
| a = ap.parse_args() | |
| held = set(json.load(open(a.held))) if a.held else set() | |
| os.makedirs(a.out, exist_ok=True) | |
| t0 = time.time() | |
| with Pool(a.procs, initializer=init, initargs=(a.manifest, a.corpus, held, a.out)) as p: | |
| res = [r for r in p.imap_unordered(one, range(a.n), chunksize=256) if r] | |
| with open(os.path.join(a.out, "index.jsonl"), "w") as fh: | |
| for r in res: fh.write(json.dumps(r, ensure_ascii=False)+"\n") | |
| dt = time.time()-t0 | |
| print(f"{len(res):,} строк за {dt/60:.1f} мин ({len(res)/dt:.0f} строк/с), отложено гарнитур: {len(held)}") | |
Xet Storage Details
- Size:
- 11.2 kB
- Xet hash:
- 0dc8e209320af4047e372973d08cff3fb3daf3317c5f596a2e49c11ded409c27
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.