File size: 8,537 Bytes
24e04bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""Generate the pilot training set.



Clean backgrounds only -- the pilot answers "can SD1.5 + a TE LoRA learn

Devanagari glyph shapes at all", so scene compositing is deliberately out of

scope (see PLAN.md §4b: that decision is deferred until the pilot reports).



Hard invariants, asserted rather than assumed:

  * font em size >= MIN_EM  (the measured VAE floor -- FINDINGS.md §2)

  * text fits the canvas with margin

  * caption fits CLIP's 77-token window, template included

  * fg/bg luminance contrast is real

"""
from __future__ import annotations

import argparse
import json
import pathlib
import random
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))

import numpy as np
from PIL import Image, ImageFilter

from data.captions import make_caption
from render.shaper import load_face, render_line

RES = 512
MIN_EM = 32          # measured VAE floor; below this diacritics are destroyed
MAX_EM = 120
MARGIN = 24
MAX_TOKENS = 77


def load_words(path: pathlib.Path) -> list[str]:
    out = []
    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line and not line.startswith("#"):
            out.append(line)
    return out


def luminance(rgb) -> float:
    r, g, b = [c / 255 for c in rgb]
    return 0.2126 * r + 0.7152 * g + 0.0722 * b


def pick_colors(rng: random.Random) -> tuple[tuple, tuple]:
    """Foreground/background with guaranteed contrast.



    Low-contrast text would be destroyed by the VAE just as surely as small

    text, so this is enforced, not sampled and hoped for.

    """
    for _ in range(64):
        if rng.random() < 0.45:      # dark on light: the common signage case
            bg = tuple(rng.randint(190, 255) for _ in range(3))
            fg = tuple(rng.randint(0, 70) for _ in range(3))
        elif rng.random() < 0.5:     # light on dark
            bg = tuple(rng.randint(0, 80) for _ in range(3))
            fg = tuple(rng.randint(185, 255) for _ in range(3))
        else:                        # saturated colour pair
            bg = tuple(rng.randint(0, 255) for _ in range(3))
            fg = tuple(rng.randint(0, 255) for _ in range(3))
        if abs(luminance(fg) - luminance(bg)) >= 0.35:
            return fg, bg
    return (0, 0, 0), (255, 255, 255)


def make_background(rng: random.Random, bg: tuple) -> Image.Image:
    kind = rng.random()
    if kind < 0.55:
        return Image.new("RGB", (RES, RES), bg)
    if kind < 0.85:
        # linear gradient -- mild, so it never competes with the glyphs
        other = tuple(max(0, min(255, c + rng.randint(-45, 45))) for c in bg)
        ramp = np.linspace(0.0, 1.0, RES, dtype=np.float32)
        # broadcast the ramp across the full canvas, vertically or horizontally
        a = (np.tile(ramp[:, None], (1, RES)) if rng.random() < 0.5
             else np.tile(ramp[None, :], (RES, 1)))[..., None]
        arr = np.array(bg, dtype=np.float32) * (1 - a) + np.array(other, dtype=np.float32) * a
        assert arr.shape == (RES, RES, 3), f"bad gradient shape {arr.shape}"
        return Image.fromarray(arr.astype(np.uint8))
    # faint noise/texture
    base = np.array(Image.new("RGB", (RES, RES), bg), dtype=np.float32)
    base += np.random.normal(0, 6, base.shape)
    img = Image.fromarray(np.clip(base, 0, 255).astype(np.uint8))
    return img.filter(ImageFilter.GaussianBlur(0.6))


def render_sample(word: str, fonts: list[str], rng: random.Random):
    """Returns (image, mask, meta) or None if no valid layout was found."""
    avail = RES - 2 * MARGIN
    for _ in range(12):
        font = rng.choice(fonts)
        # Measure once at a reference size, then solve for the largest em that
        # fits. Sampling em blindly would systematically shrink long words --
        # word length would end up correlated with text size in the dataset.
        try:
            ref = load_face(f"fonts/{font}", 64)
            rm, _ = render_line(ref, word, pad=6)
        except Exception:
            continue
        fit = int(64 * min(avail / rm.width, avail / rm.height))
        hi = min(MAX_EM, fit)
        if hi < MIN_EM:
            continue                      # cannot satisfy the VAE floor here
        em = rng.randint(MIN_EM, hi)
        try:
            face = load_face(f"fonts/{font}", em)
            mask, m = render_line(face, word, pad=6)
        except Exception:
            continue
        if mask.width > avail or mask.height > avail:
            continue                      # rounding slop at the boundary
        assert em >= MIN_EM, "VAE floor violated"

        fg, bg = pick_colors(rng)
        img = make_background(rng, bg)
        x = rng.randint(MARGIN, RES - MARGIN - mask.width)
        y = rng.randint(MARGIN, RES - MARGIN - mask.height)
        img.paste(fg, (x, y), mask)

        full_mask = Image.new("L", (RES, RES), 0)
        full_mask.paste(mask, (x, y))
        assert img.size == (RES, RES), f"bad canvas {img.size}"
        return img, full_mask, {
            "font": font, "em": em, "x": x, "y": y,
            "w": mask.width, "h": mask.height, "glyphs": m["n_glyphs"],
        }
    return None


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=4000)
    ap.add_argument("--out", default="data/pilot")
    ap.add_argument("--holdout", type=int, default=20, help="words reserved for eval")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--masks", action="store_true", help="also write glyph masks")
    args = ap.parse_args()

    rng = random.Random(args.seed)
    np.random.seed(args.seed)

    from transformers import CLIPTokenizer
    # local copy when present (offline), else pull SD1.5's own tokenizer
    try:
        tok = CLIPTokenizer.from_pretrained("models/clip")
    except Exception:
        tok = CLIPTokenizer.from_pretrained(
            "stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="tokenizer")

    words = load_words(pathlib.Path("corpus/pilot_words.txt"))
    fonts = [l.strip() for l in pathlib.Path("configs/fonts_ok.txt")
             .read_text(encoding="utf-8").splitlines() if l.strip()]
    if not fonts:
        print("no usable fonts -- run src/diag/font_audit.py"); return 1

    # Split by WORD before anything else, so no held-out word appears in training
    # in any form. Leakage here would make the eval meaningless.
    shuffled = words[:]
    rng.shuffle(shuffled)
    holdout = sorted(shuffled[: args.holdout])
    train = sorted(shuffled[args.holdout:])

    out = pathlib.Path(args.out)
    (out / "images").mkdir(parents=True, exist_ok=True)
    if args.masks:
        (out / "masks").mkdir(parents=True, exist_ok=True)

    recs, skipped, over = [], 0, 0
    for i in range(args.n):
        word = rng.choice(train)
        got = render_sample(word, fonts, rng)
        if got is None:
            skipped += 1
            continue
        img, mask, meta = got

        cap = make_caption(word, rng)
        n_tok = len(tok(cap)["input_ids"])
        if n_tok > MAX_TOKENS:          # exact check, template included
            over += 1
            continue

        name = f"{i:06d}"
        img.save(out / "images" / f"{name}.jpg", quality=95)
        if args.masks:
            mask.save(out / "masks" / f"{name}.png")
        recs.append({"file": f"images/{name}.jpg", "text": word,
                     "caption": cap, "tokens": n_tok, **meta})

    with (out / "metadata.jsonl").open("w", encoding="utf-8") as fh:
        for r in recs:
            fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    (out / "train_words.txt").write_text("\n".join(train) + "\n", encoding="utf-8")
    (out / "holdout_words.txt").write_text("\n".join(holdout) + "\n", encoding="utf-8")

    ems = [r["em"] for r in recs]
    print(f"wrote {len(recs)} samples to {out}")
    print(f"  skipped(layout)={skipped}  skipped(tokens)={over}")
    print(f"  train words={len(train)}  holdout={len(holdout)}")
    print(f"  em size: min={min(ems)} max={max(ems)} mean={sum(ems)/len(ems):.1f}")
    print(f"  tokens : max={max(r['tokens'] for r in recs)}")
    print(f"  fonts used: {len({r['font'] for r in recs})}/{len(fonts)}")
    print(f"\nholdout: {' '.join(holdout)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())