Compare commits

...
Author SHA1 Message Date
spark 520e51209c Desktop 0.3.8: the editor engine runs in the interface kept on disk (CSP allows WebAssembly)
ci / rust (push) Successful in 11m47s
ci / typescript (push) Successful in 13m52s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 14m46s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 34m48s
Since 0.3.6 the window shows the interface from disk under the app's CSP, which had no script-src: WebAssembly
was refused and Revelar said the engine was missing. script-src now allows 'wasm-unsafe-eval' (and blob: for
the engine glue fallback), worker-src 'self' blob:. A test keeps it so.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 22:16:21 +01:00
spark 467df72a59 Faces: face, shirt number and kit colour together
ci / rust (push) Successful in 8m24s
ci / typescript (push) Successful in 11m44s
A weak or ambiguous face match is settled by the number read on the shirt; a sure face whose shirt clearly
reads another number is suggested as less sure; when both teams have a player with the number, the kit colour
(median of the chest, per face) against each team's confirmed players decides, or nothing is guessed.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 21:53:42 +01:00
spark 706aa8a5df Handball officials' cards (Oficial A-F) are learnt and read like shirt numbers
ci / rust (push) Successful in 7m51s
ci / typescript (push) Successful in 11m8s
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
2026-10-13 21:44:25 +01:00
spark c32012a0cd Shirt numbers: a shorts crop for football, next to the chest crop for handball
ci / rust (push) Successful in 7m40s
ci / typescript (push) Successful in 10m49s
A sample of Liga Portugal 2026/27 photos (14 clubs) shows no chest numbers: the front number is on the shorts.
Each confirmed face now gives two samples (region CHEST and SHORTS); the reader tries both and keeps the more
confident reading. Faces collected before get the shorts crop once (faces.jersey_crops). Synthetic training
data also paints small side numbers.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 21:30:38 +01:00
spark e554c2e7d6 Shirt numbers: start teaching over, and a clearer rule for what counts as readable
ci / rust (push) Successful in 7m50s
ci / typescript (push) Successful in 10m41s
A reset (editors) sends every checked sample back to review, dropping the answers; samples and crops stay.
The help now says plainly: "Certo" only when the whole number reads in the crop, whoever the player is.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 19:46:35 +01:00
spark 3860e2e1e0 Desktop updates never fail in silence: the page asks the server and offers the installer
ci / rust (push) Successful in 7m47s
ci / typescript (push) Successful in 10m44s
The 0.3.5 app showed no update banner: the shell's own check gave no answer and the error was swallowed.
Now the error is shown, and the page also asks the update endpoint itself (installed version from the app)
and, when the shell cannot update itself, offers the release's full installer (.dmg). The API names it in
the update answer (`installer`, ignored by Tauri).

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 19:36:12 +01:00
27 changed files with 714 additions and 118 deletions

No files matched your search

@@ -0,0 +1,14 @@
-- CreateEnum
CREATE TYPE "JerseyRegion" AS ENUM ('CHEST', 'SHORTS');
-- DropIndex
DROP INDEX "jersey_samples_face_id_key";
-- AlterTable
ALTER TABLE "jersey_samples" ADD COLUMN "region" "JerseyRegion" NOT NULL DEFAULT 'CHEST';
-- CreateIndex
CREATE UNIQUE INDEX "jersey_samples_face_id_region_key" ON "jersey_samples"("face_id", "region");
-- AlterTable
ALTER TABLE "faces" ADD COLUMN "jersey_crops" INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "faces" ADD COLUMN "kit_colour" DOUBLE PRECISION[] DEFAULT ARRAY[]::DOUBLE PRECISION[];
+17 -2
View File
@@ -647,12 +647,16 @@ model Face {
/// Shirt number read under the face by the jersey model (null: not run, or not legible) and its confidence.
jerseyNumber String? @map("jersey_number")
jerseyScore Float? @map("jersey_score")
/// The set of number crops its training samples were made with (`JERSEY_CROPS` in jersey/service.ts); 0: none yet.
jerseyCrops Int @default(0) @map("jersey_crops")
/// Median RGB of the kit under the face (chest): tells the two teams apart when both have a player with a number.
kitColour Float[] @default([]) @map("kit_colour")
createdAt DateTime @default(now()) @map("created_at")
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
photo Photo @relation(fields: [photoId], references: [id], onDelete: Cascade)
group FaceGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull)
jerseySample JerseySample?
jerseySamples JerseySample[]
@@index([photoId])
@@index([groupId])
@@ -1106,6 +1110,14 @@ model PendingUpload {
@@map("pending_uploads")
}
/// Where a shirt-number crop is taken from, under the face.
enum JerseyRegion {
/// Chest and belly: the front number of handball (and most other) kits.
CHEST
/// Waist to mid-thigh: the front number of football kits (Liga Portugal shirts have none on the chest).
SHORTS
}
enum JerseySampleStatus {
/// Made from a confirmed face and the squad's number; waiting for a person to check it.
PENDING
@@ -1124,7 +1136,9 @@ enum JerseySampleStatus {
model JerseySample {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
faceId String @unique @map("face_id") @db.Uuid
faceId String @map("face_id") @db.Uuid
/// Where on the player the crop is: football kits carry the front number on the shorts, handball on the chest.
region JerseyRegion @default(CHEST)
photoId String @map("photo_id") @db.Uuid
personId String? @map("person_id") @db.Uuid
/// Torso box in fractions of the photo.
@@ -1143,6 +1157,7 @@ model JerseySample {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
face Face @relation(fields: [faceId], references: [id], onDelete: Cascade)
@@unique([faceId, region])
@@index([organizationId, status])
@@map("jersey_samples")
}
+16 -3
View File
@@ -59,6 +59,9 @@ export function newer(candidate: string, current: string): boolean {
return a.pre > b.pre;
}
/** The full installer a person downloads and opens, per platform. */
const INSTALLER: Record<string, RegExp> = { darwin: /\.dmg$/, windows: /\.msi$|-setup\.exe$/, linux: /\.AppImage$/ };
export class DesktopReleases {
private cache: { at: number; releases: GiteaRelease[] } | null = null;
@@ -99,20 +102,29 @@ export class DesktopReleases {
return res;
}
/** Tauri's dynamic update answer for one platform, or null when there is nothing newer. */
async updateFor(target: string, arch: string, current: string): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string } | null> {
/**
* Tauri's dynamic update answer for one platform, or null when there is nothing newer. `installer` (ignored by
* Tauri) is the full installer of the same release: the app offers it when it cannot update itself.
*/
async updateFor(
target: string,
arch: string,
current: string,
): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string; installer?: string } | null> {
const found = await this.forPlatform(target, arch);
if (!found) return null;
const { release } = found;
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
if (!newer(manifest.version, current)) return null;
if (!release.assets.some((a) => a.name === manifest.file)) return null;
const installer = release.assets.find((a) => INSTALLER[target]?.test(a.name));
return {
version: manifest.version,
notes: manifest.notes ?? release.body ?? "",
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
signature: manifest.signature,
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
};
}
@@ -143,7 +155,8 @@ export async function registerDesktopRoutes(app: FastifyInstance, deps: { releas
try {
const update = await releases.updateFor(target, arch, version);
if (!update) return reply.code(204).send();
return { ...update, url: `${deps.publicApiUrl.replace(/\/$/, "")}${update.url}` };
const base = deps.publicApiUrl.replace(/\/$/, "");
return { ...update, url: `${base}${update.url}`, ...(update.installer ? { installer: `${base}${update.installer}` } : {}) };
} catch (err) {
req.log.warn({ err }, "desktop update check failed");
return reply.code(204).send();
+82 -17
View File
@@ -5,8 +5,9 @@ import type { FaceGroup, Person } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import type { Broadcaster } from "../realtime.js";
import type { LocalStorage } from "../storage/storage.js";
import { type Box, torsoBox } from "../jersey/crop.js";
import { type Box, colourDistance, kitColour, numberBoxes, smallImage, torsoBox } from "../jersey/crop.js";
import type { JerseyReading } from "../jersey/model.js";
import { normLabel } from "../jersey/service.js";
/** Below this the shirt-number reading is not used for suggestions. */
export const JERSEY_MIN_SCORE = 0.7;
@@ -108,17 +109,25 @@ export class FaceService {
const analysis = await engine.analyse(storage.resolve(photo.storageKey));
// Only faces in focus are kept: the blurred crowd and benches are not who the photo is about.
const faces = inFocus(analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE));
// The shirt number under each clear face, when a number model is installed.
// The shirt number under each clear face, when a number model is installed: on the chest (handball) or the
// shorts (football), whichever the model reads with more confidence.
const numbers = new Map<number, JerseyReading>();
if (this.deps.jersey) {
for (const [i, f] of faces.entries()) {
if (f.sharpness != null && f.sharpness < MIN_SHARPNESS) continue;
const box = torsoBox(f, analysis.width, analysis.height);
if (!box) continue;
const reading = await this.deps.jersey.read(storage.resolve(photo.storageKey), box).catch(() => null);
if (reading?.number) numbers.set(i, reading);
for (const { box } of numberBoxes(f, analysis.width, analysis.height)) {
const reading = await this.deps.jersey.read(storage.resolve(photo.storageKey), box).catch(() => null);
const best = numbers.get(i);
if (reading?.number && (!best || reading.score > best.score)) numbers.set(i, reading);
}
}
}
// The kit colour under each face: tells the two teams apart when both have a player with the read number.
const small = faces.length ? await smallImage(storage.resolve(photo.storageKey)).catch(() => null) : null;
const kits = faces.map((f) => {
const chest = small ? torsoBox(f, small.width, small.height) : null;
return small && chest ? kitColour(small, chest) : null;
});
await db.$transaction(async (tx) => {
await tx.face.deleteMany({ where: { photoId } });
for (const [i, f] of faces.entries()) {
@@ -137,6 +146,7 @@ export class FaceService {
model: engine.model,
jerseyNumber: n?.number ?? null,
jerseyScore: n?.score ?? null,
kitColour: kits[i] ?? [],
},
});
}
@@ -214,10 +224,21 @@ export class FaceService {
const ok = first && first.s >= match && (!second || first.s - second.s >= margin);
let suggestedPersonId = ok ? first.p.id : null;
let suggestionScore = ok ? first.s : null;
if (!ok) {
// No face match: the shirt number, if the faces agree on one and exactly one player of these teams wears it.
const byNumber = await this.suggestByNumber(g.id, eventId);
if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber);
const read = await this.groupNumber(g.id);
if (ok && read && first.p.number && normLabel(first.p.number) !== read.number && read.votes >= 2) {
// The face says one person, the shirt clearly says another number: still suggested, but as less sure.
suggestionScore = Math.round(first.s * 0.8 * 1000) / 1000;
} else if (!ok && read) {
// The face alone is not sure (too weak, or two people too close): the number decides among the near ones.
const near = ranked.filter((r) => r.s >= match * 0.8 && normLabel(r.p.number) === read.number);
if (near.length === 1) {
suggestedPersonId = near[0]!.p.id;
suggestionScore = Math.round(Math.max(near[0]!.s, read.score * 0.9) * 1000) / 1000;
} else {
// No face to go by: the number (and, when both teams have it, the colour of the kit).
const byNumber = await this.suggestByNumber(g.id, eventId, read);
if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber);
}
}
if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) {
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
@@ -231,11 +252,12 @@ export class FaceService {
return majorityNumber(faces);
}
/** A suggestion from the shirt number: only when one squad player of the event's teams has it. Never names on its own. */
private async suggestByNumber(groupId: string, eventId: string): Promise<{ personId: string; score: number } | null> {
/**
* A suggestion from the shirt number: when one squad player of the event's teams has it, or when both teams have
* one and the kit colour clearly says which team. Never names on its own.
*/
private async suggestByNumber(groupId: string, eventId: string, read: NumberVote): Promise<{ personId: string; score: number } | null> {
const { db } = this.deps;
const read = await this.groupNumber(groupId);
if (!read) return null;
const event = await db.event.findUnique({
where: { id: eventId },
select: { organizationId: true, home: true, away: true, homeShort: true, awayShort: true, homeTeamId: true, awayTeamId: true },
@@ -244,16 +266,24 @@ export class FaceService {
// Linked to the official match: the squads say who wears the number.
const teamIds = [event.homeTeamId, event.awayTeamId].filter((t): t is string => !!t);
if (teamIds.length) {
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, goneAt: null, number: read.number }, select: { id: true } });
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, goneAt: null, number: read.number }, select: { id: true, teamId: true } });
const people = players.length
? await db.person.findMany({ where: { organizationId: event.organizationId, sportsPlayerId: { in: players.map((p) => p.id) } }, select: { id: true } })
: [];
if (people.length === 1) return { personId: people[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
if (players.length) return null; // two players with that number, or not people yet: no guess
if (people.length === 2) {
// One in each team: the kit colour of this group against each team's (from players already confirmed here).
const byPlayer = new Map(players.map((p) => [p.id, p.teamId]));
const withTeam = await db.person.findMany({ where: { id: { in: people.map((p) => p.id) } }, select: { id: true, sportsPlayerId: true } });
const team = await this.teamByKit(groupId, eventId);
const pick = team ? withTeam.find((p) => p.sportsPlayerId && byPlayer.get(p.sportsPlayerId) === team.teamId) : undefined;
if (pick && team) return { personId: pick.id, score: Math.round(read.score * 0.85 * team.sure * 1000) / 1000 };
}
if (players.length) return null; // two players with that number and no clear kit, or not people yet: no guess
}
const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(norm);
const candidates = (await db.person.findMany({ where: { organizationId: event.organizationId, number: { not: null }, club: { not: null } } }))
.filter((p) => String(Number(p.number!.trim())) === read.number)
.filter((p) => normLabel(p.number) === read.number)
.filter((p) => {
const club = norm(p.club!);
return teams.some((t) => t && (t.includes(club) || club.includes(t)));
@@ -262,6 +292,41 @@ export class FaceService {
return { personId: candidates[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
}
/**
* Which of the event's two teams a group plays for, by kit colour: each team's colour comes from the faces of its
* players already confirmed in this event (goalkeepers left out: they wear their own colours). Null unless one team
* is clearly closer. `sure` is 1 when it is very clear, less when only fairly.
*/
async teamByKit(groupId: string, eventId: string): Promise<{ teamId: string; sure: number } | null> {
const { db } = this.deps;
const event = await db.event.findUnique({ where: { id: eventId }, select: { homeTeamId: true, awayTeamId: true } });
if (!event?.homeTeamId || !event.awayTeamId) return null;
const median = (cols: number[][]) => (cols.length ? [0, 1, 2].map((c) => cols.map((v) => v[c]!).sort((a, b) => a - b)[cols.length >> 1]!) : null);
const mine = median((await db.face.findMany({ where: { groupId }, select: { kitColour: true } })).map((f) => f.kitColour).filter((k) => k.length === 3));
if (!mine) return null;
const confirmed = await db.face.findMany({
where: { photo: { eventId }, group: { personId: { not: null } }, NOT: { kitColour: { isEmpty: true } } },
select: { kitColour: true, group: { select: { person: { select: { sportsPlayerId: true } } } } },
});
const ids = [...new Set(confirmed.map((f) => f.group?.person?.sportsPlayerId).filter((x): x is string => !!x))];
const players = new Map((await db.sportsPlayer.findMany({ where: { id: { in: ids } }, select: { id: true, teamId: true, position: true } })).map((p) => [p.id, p]));
const byTeam = new Map<string, number[][]>();
for (const f of confirmed) {
const spId = f.group?.person?.sportsPlayerId;
const sp = spId ? players.get(spId) : undefined;
if (!sp || /guarda|gr\b|goal/i.test(sp.position ?? "")) continue;
byTeam.set(sp.teamId, [...(byTeam.get(sp.teamId) ?? []), f.kitColour]);
}
const home = median(byTeam.get(event.homeTeamId) ?? []);
const away = median(byTeam.get(event.awayTeamId) ?? []);
if (!home || !away || colourDistance(home, away) < 60) return null; // unknown, or kits too alike to tell
const dh = colourDistance(mine, home);
const da = colourDistance(mine, away);
const [near, far, teamId] = dh < da ? [dh, da, event.homeTeamId] : [da, dh, event.awayTeamId];
if (near > 0.6 * far || near > 90) return null;
return { teamId, sure: near < 0.35 * far ? 1 : 0.9 };
}
/** Adds the confirmed person's name to the players of these photos (keeps names already there). */
private async nameConfirmedPhotos(photoIds: string[]): Promise<void> {
if (!photoIds.length) return;
+76
View File
@@ -29,6 +29,40 @@ export function torsoBox(face: Box, width: number, height: number): Box | null {
return { x0: box.x0 / width, y0: box.y0 / height, x1: box.x1 / width, y1: box.y1 / height };
}
/**
* Where the shorts number is, from the face: waist to mid-thigh, about three and a half faces wide. Football kits
* (all of Liga Portugal) carry no number on the chest; the front number is on one leg of the shorts, small, so this
* crop is tighter than the torso one to keep it readable.
*/
export function shortsBox(face: Box, width: number, height: number): Box | null {
const fw = (face.x1 - face.x0) * width;
const fh = (face.y1 - face.y0) * height;
if (fw < 12 || fh < 12) return null;
const cx = ((face.x0 + face.x1) / 2) * width;
const top = face.y1 * height + 3.4 * fh;
const box = {
x0: Math.max(0, cx - 1.8 * fw),
x1: Math.min(width, cx + 1.8 * fw),
y0: Math.max(0, top),
y1: Math.min(height, top + 3.4 * fh),
};
// Cut off by the frame (the shorts below the bottom edge): nothing to read.
if (box.y1 - box.y0 < 2 * fh || box.x1 - box.x0 < 2 * fw) return null;
return { x0: box.x0 / width, y0: box.y0 / height, x1: box.x1 / width, y1: box.y1 / height };
}
export type JerseyRegion = "CHEST" | "SHORTS";
/** The crops under a face where a front number may be, in the order they are tried. */
export function numberBoxes(face: Box, width: number, height: number): { region: JerseyRegion; box: Box }[] {
const out: { region: JerseyRegion; box: Box }[] = [];
const chest = torsoBox(face, width, height);
if (chest) out.push({ region: "CHEST", box: chest });
const shorts = shortsBox(face, width, height);
if (shorts) out.push({ region: "SHORTS", box: shorts });
return out;
}
/** The crop the model sees and people review: from the original, upright, at most 256 px on the long side. */
export async function cropJpeg(original: string, box: Box, size = 256): Promise<Buffer> {
const img = sharp(original).rotate();
@@ -41,3 +75,45 @@ export async function cropJpeg(original: string, box: Box, size = 256): Promise<
const height = Math.max(1, Math.min(h - top, Math.round((box.y1 - box.y0) * h)));
return sharp(original).rotate().extract({ left, top, width, height }).resize({ width: size, height: size, fit: "inside" }).jpeg({ quality: 90 }).toBuffer();
}
/** A photo decoded once, small: enough to tell the colour of a kit. */
export interface SmallImage {
data: Buffer;
width: number;
height: number;
channels: number;
}
export async function smallImage(original: string, side = 512): Promise<SmallImage> {
const { data, info } = await sharp(original).rotate().resize(side, side, { fit: "inside" }).removeAlpha().raw().toBuffer({ resolveWithObject: true });
return { data, width: info.width, height: info.height, channels: info.channels };
}
/**
* The colour of the kit under a face: the median of each channel in the middle of the chest crop (away from arms,
* background and the number itself as much as a box can be). Median, not mean, so stripes and a sponsor's logo
* pull it less. Null when the box has no pixels.
*/
export function kitColour(img: SmallImage, chest: Box): number[] | null {
const x0 = Math.floor((chest.x0 + (chest.x1 - chest.x0) * 0.3) * img.width);
const x1 = Math.ceil((chest.x0 + (chest.x1 - chest.x0) * 0.7) * img.width);
const y0 = Math.floor((chest.y0 + (chest.y1 - chest.y0) * 0.05) * img.height);
const y1 = Math.ceil((chest.y0 + (chest.y1 - chest.y0) * 0.55) * img.height);
const ch: number[][] = [[], [], []];
for (let y = Math.max(0, y0); y < Math.min(img.height, y1); y++) {
for (let x = Math.max(0, x0); x < Math.min(img.width, x1); x++) {
const i = (y * img.width + x) * img.channels;
for (let c = 0; c < 3; c++) ch[c]!.push(img.data[i + c]!);
}
}
if (!ch[0]!.length) return null;
return ch.map((v) => {
v.sort((a, b) => a - b);
return v[v.length >> 1]!;
});
}
/** Distance between two kit colours (RGB, 0-441). */
export function colourDistance(a: number[], b: number[]): number {
return Math.hypot(a[0]! - b[0]!, a[1]! - b[1]!, a[2]! - b[2]!);
}
+2 -2
View File
@@ -18,8 +18,8 @@ export interface JerseyReading {
}
/**
* The shirt-number model trained with workers/ml/jersey (ONNX): the torso crop in, a number 0-99 or
* "illegible" out. Loaded once by the worker; one crop takes a few tens of milliseconds on a CPU core.
* The shirt-number model trained with workers/ml/jersey (ONNX): a chest or shorts crop in, a number 0-99, a handball
* official's card letter (A-F) or "illegible" out. Loaded once by the worker; one crop takes a few tens of milliseconds on a CPU core.
*/
export class JerseyModel {
private constructor(
+7
View File
@@ -47,6 +47,13 @@ export async function registerJerseyRoutes(app: FastifyInstance, deps: { db: Db;
return reply.header("content-type", "image/jpeg").header("cache-control", "private, max-age=86400").send(createReadStream(await jersey.cropFile(sample)));
});
/** Teaching starts over: every answer is dropped and the samples are to review again. */
app.post("/v1/orgs/:orgId/jersey/reset", { preHandler: authenticate }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
await requireMembership(db, req, orgId, "EDITOR");
return { reset: await jersey.reset(orgId) };
});
/** The checked dataset, for `workers/ml/jersey/train.py` (download it from the app). */
app.get("/v1/orgs/:orgId/jersey/dataset", { preHandler: authenticate }, async (req, reply) => {
const { orgId } = OrgParams.parse(req.params);
+46 -19
View File
@@ -3,7 +3,7 @@ import type { Db } from "../db.js";
import type { JerseySample, JerseySampleStatus } from "../generated/prisma/client.js";
import type { LocalStorage } from "../storage/storage.js";
import { MIN_SHARPNESS } from "../faces/math.js";
import { cropJpeg, torsoBox } from "./crop.js";
import { cropJpeg, numberBoxes } from "./crop.js";
export interface SampleView {
id: string;
@@ -12,14 +12,28 @@ export interface SampleView {
suggested: string | null;
label: string | null;
status: JerseySampleStatus;
region: "CHEST" | "SHORTS";
crop: string;
}
export const NUMBER = /^\d{1,3}$/;
/** What a crop can be labelled with: a shirt number, or the letter on a handball official's card (A-F; B is usually the head coach). */
export const LABEL = /^(\d{1,3}|[A-F])$/;
/** "07" and "7" are the same shirt; "b" and "Oficial B" are the same card. Null when it is neither. */
export function normLabel(raw: string | null | undefined): string | null {
const s = (raw ?? "").trim().replace(/^oficial\s*/i, "").toUpperCase();
if (NUMBER.test(s)) return String(Number(s));
return LABEL.test(s) ? s : null;
}
/** Bumped when the crops change (2: chest and shorts), so faces collected before get the new ones once. */
export const JERSEY_CROPS = 2;
/**
* Training data for reading shirt numbers. Every face in a group confirmed as someone whose squad entry has a
* number becomes a sample (the torso under the face, labelled with that number); people check them in the app
* number becomes samples (the chest and the shorts under the face, labelled with that number); people check them in the app
* (right, corrected, not legible). The checked samples are the dataset `workers/ml/jersey` trains on.
*/
export class JerseyService {
@@ -37,35 +51,38 @@ export class JerseyService {
return sig === this.sig(id);
}
/** Makes samples for confirmed faces that have none yet. Returns how many were added. */
/** Makes the samples confirmed faces do not have yet (one per region). Returns how many were added. */
async collect(organizationId: string): Promise<number> {
const { db } = this.deps;
const faces = await db.face.findMany({
where: {
organizationId,
jerseySample: null,
jerseyCrops: { lt: JERSEY_CROPS },
OR: [{ sharpness: null }, { sharpness: { gte: MIN_SHARPNESS } }],
group: { person: { number: { not: null } } },
},
include: { photo: { select: { width: true, height: true } }, group: { include: { person: true } } },
include: { photo: { select: { width: true, height: true } }, group: { include: { person: true } }, jerseySamples: { select: { region: true } } },
take: 5000,
});
let added = 0;
for (const f of faces) {
const person = f.group?.person;
if (!person?.number || !f.photo.width || !f.photo.height) continue;
const box = torsoBox(f, f.photo.width, f.photo.height);
if (!box) continue;
await db.jerseySample.create({
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person.id, ...box, suggested: person.number.trim() },
});
added++;
const have = new Set(f.jerseySamples.map((s) => s.region));
const boxes = person?.number && f.photo.width && f.photo.height ? numberBoxes(f, f.photo.width, f.photo.height) : [];
for (const { region, box } of boxes) {
if (have.has(region)) continue;
await db.jerseySample.create({
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person!.id, region, ...box, suggested: normLabel(person!.number) ?? person!.number!.trim() },
});
added++;
}
await db.face.update({ where: { id: f.id }, data: { jerseyCrops: JERSEY_CROPS } });
}
return added;
}
async view(s: JerseySample & { person?: { name: string } | null }): Promise<SampleView> {
return { id: s.id, photoId: s.photoId, person: s.person?.name ?? null, suggested: s.suggested, label: s.label, status: s.status, crop: this.cropUrl(s.id) };
return { id: s.id, photoId: s.photoId, person: s.person?.name ?? null, suggested: s.suggested, label: s.label, status: s.status, region: s.region, crop: this.cropUrl(s.id) };
}
async list(organizationId: string, status: JerseySampleStatus, limit: number): Promise<SampleView[]> {
@@ -83,16 +100,26 @@ export class JerseyService {
}
async review(sample: JerseySample, userId: string, input: { status: "CONFIRMED" | "ILLEGIBLE" | "SKIPPED" | "PENDING"; label?: string | null | undefined }): Promise<JerseySample> {
const raw = input.status === "CONFIRMED" ? (input.label ?? sample.suggested)?.trim() : null;
// "07" and "7" are the same shirt.
const label = raw && NUMBER.test(raw) ? String(Number(raw)) : raw;
if (input.status === "CONFIRMED" && (!label || !NUMBER.test(label))) throw new Error("label_required");
const label = input.status === "CONFIRMED" ? normLabel(input.label ?? sample.suggested) : null;
if (input.status === "CONFIRMED" && !label) throw new Error("label_required");
return this.deps.db.jerseySample.update({
where: { id: sample.id },
data: { status: input.status, label: label ?? null, reviewedById: input.status === "PENDING" ? null : userId, reviewedAt: input.status === "PENDING" ? null : new Date() },
});
}
/**
* Starts teaching over: every checked sample goes back to "to review" (answers given so far are dropped; the
* samples and their crops stay). Returns how many were reset.
*/
async reset(organizationId: string): Promise<number> {
const r = await this.deps.db.jerseySample.updateMany({
where: { organizationId, status: { not: "PENDING" } },
data: { status: "PENDING", label: null, reviewedById: null, reviewedAt: null },
});
return r.count;
}
/** The crop, made from the original on first request and cached. */
async cropFile(sample: JerseySample): Promise<string> {
const { db, storage } = this.deps;
@@ -110,8 +137,8 @@ export class JerseyService {
return {
version: 1,
createdAt: new Date().toISOString(),
classes: "0-99 and 'illegible'",
samples: samples.map((s) => ({ id: s.id, label: s.status === "ILLEGIBLE" ? "illegible" : s.label!, crop: this.cropUrl(s.id) })),
classes: "0-99, A-F (officials' cards) and 'illegible'",
samples: samples.map((s) => ({ id: s.id, region: s.region, label: s.status === "ILLEGIBLE" ? "illegible" : s.label!, crop: this.cropUrl(s.id) })),
};
}
}
+2 -2
View File
@@ -29,7 +29,7 @@ describe("desktop updates", () => {
it("answers with the newest desktop release for the platform, through the API, and nothing when up to date", async () => {
const releases = [
{ id: 7, tag_name: "desktop-v0.3.0", draft: false, prerelease: false, body: "Catálogo local", published_at: "2026-10-13T09:00:00Z", assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport_universal.app.tar.gz")] },
{ id: 7, tag_name: "desktop-v0.3.0", draft: false, prerelease: false, body: "Catálogo local", published_at: "2026-10-13T09:00:00Z", assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport_universal.app.tar.gz"), asset(4, "PhotoReport_0.3.0_universal.dmg")] },
{ id: 9, tag_name: "desktop-v0.4.0", draft: true, prerelease: false, body: "", published_at: null, assets: [] },
{ id: 5, tag_name: "v1.2.0", draft: false, prerelease: false, body: "", published_at: null, assets: [] },
{ id: 3, tag_name: "desktop-v0.2.0", draft: false, prerelease: false, body: "", published_at: null, assets: [] },
@@ -39,7 +39,7 @@ describe("desktop updates", () => {
const r = new DesktopReleases({ api: API, token: "read-token-123" }, impl);
const update = await r.updateFor("darwin", "aarch64", "0.2.0");
expect(update).toMatchObject({ version: "0.3.0", notes: "Catálogo local", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz" });
expect(update).toMatchObject({ version: "0.3.0", notes: "Catálogo local", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz", installer: "/v1/desktop/download/7/PhotoReport_0.3.0_universal.dmg" });
expect(await r.updateFor("darwin", "x86_64", "0.3.0")).toBeNull();
expect(await r.updateFor("windows", "x86_64", "0.2.0")).toBeNull();
expect(calls.every((c) => c.auth === "token read-token-123")).toBe(true);
+72 -5
View File
@@ -294,8 +294,9 @@ describe("faces", () => {
await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g.id}/confirm`, headers: bearer(token), payload: { name: "Miguel Silva (VSC)", club: "VSC", number: "07" } });
const orgId = (await ctx.db.photo.findFirstOrThrow()).organizationId;
const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/samples`, headers: bearer(token) })).json() as { collected: number; samples: { id: string; suggested: string; crop: string; person: string }[] };
expect(list.collected).toBe(2);
expect(list.samples[0]).toMatchObject({ suggested: "07", person: "Miguel Silva (VSC)" });
expect(list.collected).toBe(4); // chest and shorts of two faces
expect(list.samples.map((x) => (x as unknown as { region: string }).region).sort()).toEqual(["CHEST", "CHEST", "SHORTS", "SHORTS"]);
expect(list.samples[0]).toMatchObject({ suggested: "7", person: "Miguel Silva (VSC)" });
const crop = await ctx.app.inject({ method: "GET", url: list.samples[0]!.crop });
expect(crop.statusCode).toBe(200);
expect((await sharp(crop.rawPayload).metadata()).height).toBeLessThanOrEqual(256);
@@ -307,6 +308,21 @@ describe("faces", () => {
await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[1]!.id}/review`, headers: bearer(token), payload: { status: "ILLEGIBLE" } });
const dataset = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/dataset`, headers: bearer(token) })).json() as { samples: { label: string }[] };
expect(dataset.samples.map((s) => s.label).sort()).toEqual(["7", "illegible"]);
// A handball official's card: the letter is a label like a number.
const card = await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[2]!.id}/review`, headers: bearer(token), payload: { status: "CONFIRMED", label: "b" } });
expect(card.json()).toMatchObject({ status: "CONFIRMED", label: "B" });
const bad = await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[3]!.id}/review`, headers: bearer(token), payload: { status: "CONFIRMED", label: "Z" } });
expect(bad.statusCode).toBe(400);
await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[2]!.id}/review`, headers: bearer(token), payload: { status: "PENDING" } });
// Starting over: every answer is dropped, the samples are to review again.
const reset = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/jersey/reset`, headers: bearer(token) });
expect(reset.json()).toEqual({ reset: 2 });
expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/dataset`, headers: bearer(token) })).json() as { samples: unknown[] }).samples).toEqual([]);
const again = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/samples`, headers: bearer(token) })).json() as { samples: { label: string | null; status: string }[] };
expect(again.samples.length).toBe(list.samples.length);
expect(again.samples.every((s) => s.status === "PENDING" && s.label === null)).toBe(true);
});
it("suggests a squad player from the shirt number the faces agree on, when only one of these teams wears it", async () => {
@@ -319,16 +335,24 @@ describe("faces", () => {
{ organizationId: orgId, name: "Zé Sete", club: "VSC", number: "7" },
],
});
// The number model reads 10, 10 and (once, less sure) 16 on this player's shirt.
// Football: nothing on the chest; on the shorts the model reads 10, 10 and (once, less sure) 16.
const readings = ["10", "10", "16"];
let calls = 0;
const reader = { read: async () => ({ number: readings[calls++ % 3]!, score: calls === 3 ? 0.75 : 0.95 }) };
let shorts = 0;
const reader = {
read: async () => {
calls++;
if (calls % 2 === 1) return { number: null, score: 0.9 }; // the chest crop comes first
const n = shorts++;
return { number: readings[n]!, score: n === 2 ? 0.75 : 0.95 };
},
};
const withNumbers = new FaceService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), broadcaster, log: quiet, engine, jersey: reader });
await photo("2026:09:23 21:00:00", [5]);
await photo("2026:09:23 21:01:00", [5]);
await photo("2026:09:23 21:02:00", [5]);
for (let ids = await withNumbers.claim(10); ids.length; ids = await withNumbers.claim(10)) for (const id of ids) await withNumbers.process(id);
expect(calls).toBe(3);
expect(calls).toBe(6); // chest and shorts of each face
const { groups } = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as {
groups: { person: unknown; suggestion: { name: string; score: number } | null; number: { value: string; votes: number } | null }[];
@@ -341,4 +365,47 @@ describe("faces", () => {
expect(groups[0]!.person).toBeNull();
expect((await ctx.db.photo.findMany({ select: { players: true } })).every((p) => p.players.length === 0)).toBe(true);
});
it("tells apart two players with the same number, one per team, by the colour of the kit", async () => {
const { token, day1, orgId } = await setup();
const team = (name: string, ext: string) => ctx.db.sportsTeam.create({ data: { provider: "FPA", externalId: ext, sport: "handball", name, slug: name.toLowerCase() } });
const home = await team("VSC", "t1");
const away = await team("AAAS", "t2");
await ctx.db.event.update({ where: { id: day1.id }, data: { homeTeamId: home.id, awayTeamId: away.id } });
const player = async (teamId: string, name: string, number: string, position: string | null = null) => {
const sp = await ctx.db.sportsPlayer.create({ data: { teamId, season: "20262027", name, number, position } });
return ctx.db.person.create({ data: { organizationId: orgId, name, number, sportsPlayerId: sp.id } });
};
const homeSeven = await player(home.id, "Casa Sete", "7");
const awaySeven = await player(away.id, "Fora Sete", "7");
await player(home.id, "Casa Dez", "10");
await player(away.id, "Fora Dez", "10");
await player(away.id, "Fora Guarda-Redes", "1", "Guarda-Redes");
// Two players already confirmed in this event: the home side plays in red, the away side in blue.
await photo("2026:09:23 21:00:00", [1]);
await photo("2026:09:23 21:01:00", [2]);
await drain();
const listed = () => ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) }).then((r) => r.json() as { groups: { id: string; size: number; person: { name: string } | null; suggestion: { name: string; score: number } | null }[] });
const [g1, g2] = (await listed()).groups;
await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g1!.id}/confirm`, headers: bearer(token), payload: { personId: homeSeven.id } });
await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g2!.id}/confirm`, headers: bearer(token), payload: { personId: awaySeven.id } });
await ctx.db.face.updateMany({ where: { groupId: g1!.id }, data: { kitColour: [200, 30, 30] } });
await ctx.db.face.updateMany({ where: { groupId: g2!.id }, data: { kitColour: [30, 40, 190] } });
// Someone new, whose shirt reads 10 (both teams have a 10), in red.
await photo("2026:09:23 21:02:00", [3]);
await photo("2026:09:23 21:03:00", [3]);
await drain();
const g3 = (await listed()).groups.find((g) => !g.person)!;
await ctx.db.face.updateMany({ where: { groupId: g3.id }, data: { jerseyNumber: "10", jerseyScore: 0.95, kitColour: [190, 45, 35] } });
await faces.refreshSuggestions(day1.id);
const suggested = (await listed()).groups.find((g) => g.id === g3.id)!;
expect(suggested.suggestion).toMatchObject({ name: "Casa Dez" });
expect(suggested.person).toBeNull();
// A kit in between the two: no guess.
await ctx.db.face.updateMany({ where: { groupId: g3.id }, data: { kitColour: [115, 35, 110] } });
await faces.refreshSuggestions(day1.id);
expect((await listed()).groups.find((g) => g.id === g3.id)!.suggestion).toBeNull();
});
});
+51
View File
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { numberBoxes, shortsBox, torsoBox } from "../src/jersey/crop.js";
// A player standing in a 3:2 frame: face 4% wide and 6% tall, high in the picture.
const face = { x0: 0.48, y0: 0.1, x1: 0.52, y1: 0.16 };
const W = 6000;
const H = 4000;
describe("shirt-number crops", () => {
it("takes the chest for handball and the shorts for football, the shorts lower and tighter", () => {
const chest = torsoBox(face, W, H)!;
const shorts = shortsBox(face, W, H)!;
expect(chest.y0).toBeGreaterThan(face.y1);
// The shorts start around the waist, under most of the chest crop, and reach mid-thigh.
expect(shorts.y0).toBeGreaterThan(chest.y0 + (chest.y1 - chest.y0) * 0.6);
expect(shorts.y1).toBeCloseTo(face.y1 + 6.8 * (face.y1 - face.y0), 5);
expect(shorts.y1 - shorts.y0).toBeLessThan(chest.y1 - chest.y0);
expect(numberBoxes(face, W, H).map((b) => b.region)).toEqual(["CHEST", "SHORTS"]);
});
it("leaves out the shorts when the frame cuts them (a close-up from the waist up)", () => {
const low = { x0: 0.45, y0: 0.4, x1: 0.55, y1: 0.55 };
expect(shortsBox(low, W, H)).toBeNull();
expect(numberBoxes(low, W, H).map((b) => b.region)).toEqual(["CHEST"]);
});
});
describe("labels", () => {
it("reads shirt numbers and handball officials' cards the same way", async () => {
const { normLabel } = await import("../src/jersey/service.js");
expect(normLabel("07")).toBe("7");
expect(normLabel(" 10 ")).toBe("10");
expect(normLabel("b")).toBe("B");
expect(normLabel("Oficial B")).toBe("B");
expect(normLabel("G")).toBeNull();
expect(normLabel("1234")).toBeNull();
expect(normLabel(null)).toBeNull();
});
});
describe("kit colour", () => {
it("takes the median colour in the middle of the chest, so a logo or stripe pulls it little", async () => {
const { kitColour } = await import("../src/jersey/crop.js");
const width = 100;
const height = 100;
const data = Buffer.alloc(width * height * 3);
for (let i = 0; i < width * height; i++) data.set([200, 20, 20], i * 3); // a red shirt
for (let y = 40; y < 46; y++) for (let x = 45; x < 55; x++) data.set([255, 255, 255], (y * width + x) * 3); // a white logo
expect(kitColour({ data, width, height, channels: 3 }, { x0: 0.2, y0: 0.2, x1: 0.8, y1: 0.9 })).toEqual([200, 20, 20]);
});
});
+1 -1
View File
@@ -13,7 +13,7 @@ export function apiUrlFor(configured: string | undefined, location: { protocol:
return "http://localhost:3000";
}
const API_URL = apiUrlFor(import.meta.env.VITE_API_URL as string | undefined, typeof window === "undefined" ? undefined : window.location);
export const API_URL = apiUrlFor(import.meta.env.VITE_API_URL as string | undefined, typeof window === "undefined" ? undefined : window.location);
export function createApi(onSessionLost: () => void): ApiClient {
return new ApiClient({
+121 -23
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { t } from "../i18n.js";
import { desktopInvoke, type Invoke, isDesktop } from "../platform.js";
import { API_URL } from "../api.js";
import { desktopInvoke, type Invoke, isDesktop, openExternal } from "../platform.js";
interface UpdateInfo {
version: string;
@@ -48,37 +49,134 @@ export function UiReadyNotice({ listen = tauriListen, enabled = isDesktop(), rel
);
}
/** Desktop only: a new version of the app's shell, installed with one click (it restarts). */
export function UpdateNotice({ invoke = desktopInvoke, enabled = isDesktop() }: { invoke?: Invoke; enabled?: boolean }) {
/** What the server offers when the app cannot update itself (or its own check failed). */
export interface ServerUpdate {
version: string;
currentVersion: string;
installer: string | null;
}
/** This computer's platform as the update endpoint names it (Mac builds are universal: one answer for both chips). */
function platform(): { target: string; arch: string } {
const ua = typeof navigator === "undefined" ? "" : navigator.userAgent;
if (/Mac OS X|Macintosh/.test(ua)) return { target: "darwin", arch: "aarch64" };
if (/Windows/.test(ua)) return { target: "windows", arch: "x86_64" };
return { target: "linux", arch: "x86_64" };
}
/** Asks the update endpoint directly, from the page: works whatever the installed shell can or cannot do. */
export async function askServer(apiUrl = API_URL): Promise<ServerUpdate | null> {
const currentVersion = await (await import("@tauri-apps/api/app")).getVersion();
const { target, arch } = platform();
const res = await fetch(`${apiUrl}/v1/desktop/update/${target}/${arch}/${encodeURIComponent(currentVersion)}`);
if (res.status !== 200) return null;
const body = (await res.json()) as { version?: string; installer?: string };
if (!body.version) return null;
return { version: body.version, currentVersion, installer: body.installer ?? null };
}
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
/**
* Desktop only: a new version of the app's shell, installed with one click (it restarts). When the installed shell
* cannot do that (its own check fails, or it was built without the update key), the page asks the server itself and
* offers the full installer instead, with the reason, so an update is never missed in silence.
*/
export function UpdateNotice({
invoke = desktopInvoke,
enabled = isDesktop(),
server = askServer,
open = openExternal,
}: {
invoke?: Invoke;
enabled?: boolean;
server?: () => Promise<ServerUpdate | null>;
open?: (url: string) => Promise<void>;
}) {
const [update, setUpdate] = useState<UpdateInfo | null>(null);
const [manual, setManual] = useState<(ServerUpdate & { reason: string | null }) | null>(null);
const [state, setState] = useState<"idle" | "installing" | "failed">("idle");
const [error, setError] = useState<string | null>(null);
const [dismissed, setDismissed] = useState(false);
useEffect(() => {
if (!enabled) return;
const check = () => void invoke<UpdateInfo | null>("update_check").then(setUpdate, () => {});
check();
const id = setInterval(check, EVERY_MS);
return () => clearInterval(id);
}, [enabled, invoke]);
let alive = true;
const check = async () => {
let reason: string | null = null;
try {
const found = await invoke<UpdateInfo | null>("update_check");
if (!alive) return;
if (found) {
setUpdate(found);
setManual(null);
return;
}
} catch (err) {
reason = message(err);
}
try {
const offered = await server();
if (alive && offered) setManual({ ...offered, reason });
} catch {
// No network: the next check tries again.
}
};
void check();
const id = setInterval(() => void check(), EVERY_MS);
return () => {
alive = false;
clearInterval(id);
};
}, [enabled, invoke, server]);
if (!update || dismissed) return null;
if (dismissed) return null;
if (update) {
return (
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
<span>{t.update.available(update.version, update.currentVersion)}</span>
{update.notes && <span className="truncate text-muted">{update.notes}</span>}
<button
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-50"
disabled={state === "installing"}
onClick={() => {
setState("installing");
setError(null);
invoke("update_install").catch((err: unknown) => {
setState("failed");
setError(message(err));
});
}}
>
{state === "installing" ? t.update.installing : t.update.install}
</button>
{state === "failed" && (
<span className="text-danger">
{t.update.failed}
{error ? ` (${error})` : ""}
</span>
)}
<button className="text-faint hover:text-ink" onClick={() => setDismissed(true)} aria-label={t.update.later}>
{t.update.later}
</button>
</div>
);
}
if (!manual) return null;
return (
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
<span>{t.update.available(update.version, update.currentVersion)}</span>
{update.notes && <span className="truncate text-muted">{update.notes}</span>}
<button
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-50"
disabled={state === "installing"}
onClick={() => {
setState("installing");
invoke("update_install").catch(() => setState("failed"));
}}
>
{state === "installing" ? t.update.installing : t.update.install}
</button>
{state === "failed" && <span className="text-danger">{t.update.failed}</span>}
<button className="text-faint hover:text-ink" onClick={() => setDismissed(true)} aria-label={t.update.later}>
<span>{t.update.available(manual.version, manual.currentVersion)}</span>
<span className="text-muted">{t.update.manual}</span>
{manual.reason && <span className="truncate text-faint">({manual.reason})</span>}
{manual.installer && (
<button
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong"
onClick={() => void open(manual.installer!)}
>
{t.update.download}
</button>
)}
<button className={`${manual.installer ? "" : "ml-auto "}text-faint hover:text-ink`} onClick={() => setDismissed(true)} aria-label={t.update.later}>
{t.update.later}
</button>
</div>
+23 -2
View File
@@ -56,15 +56,36 @@ describe("interface update notice", () => {
describe("update notice", () => {
it("offers a newer shell and installs it", async () => {
const invoke = vi.fn(async (cmd: string) => (cmd === "update_check" ? { version: "0.3.0", currentVersion: "0.2.0", notes: "Catálogo local" } : null)) as unknown as Invoke;
render(<UpdateNotice invoke={invoke} enabled />);
render(<UpdateNotice invoke={invoke} enabled server={async () => null} />);
expect(await screen.findByText("Nova versão da app: 0.3.0 (tens a 0.2.0).")).toBeTruthy();
fireEvent.click(screen.getByText("Instalar e reiniciar"));
expect(invoke).toHaveBeenCalledWith("update_install");
});
it("offers the installer when the app cannot update itself, with the reason", async () => {
const invoke = vi.fn(async () => {
throw new Error("Could not fetch a valid release JSON from the remote");
}) as unknown as Invoke;
const server = vi.fn(async () => ({ version: "0.3.7", currentVersion: "0.3.5", installer: "https://api.example/v1/desktop/download/1/PhotoReport.dmg" }));
const open = vi.fn(async () => {});
render(<UpdateNotice invoke={invoke} enabled server={server} open={open} />);
expect(await screen.findByText("Nova versão da app: 0.3.7 (tens a 0.3.5).")).toBeTruthy();
expect(screen.getByText("(Could not fetch a valid release JSON from the remote)")).toBeTruthy();
fireEvent.click(screen.getByText("Descarregar instalador"));
expect(open).toHaveBeenCalledWith("https://api.example/v1/desktop/download/1/PhotoReport.dmg");
});
it("asks the server too when the app itself finds nothing (a build without the update key)", async () => {
const invoke = vi.fn(async () => null) as unknown as Invoke;
const server = vi.fn(async () => ({ version: "0.3.7", currentVersion: "0.3.5", installer: null }));
render(<UpdateNotice invoke={invoke} enabled server={server} />);
expect(await screen.findByText("Nova versão da app: 0.3.7 (tens a 0.3.5).")).toBeTruthy();
expect(screen.queryByText("Descarregar instalador")).toBeNull();
});
it("stays quiet when there is nothing new, and outside the desktop app", async () => {
const invoke = vi.fn(async () => null) as unknown as Invoke;
const { container } = render(<UpdateNotice invoke={invoke} enabled />);
const { container } = render(<UpdateNotice invoke={invoke} enabled server={async () => null} />);
await waitFor(() => expect(invoke).toHaveBeenCalled());
expect(container.textContent).toBe("");
const never = vi.fn() as unknown as Invoke;
+10 -3
View File
@@ -351,6 +351,8 @@ export const t = {
install: "Instalar e reiniciar",
installing: "A instalar…",
failed: "Não foi possível instalar. Tenta mais tarde.",
manual: "Esta instalação não se atualiza sozinha: descarrega o instalador e abre-o (só desta vez).",
download: "Descarregar instalador",
later: "Mais tarde",
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
reload: "Recarregar agora",
@@ -378,8 +380,9 @@ export const t = {
numbers: {
title: "Números das camisolas",
counts: (pending: number, ok: number, bad: number) => `por rever ${pending} · certos ${ok} · ilegíveis ${bad}`,
keys: "⏎ certo · dígitos + ⏎ corrigir · X ilegível · S não é camisola · ⌫ desfazer",
cropAlt: "Tronco do jogador",
keys: "⏎ certo · dígitos (ou A–F, oficiais) + ⏎ corrigir · X ilegível · S não é camisola · ⌫ desfazer",
cropAlt: "Recorte do jogador",
region: { CHEST: "peito", SHORTS: "calção" } as Record<"CHEST" | "SHORTS", string>,
squadSays: (n: string) => `o plantel diz ${n}`,
right: "Certo",
other: "Outro número",
@@ -389,7 +392,11 @@ export const t = {
empty: "Nada por rever. Confirma grupos em Caras (com o número no plantel) e aparecem aqui os recortes.",
collected: (n: number) => `${n} recortes novos a partir das caras confirmadas.`,
perNumber: "Exemplos por número",
help: "Cada recorte é o tronco de alguém já identificado pela cara; o número vem do plantel. Diz se está certo, corrige, ou marca que não se lê. Uns milhares de exemplos chegam para treinar o modelo; quanto mais variados (números, equipas, ângulos), melhor.",
help: "Cada recorte é o peito ou o calção de alguém já identificado pela cara (no futebol o número da frente está no calção; no andebol, no peito); o número vem do plantel. Aqui ensinas a ler o número, não a reconhecer o jogador: só é \"Certo\" se o número se lê inteiro no recorte. Número tapado, cortado, só meio visível ou sem número: \"Não se lê\", mesmo que o jogador esteja certo. No andebol, os oficiais da equipa têm um cartão ao pescoço com uma letra (A a F; o B é normalmente o treinador principal): escreve a letra como se fosse o número. Uns milhares de exemplos chegam para treinar o modelo; quanto mais variados (números, equipas, ângulos), melhor.",
reset: "Recomeçar o ensino",
resetConfirm: (n: number) => `Apagar as ${n} respostas e rever tudo de novo`,
resetCancel: "Cancelar",
resetDone: (n: number) => `${n} respostas apagadas. Os recortes estão todos por rever.`,
download: "Descarregar conjunto de treino",
read: (n: string, votes: number) => `O modelo leu ${n} na camisola (${votes} ${votes === 1 ? "foto" : "fotos"})`,
},
+44 -4
View File
@@ -19,6 +19,7 @@ export function NumbersPage() {
const [done, setDone] = useState<JerseySample[]>([]);
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<string | null>(null);
const [confirmReset, setConfirmReset] = useState(false);
const loading = useRef(false);
const load = useCallback(async () => {
@@ -73,7 +74,11 @@ export function NumbersPage() {
if (isTyping(e.target) || e.metaKey || e.ctrlKey || e.altKey) return;
if (/^\d$/.test(e.key)) {
e.preventDefault();
setTyped((x) => (x + e.key).slice(-3));
setTyped((x) => (/^\d*$/.test(x) ? x + e.key : e.key).slice(-3));
} else if (/^[a-f]$/i.test(e.key)) {
// A handball official's card (Oficial A..F): one letter, never mixed with digits.
e.preventDefault();
setTyped(e.key.toUpperCase());
} else if (e.key === "Enter") {
e.preventDefault();
void answer("CONFIRMED", typed || undefined);
@@ -113,7 +118,10 @@ export function NumbersPage() {
<div className="mx-auto grid max-w-6xl gap-6 p-6 max-sm:p-3 lg:grid-cols-[1fr_320px]">
<section className="border border-line bg-panel">
<div className="panel-head">
<span>{current?.person ?? t.numbers.title}</span>
<span>
{current?.person ?? t.numbers.title}
{current && <span className="ml-2 border border-black bg-cell px-1.5 py-0.5 text-[10px] text-muted">{t.numbers.region[current.region]}</span>}
</span>
<span className="normal-case tracking-normal text-faint">{t.numbers.keys}</span>
</div>
{note && <p className="px-4 pt-3 text-[12px] text-muted">{note}</p>}
@@ -131,9 +139,13 @@ export function NumbersPage() {
<input
aria-label={t.numbers.other}
placeholder={t.numbers.other}
inputMode="numeric"
inputMode="text"
value={typed}
onChange={(e) => setTyped(e.target.value.replace(/\D/g, "").slice(0, 3))}
onChange={(e) => {
const v = e.target.value.toUpperCase();
const letter = /[A-F]/.exec(v)?.[0];
setTyped(letter ?? v.replace(/\D/g, "").slice(0, 3));
}}
onKeyDown={(e) => e.key === "Enter" && void answer("CONFIRMED", typed || undefined)}
className="h-9 w-28 border border-black bg-[#161617] px-2 text-center font-mono text-[15px] text-ink"
/>
@@ -178,6 +190,34 @@ export function NumbersPage() {
{!stats?.numbers.length && <span className="text-[12px] text-faint">—</span>}
</div>
</section>
{role !== null && hasRole(role, "EDITOR") && (c.CONFIRMED ?? 0) + (c.ILLEGIBLE ?? 0) + (c.SKIPPED ?? 0) > 0 && (
<section className="border border-line bg-panel p-3">
{confirmReset ? (
<div className="flex flex-col gap-2">
<button
className="h-9 w-full bg-danger px-3 text-[13px] font-semibold text-white"
onClick={() => {
void api.resetJerseySamples(orgId).then((r) => {
setConfirmReset(false);
setDone([]);
setNote(t.numbers.resetDone(r.reset));
void load();
});
}}
>
{t.numbers.resetConfirm((c.CONFIRMED ?? 0) + (c.ILLEGIBLE ?? 0) + (c.SKIPPED ?? 0))}
</button>
<button className="text-[12px] text-faint underline" onClick={() => setConfirmReset(false)}>
{t.numbers.resetCancel}
</button>
</div>
) : (
<button className="h-9 w-full border border-black bg-cell text-[13px] text-muted hover:text-ink" onClick={() => setConfirmReset(true)}>
{t.numbers.reset}
</button>
)}
</section>
)}
{role !== null && hasRole(role, "EDITOR") && (
<button className="h-9 w-full bg-accent font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong" onClick={() => void download()}>
{t.numbers.download}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.7",
"version": "0.3.8",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.7"
version = "0.3.8"
edition = "2024"
publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
+2 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.7",
"version": "0.3.8",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
@@ -23,7 +23,7 @@
}
],
"security": {
"csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost https://*.photoreport.pt wss://*.photoreport.pt http://localhost:3000 ws://localhost:3000; img-src 'self' data: blob: https://*.photoreport.pt http://localhost:3000; style-src 'self' 'unsafe-inline'; font-src 'self' data:"
"csp": "default-src 'self'; script-src 'self' 'wasm-unsafe-eval' blob:; worker-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost https://*.photoreport.pt wss://*.photoreport.pt http://localhost:3000 ws://localhost:3000; img-src 'self' data: blob: https://*.photoreport.pt http://localhost:3000; style-src 'self' 'unsafe-inline'; font-src 'self' data:"
}
},
"bundle": {
@@ -35,3 +35,27 @@ fn every_registered_command_is_allowed_for_the_web_app() {
);
}
}
/// The interface runs from disk under the app's own CSP: the photo editor's engine is WebAssembly, started in a
/// worker. Without 'wasm-unsafe-eval' Revelar says the engine is missing (as it did in 0.3.6 and 0.3.7).
#[test]
fn the_csp_lets_the_editor_engine_run() {
let conf = read("tauri.conf.json");
let csp = conf
.split("\"csp\": \"")
.nth(1)
.and_then(|s| s.split('"').next())
.expect("csp");
let script = csp
.split(';')
.map(str::trim)
.find(|d| d.starts_with("script-src"))
.expect("script-src");
assert!(script.contains("'wasm-unsafe-eval'"), "{script}");
let worker = csp
.split(';')
.map(str::trim)
.find(|d| d.starts_with("worker-src"))
.expect("worker-src");
assert!(worker.contains("'self'"), "{worker}");
}
+15 -4
View File
@@ -193,8 +193,10 @@ face in it gets the name in Players, which goes to IPTC Title and Persons Shown;
join the group are named on arrival. Suggestions never name photos on their own. Groups can be merged or ignored
(public, staff). Measured locally on 2 cores: about 1 s per photo with AuraFace.
Shirt numbers come from our own model, because general OCR doesn't read shirts. The torso under each
confirmed face becomes a training sample, labelled with the squad's number. People check these samples in
Shirt numbers come from our own model, because general OCR doesn't read shirts. Under each confirmed face two
crops become training samples, labelled with the squad's number: the chest (handball kits carry the front number
there) and waist to mid-thigh (football: Liga Portugal 2026/27 shirts have no chest number, the front number is on
one leg of the shorts, as a sample of 14 clubs showed). The worker reads both and keeps the more confident reading. People check these samples in
"Números das camisolas". `workers/ml/jersey` trains a ResNet18 on the checked samples (on a Mac with MPS) and
exports it to ONNX.
@@ -202,8 +204,17 @@ With `JERSEY_MODEL_DIR` set, the worker reads the number of every clear face thr
CPU. A group's number is the one more than half of its clear readings agree on; it is shown as `#10` on the
group.
When a group has no face match, it is suggested as the squad player who wears that number in either team of
the event. This happens only when exactly one player matches, and the score is 0.9 × the mean reading.
Face and number are used together:
- **Face sure, number agrees (or none read):** the face's suggestion.
- **Face sure, number clearly another (two or more readings):** still the face's suggestion, at 0.8 × its score.
- **Face not sure (weak, or two people too close):** among the people the face is near to, the one whose number was
read; else the squad player who wears that number in either team of the event (0.9 × the mean reading).
- **Both teams have that number:** the kit colour decides. Each face keeps the median colour of the middle of its
chest; each team's colour is the median of its players already confirmed in the event (goalkeepers left out).
The group goes to the team whose colour is clearly closer, never when the two kits are alike or the group's
colour sits in between.
Suggestions still never name anyone on their own.
Next: back-of-shirt numbers. These are players with no face visible, and they need a box detector trained on
+5
View File
@@ -565,6 +565,11 @@ export class ApiClient {
return this.request<JerseySample>("POST", `/v1/jersey/samples/${id}/review`, { status, ...(label !== undefined && { label }) });
}
/** Teaching starts over: every answer is dropped, the samples are to review again. */
resetJerseySamples(orgId: string) {
return this.request<{ reset: number }>("POST", `/v1/orgs/${orgId}/jersey/reset`);
}
/** The checked dataset as a JSON file (crops by signed URL), for workers/ml/jersey. */
jerseyDatasetUrl(orgId: string) {
return `/v1/orgs/${orgId}/jersey/dataset`;
+2
View File
@@ -332,6 +332,8 @@ export interface JerseySample {
suggested: string | null;
label: string | null;
status: "PENDING" | "CONFIRMED" | "ILLEGIBLE" | "SKIPPED";
/** Where on the player the crop is: chest (handball) or shorts (football). */
region: "CHEST" | "SHORTS";
crop: string;
}
+5 -2
View File
@@ -7,8 +7,11 @@ ONNX. The worker then runs that ONNX file on the CPU, so the server needs no GPU
The loop:
1. **Collect.** Every face in a group confirmed as a squad player who has a number becomes a sample: the torso
crop, labelled with the squad's number.
1. **Collect.** Every face in a group confirmed as a squad player who has a number becomes two samples, both
labelled with the squad's number: the chest (where handball kits carry the front number) and the shorts (where
football kits carry it; Liga Portugal shirts have none on the chest).
Handball team officials wear an accreditation card with a letter (Oficial A to F; B is usually the head coach). Give
an official the letter as their number ("B") and their cards are learnt and read like shirt numbers.
2. **Check.** In the app, go to **Caras → Números das camisolas**. The keys are:
- ⏎ the number is right;
- digits then ⏎ to correct it;
+31 -3
View File
@@ -7,7 +7,7 @@ Each sample is a torso-like crop with a number painted on it: on a real crop (so
look real) or on a plain shirt colour. The number is drawn in a sporty font, in a colour that stands out, sometimes
outlined, then warped like cloth: tilted, in perspective, rippled, blurred. It is written to <out>/<id>.jpg and listed in
<out>/dataset.json, in the same format as the dataset from the app (label = the number, or "illegible" for shirts
painted without one). Mix it with the real dataset in train.py (--extra); the check keeps using real crops only.
painted without one); now and then the crop gets a team official's card with a letter A-F instead (handball). Mix it with the real dataset in train.py (--extra); the check keeps using real crops only.
Fonts: any .ttf/.otf/.woff in --fonts. Free sporty ones (Oswald, Anton, Bebas Neue, Teko, Saira Condensed, ...)
come from npm: `npm pack @fontsource/oswald` and so on.
@@ -97,6 +97,21 @@ def _perspective(src, dst):
return np.linalg.solve(a, b).tolist()
def badge(letter: str, font_path: Path, rng: random.Random) -> Image.Image:
"""A team official's accreditation card (handball): a pale card with a big letter, on a lanyard."""
cw = int(H * rng.uniform(0.22, 0.34))
ch = int(cw * rng.uniform(1.3, 1.6))
card = Image.new("RGBA", (cw, ch), (0, 0, 0, 0))
d = ImageDraw.Draw(card)
paper = tuple(rng.randint(225, 255) for _ in range(3))
d.rounded_rectangle([0, 0, cw - 1, ch - 1], radius=max(2, cw // 12), fill=paper + (255,), outline=(120, 120, 120, 255))
d.rectangle([0, 0, cw, int(ch * rng.uniform(0.18, 0.3))], fill=tuple(rng.randint(0, 200) for _ in range(3)) + (255,))
ink = rng.choice([(0, 0, 0), (20, 20, 60), (60, 0, 0)])
glyph = number_layer(letter, font_path, int(ch * rng.uniform(0.32, 0.45)), ink, None, rng)
card.paste(glyph, ((cw - glyph.width) // 2, int(ch * 0.62) - glyph.height // 2), glyph)
return card.rotate(rng.uniform(-12, 12), resample=Image.BICUBIC, expand=True)
def sample(rng: random.Random, backgrounds: list[Path], fonts: list[Path], with_number: bool):
if backgrounds and rng.random() < 0.6:
bg = Image.open(rng.choice(backgrounds)).convert("RGB")
@@ -106,15 +121,28 @@ def sample(rng: random.Random, backgrounds: list[Path], fonts: list[Path], with_
w = bg.width
if not with_number:
return bg, "illegible"
if rng.random() < 0.08: # an official's card instead of a shirt number
letter = rng.choice("ABCDEF")
card = badge(letter, rng.choice(fonts), rng)
x = int((w - card.width) / 2 + rng.uniform(-0.2, 0.2) * w)
x = max(0, min(w - card.width, x))
y = int(H * rng.uniform(0.15, 0.6))
d = ImageDraw.Draw(bg)
d.line([(x + card.width // 2, 0), (x + card.width // 2, y)], fill=tuple(rng.randint(0, 255) for _ in range(3)), width=3)
bg.paste(card, (x, y), card)
return bg, letter
n = rng.choice([rng.randint(1, 30), rng.randint(1, 30), rng.randint(0, 99)])
region = bg.crop((w // 3, H // 4, 2 * w // 3, H // 2)).resize((1, 1)).getpixel((0, 0))
fill = contrasting(region, rng)
outline = contrasting(fill, rng) if rng.random() < 0.3 else None
height = int(H * rng.uniform(0.22, 0.48))
# Big on a chest crop (handball); small and to one side on a shorts crop (football).
shorts = rng.random() < 0.4
height = int(H * (rng.uniform(0.12, 0.26) if shorts else rng.uniform(0.22, 0.48)))
layer = warp(number_layer(str(n), rng.choice(fonts), height, fill, outline, rng), rng)
if layer.width > w * 0.95:
layer = layer.resize((int(w * 0.95), int(layer.height * w * 0.95 / layer.width)))
x = int((w - layer.width) / 2 + rng.uniform(-0.15, 0.15) * w)
x = int((w - layer.width) / 2 + rng.uniform(-0.3, 0.3) * w) if shorts else int((w - layer.width) / 2 + rng.uniform(-0.15, 0.15) * w)
x = max(0, min(w - layer.width, x))
y = int(H * rng.uniform(0.05, 0.55))
bg.paste(layer, (x, y), layer)
# an arm or the ball across a corner, now and then (never most of the number)
+42 -22
View File
@@ -3,10 +3,12 @@
python train.py --dataset jersey-dataset-2026-10-12.json --api https://api.photoreport.pt --out models/jersey-v1
The model looks at the torso crop under a face and reads it digit by digit: is there a legible number, 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. The exported model still answers
one probability per number 0-99 plus "illegible" (the worker does not need to know how it reads).
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).
@@ -29,7 +31,9 @@ from torch.utils.data import DataLoader, Dataset
from torchvision import models, transforms
SIZE = 160
LABELS = [str(n) for n in range(100)] + ["illegible"]
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]
@@ -92,17 +96,27 @@ ILLEGIBLE = len(LABELS) - 1
IGNORE = -100
def targets(y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Class index -> (legible 0/1, tens 0=none or 1+digit, units digit); digits are ignored for illegible crops."""
legible = (y != ILLEGIBLE).long()
n = torch.where(legible.bool(), y, torch.zeros_like(y))
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
return legible, torch.where(legible.bool(), tens, IGNORE), torch.where(legible.bool(), units, IGNORE)
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 three small heads: legible?, tens digit (or none), units digit."""
"""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__()
@@ -110,17 +124,18 @@ class DigitReader(nn.Module):
m.fc = nn.Identity()
self.backbone = m
self.drop = nn.Dropout(0.3)
self.legible = nn.Linear(512, 2)
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.legible(f), self.tens(f), self.units(f)
return self.kind(f), self.tens(f), self.units(f), self.letter(f)
class NumberProbs(nn.Module):
"""For export: digit probabilities -> one probability per label (0..99, illegible), the format the worker reads."""
"""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__()
@@ -134,17 +149,18 @@ class NumberProbs(nn.Module):
self.register_buffer("tens_mask", mask)
def forward(self, x):
legible, tens, units = self.reader(x)
p_leg = torch.softmax(legible, 1)
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_leg[:, 1:2] * p_tens[:, self.tens_idx] * p_units[:, self.units_idx]
return torch.cat([numbers, p_leg[:, 0:1]], 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 or illegible), and of the number alone on legible crops."""
"""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
@@ -194,10 +210,14 @@ def main():
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):
legible, tens, units = targets(y)
lo_leg, lo_tens, lo_units = out
return ce(lo_leg, legible) + ce(lo_tens, tens) + ce(lo_units, units)
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))