Team officials wear an accreditation card with a letter; B is usually the head coach. A person whose number is a letter A-F (or "Oficial B") gets samples labelled with it, the review accepts the letter, and the model has a letter head next to the digits (labels 0-99, A-F, illegible). Synthetic data paints cards on lanyards too. Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
254 lines
11 KiB
Python
254 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Trains the shirt-number model from the dataset checked in the app (Números das camisolas).
|
|
|
|
python train.py --dataset jersey-dataset-2026-10-12.json --api https://api.photoreport.pt --out models/jersey-v1
|
|
|
|
The model looks at a crop under a face (chest or shorts) and reads it digit by digit: is there a legible number (or a
|
|
team official's badge letter), what is the tens digit (or none), what is the units digit. Reading digits instead of
|
|
whole numbers means every "20" also teaches the model what a 2 and a 0 look like, so it needs far fewer examples per
|
|
number. Handball officials wear a card on a lanyard with a letter, A to F (B is usually the head coach): that letter
|
|
is read the same way. The exported model still answers one probability per label: 0-99, A-F, "illegible" (the worker
|
|
does not need to know how it reads).
|
|
|
|
It runs on the Mac's GPU (MPS) when there is one, else CUDA, else the CPU. The output folder gets `jersey.onnx`
|
|
(what the worker runs), `labels.json` and `metrics.json` (accuracy on crops kept out of training).
|
|
|
|
A sample in the dataset is {id, label, crop} with crop a signed URL path, or {id, label, file} for a local crop.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import random
|
|
import urllib.request
|
|
from collections import Counter
|
|
from pathlib import Path
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
from PIL import Image
|
|
from torch.utils.data import DataLoader, Dataset
|
|
from torchvision import models, transforms
|
|
|
|
SIZE = 160
|
|
NUMBERS = [str(n) for n in range(100)]
|
|
LETTERS = list("ABCDEF") # handball team officials' badges ("Oficial A".."F")
|
|
LABELS = NUMBERS + LETTERS + ["illegible"]
|
|
MEAN, STD = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
|
|
|
|
|
|
def download(manifest: dict, api: str, cache: Path) -> list[tuple[Path, int, str]]:
|
|
"""Fetches every crop once (signed URLs from the manifest); returns (file, class index, group) triples.
|
|
Crops of the same photo share a group, so the check never sees a photo the model trained on."""
|
|
cache.mkdir(parents=True, exist_ok=True)
|
|
items = []
|
|
for s in manifest["samples"]:
|
|
label = s["label"]
|
|
if label not in LABELS:
|
|
continue # numbers above 99 are too rare to learn
|
|
if "file" in s:
|
|
f = Path(s["file"])
|
|
else:
|
|
f = cache / f"{s['id']}.jpg"
|
|
if not f.exists():
|
|
urllib.request.urlretrieve(api.rstrip("/") + s["crop"], f)
|
|
items.append((f, LABELS.index(label), str(s.get("group") or s.get("photoId") or s["id"])))
|
|
return items
|
|
|
|
|
|
def letterbox(img: Image.Image) -> Image.Image:
|
|
"""Fits the crop into a square without distorting the digits (grey padding)."""
|
|
img = img.convert("RGB")
|
|
img.thumbnail((SIZE, SIZE))
|
|
out = Image.new("RGB", (SIZE, SIZE), (114, 114, 114))
|
|
out.paste(img, ((SIZE - img.width) // 2, (SIZE - img.height) // 2))
|
|
return out
|
|
|
|
|
|
class Crops(Dataset):
|
|
def __init__(self, items, train: bool):
|
|
self.items = items
|
|
aug = [
|
|
transforms.RandomAffine(degrees=10, translate=(0.08, 0.08), scale=(0.85, 1.15), shear=6, fill=114),
|
|
transforms.ColorJitter(0.35, 0.35, 0.35, 0.05),
|
|
transforms.RandomGrayscale(0.1),
|
|
]
|
|
# Never flip horizontally: a mirrored 7 is not a 7.
|
|
self.tf = transforms.Compose([*(aug if train else []), transforms.ToTensor(), transforms.Normalize(MEAN, STD)])
|
|
|
|
def __len__(self):
|
|
return len(self.items)
|
|
|
|
def __getitem__(self, i):
|
|
f, y = self.items[i][:2]
|
|
return self.tf(letterbox(Image.open(f))), y
|
|
|
|
|
|
def device() -> torch.device:
|
|
if torch.backends.mps.is_available():
|
|
return torch.device("mps")
|
|
if torch.cuda.is_available():
|
|
return torch.device("cuda")
|
|
return torch.device("cpu")
|
|
|
|
|
|
ILLEGIBLE = len(LABELS) - 1
|
|
IGNORE = -100
|
|
|
|
|
|
KIND_ILLEGIBLE, KIND_NUMBER, KIND_LETTER = 0, 1, 2
|
|
|
|
|
|
def targets(y: torch.Tensor):
|
|
"""Class index -> (kind, tens 0=none or 1+digit, units digit, letter); the parts that don't apply are ignored."""
|
|
is_number = y < len(NUMBERS)
|
|
is_letter = (y >= len(NUMBERS)) & (y != ILLEGIBLE)
|
|
kind = torch.full_like(y, KIND_ILLEGIBLE)
|
|
kind = torch.where(is_number, torch.full_like(y, KIND_NUMBER), kind)
|
|
kind = torch.where(is_letter, torch.full_like(y, KIND_LETTER), kind)
|
|
n = torch.where(is_number, y, torch.zeros_like(y))
|
|
tens = torch.where(n >= 10, 1 + n // 10, torch.zeros_like(n))
|
|
units = n % 10
|
|
letter = torch.where(is_letter, y - len(NUMBERS), torch.zeros_like(y))
|
|
ignore = torch.full_like(y, IGNORE)
|
|
return kind, torch.where(is_number, tens, ignore), torch.where(is_number, units, ignore), torch.where(is_letter, letter, ignore)
|
|
|
|
|
|
class DigitReader(nn.Module):
|
|
"""ResNet18 with four small heads: what is there (nothing legible, a number, a badge letter), tens digit (or
|
|
none), units digit, letter."""
|
|
|
|
def __init__(self, pretrained: bool):
|
|
super().__init__()
|
|
m = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None)
|
|
m.fc = nn.Identity()
|
|
self.backbone = m
|
|
self.drop = nn.Dropout(0.3)
|
|
self.kind = nn.Linear(512, 3)
|
|
self.tens = nn.Linear(512, 11)
|
|
self.units = nn.Linear(512, 10)
|
|
self.letter = nn.Linear(512, len(LETTERS))
|
|
|
|
def forward(self, x):
|
|
f = self.drop(self.backbone(x))
|
|
return self.kind(f), self.tens(f), self.units(f), self.letter(f)
|
|
|
|
|
|
class NumberProbs(nn.Module):
|
|
"""For export: head probabilities -> one probability per label (0..99, A..F, illegible), the format the worker reads."""
|
|
|
|
def __init__(self, reader: DigitReader):
|
|
super().__init__()
|
|
self.reader = reader
|
|
# Tens index 1 is a leading zero ("07"), which numbers never have: it is left out.
|
|
tens_idx = [0 if n < 10 else 1 + n // 10 for n in range(100)]
|
|
self.register_buffer("tens_idx", torch.tensor(tens_idx))
|
|
self.register_buffer("units_idx", torch.tensor([n % 10 for n in range(100)]))
|
|
mask = torch.ones(11)
|
|
mask[1] = 0
|
|
self.register_buffer("tens_mask", mask)
|
|
|
|
def forward(self, x):
|
|
kind, tens, units, letter = self.reader(x)
|
|
p_kind = torch.softmax(kind, 1)
|
|
p_tens = torch.softmax(tens, 1) * self.tens_mask
|
|
p_tens = p_tens / p_tens.sum(1, keepdim=True)
|
|
p_units = torch.softmax(units, 1)
|
|
numbers = p_kind[:, KIND_NUMBER : KIND_NUMBER + 1] * p_tens[:, self.tens_idx] * p_units[:, self.units_idx]
|
|
letters = p_kind[:, KIND_LETTER : KIND_LETTER + 1] * torch.softmax(letter, 1)
|
|
return torch.cat([numbers, letters, p_kind[:, KIND_ILLEGIBLE : KIND_ILLEGIBLE + 1]], 1)
|
|
|
|
|
|
def evaluate(model, loader, dev):
|
|
"""Accuracy of the final answer (number, letter or illegible), and of the label alone on legible crops."""
|
|
model.eval()
|
|
probs = NumberProbs(model).to(dev).eval()
|
|
ok = total = num_ok = num_total = 0
|
|
confusion = Counter()
|
|
with torch.no_grad():
|
|
for x, y in loader:
|
|
p = probs(x.to(dev)).argmax(1).cpu()
|
|
ok += (p == y).sum().item()
|
|
total += len(y)
|
|
legible = y != ILLEGIBLE
|
|
num_ok += (p[legible] == y[legible]).sum().item()
|
|
num_total += legible.sum().item()
|
|
for a, b in zip(y.tolist(), p.tolist()):
|
|
if a != b:
|
|
confusion[f"{LABELS[a]}->{LABELS[b]}"] += 1
|
|
return ok / max(1, total), num_ok / max(1, num_total), confusion
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("--dataset", required=True, help="JSON downloaded from the app")
|
|
ap.add_argument("--api", required=True, help="API base URL, e.g. https://api.photoreport.pt")
|
|
ap.add_argument("--out", default="models/jersey")
|
|
ap.add_argument("--epochs", type=int, default=25)
|
|
ap.add_argument("--batch", type=int, default=64)
|
|
ap.add_argument("--no-pretrained", action="store_true", help="start from scratch (offline)")
|
|
ap.add_argument("--cache", default="cache/crops")
|
|
ap.add_argument("--extra", action="append", default=[], help="more training data, e.g. synth/dataset.json (never used for the check)")
|
|
args = ap.parse_args()
|
|
|
|
manifest = json.loads(Path(args.dataset).read_text())
|
|
items = download(manifest, args.api, Path(args.cache))
|
|
if len(items) < 50:
|
|
raise SystemExit(f"only {len(items)} checked crops: check more in the app first (a few thousand is the goal)")
|
|
random.seed(7)
|
|
groups = sorted({g for *_, g in items})
|
|
random.shuffle(groups)
|
|
held = set(groups[: max(1, int(len(groups) * 0.2))])
|
|
val = [it for it in items if it[2] in held]
|
|
train = [it for it in items if it[2] not in held]
|
|
for extra in args.extra:
|
|
train += download(json.loads(Path(extra).read_text()), args.api, Path(args.cache))
|
|
counts = Counter(y for _, y, _ in train)
|
|
print(f"{len(train)} to train, {len(val)} to check; {len(counts)} classes seen; most common: {[(LABELS[k], v) for k, v in counts.most_common(5)]}")
|
|
|
|
dev = device()
|
|
model = DigitReader(not args.no_pretrained).to(dev)
|
|
ce = nn.CrossEntropyLoss(ignore_index=IGNORE, label_smoothing=0.05)
|
|
|
|
def part(logits, target):
|
|
# A batch with nothing of this kind (no letters, say) adds nothing, instead of NaN.
|
|
return ce(logits, target) if (target != IGNORE).any() else logits.sum() * 0
|
|
|
|
def loss_fn(out, y):
|
|
kind, tens, units, letter = targets(y)
|
|
lo_kind, lo_tens, lo_units, lo_letter = out
|
|
return ce(lo_kind, kind) + part(lo_tens, tens) + part(lo_units, units) + part(lo_letter, letter)
|
|
|
|
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
|
|
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=1e-3, total_steps=args.epochs * max(1, (len(train) + args.batch - 1) // args.batch))
|
|
tl = DataLoader(Crops(train, True), batch_size=args.batch, shuffle=True, num_workers=2)
|
|
vl = DataLoader(Crops(val, False), batch_size=args.batch, num_workers=2)
|
|
|
|
best = -1.0
|
|
out = Path(args.out)
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
for epoch in range(args.epochs):
|
|
model.train()
|
|
for x, y in tl:
|
|
opt.zero_grad()
|
|
loss = loss_fn(model(x.to(dev)), y.to(dev))
|
|
loss.backward()
|
|
opt.step()
|
|
sched.step()
|
|
acc, num_acc, confusion = evaluate(model, vl, dev)
|
|
print(f"epoch {epoch + 1}/{args.epochs}: loss {loss.item():.3f}, held-out: {acc:.1%} right overall, {num_acc:.1%} of legible numbers read right")
|
|
if acc > best:
|
|
best = acc
|
|
torch.save(model.state_dict(), out / "best.pt")
|
|
(out / "metrics.json").write_text(json.dumps({"accuracy": acc, "numbers_accuracy": num_acc, "epoch": epoch + 1, "train": len(train), "val": len(val), "mistakes": confusion.most_common(20)}, indent=1))
|
|
|
|
model.load_state_dict(torch.load(out / "best.pt", map_location="cpu"))
|
|
model = NumberProbs(model.cpu().eval()).eval()
|
|
torch.onnx.export(model, torch.zeros(1, 3, SIZE, SIZE), out / "jersey.onnx", input_names=["image"], output_names=["probs"], dynamic_axes={"image": {0: "n"}, "probs": {0: "n"}}, opset_version=17, dynamo=False)
|
|
(out / "labels.json").write_text(json.dumps({"labels": LABELS, "size": SIZE, "mean": MEAN, "std": STD, "letterbox": 114}))
|
|
print(f"best accuracy {best:.1%}; model in {out / 'jersey.onnx'}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|