File size: 11,480 Bytes
1a2bc7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Corner model for the Voltorb reader: same network as public/voltorb-board.json (photo letterboxed to 128x128 RGB in,
# four 32x32 corner heatmaps out, soft-argmax), trained on every upload with corners: tests/voltorb/train/corners.json plus the
# boards outlined in the board annotator (tests/voltorb/boards.json), any game version, plus synthetic photos made from them.
# 15% are held out to measure corner error, in native DS px, for this model and the live one.
# Usage: corner.py <workdir> [steps] → <workdir>/board.json, <workdir>/board-score.json (held-out error, live vs new)
import base64, json, math, random, sys
import numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from PIL import Image, ImageEnhance, ImageFilter, ImageOps
import os
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')); D = ROOT + '/tests/voltorb'
W = sys.argv[1] if len(sys.argv) > 1 else D + '/train'  # writes board.json (new weights) and board-score.json here
R, HM = 128, 32
NATIVE = np.array([[8, 6], [194, 6], [194, 192], [8, 192]], float)
random.seed(0); np.random.seed(0); torch.manual_seed(0)

# one model, all boards: the reader's earlier exact corners plus every board outlined in the annotator (any game version)
lab = json.load(open(D + '/train/corners.json')); ann = json.load(open(D + '/boards.json'))
for k, b in ann.items():
    if 'corners' in b: lab[k] = {'w': b['w'], 'h': b['h'], 'corners': b['corners']}
onDisk = {f.split('-', 1)[1]: f for f in os.listdir(D) if f.startswith(('ok-', 'fail-'))}
group = lambda k: ann[k]['layout'] if k in ann and ann[k]['layout'] != 'DS' else 'DS photo' if k.lower().endswith(('.jpg', '.jpeg')) else 'DS screenshot'
keys = sorted(k for k in lab if k in onDisk)
random.shuffle(keys); test = set(keys[:len(keys) * 15 // 100])
def load(k):
    im = ImageOps.exif_transpose(Image.open(f'{D}/{onDisk[k]}')).convert('RGB')
    w, h = lab[k]['w'], lab[k]['h']
    if im.size != (w, h): im = im.resize((w, h))
    m = 640 / max(w, h)  # the network sees at most 128 px of the board; 800 px keeps training fast
    if m < 1: im = im.resize((round(w * m), round(h * m))); return im, np.array(lab[k]['corners']) * m
    return im, np.array(lab[k]['corners'])
train = [load(k) for k in keys if k not in test]; held = [(k, *load(k)) for k in sorted(test)]
print(len(train), 'training images,', len(held), 'held out', flush=True)

def homography(src, dst):
    A = []
    for (x, y), (u, v) in zip(src, dst): A += [[x, y, 1, 0, 0, 0, -u * x, -u * y, -u], [0, 0, 0, x, y, 1, -v * x, -v * y, -v]]
    return np.linalg.svd(np.array(A, float))[2][-1].reshape(3, 3)
# flattened screens (768x576, native x3) from the labelled photos, for synthetic photos
def flat_of(im, c):
    H = homography(NATIVE * 3, c); H /= H[2, 2]  # flat px -> image px
    return im.transform((768, 576), Image.PERSPECTIVE, H.ravel()[:8], Image.BILINEAR)
flats = [flat_of(im, c) for im, c in random.sample(train, min(150, len(train)))]

def photo_look(img):
    img = ImageEnhance.Brightness(img).enhance(random.uniform(0.35, 1.4))
    img = ImageEnhance.Contrast(img).enhance(random.uniform(0.5, 1.3))
    img = ImageEnhance.Color(img).enhance(random.uniform(0.5, 1.4))
    if random.random() < 0.6: img = img.filter(ImageFilter.GaussianBlur(random.uniform(0.3, 2.0)))
    a = np.asarray(img, np.float32)
    if random.random() < 0.5:  # glare
        yy, xx = np.mgrid[0:a.shape[0], 0:a.shape[1]]; cx, cy, r = random.uniform(0, a.shape[1]), random.uniform(0, a.shape[0]), random.uniform(10, 60)
        a += random.uniform(40, 160) * np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * r * r))[..., None]
    a += np.random.normal(0, random.uniform(0, 12), a.shape); a *= np.array([random.uniform(0.85, 1.15) for _ in range(3)])
    return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))

def square(im, c, cx, cy, side, ang=0.0):
    # a square crop of side `side` centred at (cx, cy), turned by ang degrees, black outside the photo; corners in 0..1
    big = Image.new('RGB', (round(side), round(side)))
    t = math.radians(ang); cs, sn = math.cos(t), math.sin(t)
    # output (u, v) -> input: centre + rot(u - side/2, v - side/2)
    a, b, d, e = cs, -sn, sn, cs
    coeffs = (a, b, cx - a * side / 2 - b * side / 2, d, e, cy - d * side / 2 - e * side / 2)
    out = im.transform((round(side), round(side)), Image.AFFINE, coeffs, Image.BILINEAR, fillcolor=(0, 0, 0)).resize((R, R), Image.BILINEAR)
    rel = c - [cx, cy]; p = np.c_[rel[:, 0] * cs + rel[:, 1] * sn, -rel[:, 0] * sn + rel[:, 1] * cs] + side / 2
    return out, p / side

def letterbox(im, c):  # what the reader's first look sees
    w, h = im.size; s = max(w, h); return square(im, c, w / 2, h / 2, s)
def from_real():
    im, c = random.choice(train)
    if random.random() < 0.4: x, p = letterbox(im, c)
    else:  # the reader's second look: a close crop around the board, a bit off-centre and turned
        bx0, by0, bx1, by1 = c[:, 0].min(), c[:, 1].min(), c[:, 0].max(), c[:, 1].max(); bs = max(bx1 - bx0, by1 - by0)
        x, p = square(im, c, (bx0 + bx1) / 2 + random.uniform(-.2, .2) * bs, (by0 + by1) / 2 + random.uniform(-.2, .2) * bs, bs * random.uniform(1.15, 2.2), random.uniform(-15, 15))
    return photo_look(x), p
def synthetic():
    flat = random.choice(flats); W = R * 2
    scale = random.uniform(0.45, 1.05); cx, cy = random.uniform(0.3, 0.7) * W, random.uniform(0.3, 0.7) * W
    ang = random.uniform(-0.35, 0.35); hw, hh = scale * W / 2, scale * W / 2 * 0.75; quad = []
    for sx, sy in [(-1, -1), (1, -1), (1, 1), (-1, 1)]:
        x, y = sx * hw * random.uniform(0.8, 1.2), sy * hh * random.uniform(0.8, 1.2)
        quad.append((cx + x * math.cos(ang) - y * math.sin(ang), cy + x * math.sin(ang) + y * math.cos(ang)))
    Hm = homography([(0, 0), (768, 0), (768, 576), (0, 576)], quad); Hinv = np.linalg.inv(Hm); Hinv /= Hinv[2, 2]
    im, _ = random.choice(train); w, h = im.size; s = random.randint(min(w, h) // 4, min(w, h) // 2); x0, y0 = random.randint(0, w - s), random.randint(0, h - s)
    canvas = im.crop((x0, y0, x0 + s, y0 + s)).resize((W, W))
    mask = Image.new('L', (768, 576), 255).transform((W, W), Image.PERSPECTIVE, Hinv.ravel()[:8], Image.BILINEAR)
    canvas = Image.composite(Image.new('RGB', (W, W), tuple(random.randint(0, 70) for _ in range(3))), canvas, mask.filter(ImageFilter.MaxFilter(9)))
    canvas = Image.composite(flat.transform((W, W), Image.PERSPECTIVE, Hinv.ravel()[:8], Image.BILINEAR), canvas, mask)
    c = np.c_[NATIVE * 3, np.ones(4)] @ Hm.T; c = c[:, :2] / c[:, 2:]
    return photo_look(canvas).resize((R, R)), c / W
def sample():
    x, c = from_real() if random.random() < 0.6 else synthetic()
    return np.asarray(x, np.float32).transpose(2, 0, 1) / 255.0, c

class Net(nn.Module):
    def __init__(s):
        super().__init__()
        s.c1 = nn.Conv2d(3, 16, 3, 2, 1); s.c2 = nn.Conv2d(16, 32, 3, 2, 1); s.c3 = nn.Conv2d(32, 64, 3, 2, 1); s.c4 = nn.Conv2d(64, 64, 3, 1, 2, dilation=2)
        s.u = nn.Conv2d(96, 32, 3, 1, 1); s.h = nn.Conv2d(32, 4, 1)
    def forward(s, x):
        a = F.relu(s.c1(x)); b = F.relu(s.c2(a)); c = F.relu(s.c3(b)); c = F.relu(s.c4(c))
        u = F.interpolate(c, scale_factor=2, mode='nearest'); u = F.relu(s.u(torch.cat([u, b], 1)))
        return s.h(u)
def soft_argmax(logits):
    p = F.softmax(logits.flatten(2), -1).view_as(logits); g = (torch.arange(HM, dtype=torch.float32, device=logits.device) + 0.5) / HM
    return torch.stack([(p.sum(2) * g).sum(-1), (p.sum(3) * g).sum(-1)], -1)

# held-out error the way the reader looks: whole photo letterboxed, then a close crop around the first guess.
# Error per corner in native screen px (the board is 186 native px wide; a digit is 6 px wide)
def evaluate(m):
    m.eval(); errs = []; groups = []
    with torch.no_grad():
        for k, im, c in held:
            run = lambda x: soft_argmax(m(torch.tensor(np.asarray(x, np.float32).transpose(2, 0, 1)[None] / 255.0)))[0].numpy()
            w, h = im.size; s = max(w, h); x, _ = letterbox(im, c); q = run(x) * s - [(s - w) / 2, (s - h) / 2]
            cx, cy = (q[:, 0].min() + q[:, 0].max()) / 2, (q[:, 1].min() + q[:, 1].max()) / 2; side = max(np.ptp(q[:, 0]), np.ptp(q[:, 1])) * 1.6
            x, _ = square(im, c, cx, cy, side); q = run(x) * side - side / 2 + [cx, cy]
            px = np.linalg.norm(c[1] - c[0]) / 186  # image px per native px
            errs.append(np.linalg.norm(q - c, axis=1).mean() / px); groups.append(group(k))
    m.train(); e = np.array(errs); g = np.array(groups)
    per = '; '.join(f'{n} ({(g == n).sum()}): mean {e[g == n].mean():.1f}, within 6 px {np.mean(e[g == n] < 6) * 100:.0f}%' for n in sorted(set(groups)))
    return {'mean': float(e.mean()), 'median': float(np.median(e)), 'within6': float(np.mean(e < 6)), 'n': len(e)}, per + f'\n  all: mean {e.mean():.1f} native px, median {np.median(e):.1f}, within 3 px {np.mean(e < 3) * 100:.0f}%, within 6 px {np.mean(e < 6) * 100:.0f}%'

if __name__ == '__main__':
    live = Net(); js = json.load(open(ROOT + '/public/voltorb-board.json'))
    live.load_state_dict({k: torch.tensor(np.frombuffer(base64.b64decode(b), np.int8).astype(np.float32) * sc).view_as(v) for (k, v), (sc, b) in zip(live.state_dict().items(), [js[k] for k in live.state_dict()])})
    ls, lt = evaluate(live); print('live model, held out:', lt, flush=True)
    # training images are made on every core but two (forked workers share the loaded photos), the network trains on MPS
    import time
    class Stream(torch.utils.data.IterableDataset):
        def __iter__(s):
            w = torch.utils.data.get_worker_info(); seed = (w.id if w else 0) * 7919 + int(time.time())
            random.seed(seed); np.random.seed(seed % 2 ** 32)
            while True:
                x, c = sample(); yield torch.from_numpy(np.ascontiguousarray(x, np.float32)), torch.tensor(c, dtype=torch.float32)
    batches = iter(torch.utils.data.DataLoader(Stream(), batch_size=32, num_workers=max(1, (os.cpu_count() or 4) - 2), multiprocessing_context='fork', prefetch_factor=4))
    dev = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
    m = Net(); m.load_state_dict(live.state_dict()); m = m.to(dev)  # start from the live model: more boards refine it instead of starting over
    opt = torch.optim.Adam(m.parameters(), 2e-3); steps = int(sys.argv[2]) if len(sys.argv) > 2 else 24000  # 6000 undertrained once there were ~6k boards: 96% → 98% within 6 px, 48% → 92% within 3
    for it in range(steps):
        xs, cs = next(batches)
        loss = (soft_argmax(m(xs.to(dev))) - cs.to(dev)).abs().mean()
        opt.zero_grad(); loss.backward(); opt.step()
        if it == 0: t0 = time.time()
        if it % 500 == 0: print(it, f'{loss.item() * R:.2f} px of 128, {(time.time() - t0) / max(it, 1):.2f} s/step', flush=True)
        if it == int(steps * 0.7): [g.update(lr=5e-4) for g in opt.param_groups]
    m = m.cpu()
    # same format as public/voltorb-board.json: per tensor [scale, base64 int8]
    out = {}
    for k, v in m.state_dict().items():
        a = v.numpy().ravel(); sc = float(np.abs(a).max() / 127) or 1.0
        out[k] = [float(f'{sc:.6g}'), base64.b64encode(np.round(a / sc).clip(-127, 127).astype(np.int8).tobytes()).decode()]
    json.dump(out, open(W + '/board.json', 'w'))
    ns, nt = evaluate(m); print('new model, held out:', nt, flush=True)
    json.dump({'live': ls, 'new': ns}, open(W + '/board-score.json', 'w'))