import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import sharp from "sharp"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js"; import { normalize } from "../src/faces/math.js"; import { FaceService } from "../src/faces/service.js"; import { IngestService } from "../src/ingest/service.js"; import { MemoryBroadcaster } from "../src/realtime.js"; import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; const quiet = { info: () => {}, warn: () => {} }; /** A person's "face": a fixed direction in embedding space plus a little noise per photo. */ function personVector(seed: number, noise = 0): number[] { // Deterministic pseudo-random directions (64 dims): different people land far apart, like real embeddings. const rand = (k: number) => { const x = Math.sin(k * 127.1 + 311.7) * 43758.5453; return (x - Math.floor(x)) * 2 - 1; }; const v = Array.from({ length: 64 }, (_, i) => rand(seed * 1000 + i) + (noise ? rand(noise * 7919 + i) * 0.15 : 0)); return normalize(v); } /** Answers with the faces registered for each stored file (keyed by the file's sha256 in its path). */ class FakeEngine implements FaceEngine { readonly model = "auraface-v1"; readonly byColor = new Map(); calls = 0; async analyse(file: string): Promise { this.calls++; const sha = path.basename(file).split(".")[0]!; return this.byColor.get(sha) ?? { width: 600, height: 400, faces: [] }; } async close(): Promise {} } describe("faces", () => { let ctx: TestContext; let dir: string; let ingestRoot: string; let ingest: IngestService; let faces: FaceService; let engine: FakeEngine; const broadcaster = new MemoryBroadcaster(); beforeAll(async () => { dir = await mkdtemp(path.join(tmpdir(), "pr-faces-")); ingestRoot = path.join(dir, "ingest"); ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }, broadcaster); const storage = new LocalStorage(ctx.config.STORAGE_ROOT); engine = new FakeEngine(); ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner(ctx.config.JWT_SECRET, 3600), broadcaster, ingestRoot, log: quiet }); faces = new FaceService({ db: ctx.db, storage, broadcaster, log: quiet, engine }); }); afterAll(async () => { await ctx.app.close(); await ctx.db.$disconnect(); await rm(dir, { recursive: true, force: true }); }); beforeEach(async () => { await resetDb(ctx.db); broadcaster.sent.length = 0; engine.byColor.clear(); }); async function setup(biometrics = true) { const { org, user } = await seedUser(ctx.db, "owner@fpa.pt", { org: "fpa", role: "OWNER" }); const token = (await login(ctx.app, "owner@fpa.pt")).body.accessToken; if (biometrics) { const r = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${org!.id}/biometrics`, headers: bearer(token), payload: { enabled: true, legalBasis: "Uso interno da federação para notícias e galerias (contrato)." } }); expect(r.statusCode).toBe(200); } await ctx.db.ftpAccount.create({ data: { organizationId: org!.id, userId: user.id, login: "cam" } }); const mk = async (home: string, startsAt: string) => (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/events`, headers: bearer(token), payload: { home, away: "AAAS", startsAt } })).json() as { id: string }; const day1 = await mk("VSC", "2026-09-23T19:30:00Z"); const day2 = await mk("ABC", "2026-09-30T19:30:00Z"); return { orgId: org!.id, token, day1, day2 }; } /** Ingests a photo with the given people's faces in it. */ let n = 0; async function photo(taken: string, people: number[], sharpness: number | null | (number | null)[] = 200): Promise { n++; const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: n % 256, g: (n * 7) % 256, b: (n * 13) % 256 } } }) .jpeg() .withExif({ IFD2: { DateTimeOriginal: taken } }) .toBuffer(); const file = path.join(ingestRoot, "cam", `IMG_${n}.jpg`); await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, data); const { createHash } = await import("node:crypto"); const sha = createHash("sha256").update(data).digest("hex"); engine.byColor.set(sha, { width: 600, height: 400, faces: people.map((p, i) => ({ x0: 0.1 + i * 0.2, y0: 0.2, x1: 0.18 + i * 0.2, y1: 0.32, score: 0.9, sharpness: Array.isArray(sharpness) ? sharpness[i]! : sharpness, landmarks: [], embedding: personVector(p, n) })), }); const out = await ingest.ingestFile(file); if (out.status !== "ingested") throw new Error(JSON.stringify(out)); return out.photoId; } async function drain() { for (let ids = await faces.claim(10); ids.length; ids = await faces.claim(10)) for (const id of ids) await faces.process(id); } it("does nothing without biometrics switched on, and needs a legal basis to switch them on", async () => { const { orgId, token } = await setup(false); await photo("2026:09:23 21:00:00", [1]); expect(await faces.claim(5)).toEqual([]); const refused = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/biometrics`, headers: bearer(token), payload: { enabled: true } }); expect(refused.json()).toMatchObject({ error: "legal_basis_required" }); }); it("analyses the photos already here once biometrics are switched on", async () => { const { orgId, token } = await setup(false); const id = await photo("2026:09:23 21:00:00", [1]); expect(await faces.claim(5)).toEqual([]); const on = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/biometrics`, headers: bearer(token), payload: { enabled: true, legalBasis: "Contrato com a federação." } }); expect(on.statusCode).toBe(200); expect(await faces.claim(5)).toEqual([id]); }); it("queues photos left without analysis while biometrics are on, and leaves other organizations alone", async () => { await setup(true); const id = await photo("2026:09:23 21:00:00", [1]); expect(await faces.claim(5)).toEqual([id]); await drain(); // A photo that slipped through as "no analysis" (it arrived while a toggle raced its ingest). await ctx.db.photo.update({ where: { id }, data: { facesStatus: "NONE" } }); const other = await seedUser(ctx.db, "outro@clube.pt", { org: "clube", role: "OWNER" }); const theirs = await ctx.db.photo.create({ data: { organizationId: other.org!.id, source: "UPLOAD", originalName: "x.jpg", sha256: "f".repeat(64), byteSize: 1, storageKey: "x", status: "READY" } }); expect(await faces.queueMissed()).toBe(1); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id } })).facesStatus).toBe("PENDING"); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: theirs.id } })).facesStatus).toBe("NONE"); }); it("reads the faces again from the original when it replaces a desktop preview", async () => { const { orgId } = await setup(); const user = await ctx.db.user.findFirstOrThrow(); const original = await sharp({ create: { width: 1200, height: 800, channels: 3, background: "#345" } }).jpeg().toBuffer(); const { createHash } = await import("node:crypto"); const sha256 = createHash("sha256").update(original).digest("hex"); const preview = path.join(dir, "preview.jpg"); await writeFile(preview, await sharp(original).resize(600).jpeg().toBuffer()); const sent = await ingest.ingest(preview, { organizationId: orgId, userId: user.id, source: "DESKTOP", originalName: "IMG_9.JPG", original: { sha256, size: original.length } }); await drain(); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: sent.photoId } })).facesStatus).toBe("DONE"); const full = path.join(dir, "IMG_9.JPG"); await writeFile(full, original); await ingest.ingest(full, { organizationId: orgId, userId: user.id, source: "DESKTOP", originalName: "IMG_9.JPG" }); expect(await faces.claim(5)).toEqual([sent.photoId]); }); it("groups faces of the same person within an event", async () => { const { token, day1 } = await setup(); await photo("2026:09:23 21:00:00", [1, 2]); await photo("2026:09:23 21:01:00", [1]); await photo("2026:09:23 21:02:00", [2, 3]); await drain(); const res = await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) }); const { groups, pending } = res.json() as { groups: { size: number; samples: unknown[] }[]; pending: number }; expect(pending).toBe(0); expect(groups.map((g) => g.size)).toEqual([2, 2, 1]); expect(groups[0]!.samples).toHaveLength(2); expect(broadcaster.sent.some((s) => s.message.type === "faces.updated")).toBe(true); }); it("lists the groups to name surest suggestion first, then the ones with nothing to go by", async () => { const { token, day1 } = await setup(); await photo("2026:09:23 21:00:00", [1, 2]); await photo("2026:09:23 21:01:00", [1, 2]); await photo("2026:09:23 21:02:00", [3]); await drain(); const listed = async () => ((await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { id: string }[] }).groups.map((g) => g.id); const [big1, big2, small] = await listed(); const org = (await ctx.db.event.findUniqueOrThrow({ where: { id: day1.id } })).organizationId; const rui = await ctx.db.person.create({ data: { organizationId: org, name: "Rui" } }); const ana = await ctx.db.person.create({ data: { organizationId: org, name: "Ana" } }); // The smallest group has the surest suggestion: it goes first; a weaker one next; nothing suggested last. await ctx.db.faceGroup.update({ where: { id: small! }, data: { suggestedPersonId: rui.id, suggestionScore: 0.66 } }); await ctx.db.faceGroup.update({ where: { id: big2! }, data: { suggestedPersonId: ana.id, suggestionScore: 0.49 } }); expect(await listed()).toEqual([small, big2, big1]); }); it("joins the cards named as the same person into one, and learns from all of them", async () => { const { token, day1 } = await setup(); await photo("2026:09:23 21:00:00", [1, 2]); await photo("2026:09:23 21:01:00", [1, 3]); await drain(); const list = async () => ((await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { id: string; size: number; person: { name: string } | null }[] }).groups; const before = await list(); expect(before).toHaveLength(3); // Two different-looking groups are both him (another angle, another light). for (const g of before.filter((x) => x.size === 1)) { await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g.id}/confirm`, headers: bearer(token), payload: { name: "Schjelderup" } }); } const after = await list(); const his = after.filter((g) => g.person?.name === "Schjelderup"); expect(his).toHaveLength(1); expect(his[0]!.size).toBe(2); expect((await ctx.db.person.findFirstOrThrow({ where: { name: "Schjelderup" } })).faceCount).toBe(2); }); it("names every photo of a confirmed group, and later photos as they arrive", async () => { const { token, day1 } = await setup(); const a = await photo("2026:09:23 21:00:00", [1, 2]); const b = await photo("2026:09:23 21:01:00", [1]); await drain(); const { groups } = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { id: string; size: number }[] }; const miguel = groups.find((g) => g.size === 2)!; const confirmed = await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${miguel.id}/confirm`, headers: bearer(token), payload: { name: "Miguel Silva (VSC)", club: "VSC", number: "7" } }); expect(confirmed.json()).toMatchObject({ person: { name: "Miguel Silva (VSC)", number: "7" } }); const players = async (id: string) => (await ctx.db.photo.findUniqueOrThrow({ where: { id } })).players; expect(await players(a)).toEqual(["Miguel Silva (VSC)"]); expect(await players(b)).toEqual(["Miguel Silva (VSC)"]); const later = await photo("2026:09:23 21:30:00", [1]); await drain(); expect(await players(later)).toEqual(["Miguel Silva (VSC)"]); const faceList = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${later}/faces`, headers: bearer(token) })).json() as { faces: { person: { name: string } | null }[] }; expect(faceList.faces[0]?.person?.name).toBe("Miguel Silva (VSC)"); }); it("suggests people already confirmed in earlier events, without naming photos until confirmed", async () => { const { token, day1, day2 } = await setup(); await photo("2026:09:23 21:00:00", [1]); await drain(); const g1 = ((await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { id: string }[] }).groups[0]!; await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g1.id}/confirm`, headers: bearer(token), payload: { name: "Miguel Silva (VSC)" } }); const next = await photo("2026:09:30 21:00:00", [1]); await drain(); const { groups } = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day2.id}/face-groups`, headers: bearer(token) })).json() as { groups: { id: string; suggestion: { name: string; score: number } | null; person: unknown }[] }; expect(groups[0]).toMatchObject({ person: null, suggestion: { name: "Miguel Silva (VSC)" } }); expect(groups[0]!.suggestion!.score).toBeGreaterThan(0.9); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: next } })).players).toEqual([]); // Search: the person is named in day 1 and suggested (not named) in day 2; names and teams are searchable. const personId = groups[0]!.suggestion!.name ? ((await ctx.app.inject({ method: "GET", url: `/v1/events/${day2.id}/face-groups`, headers: bearer(token) })).json() as { groups: { suggestion: { id: string } }[] }).groups[0]!.suggestion.id : ""; const orgId = (await ctx.db.photo.findUniqueOrThrow({ where: { id: next } })).organizationId; const found = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/search?personId=${personId}`, headers: bearer(token) })).json() as { photos: { id: string }[]; suggested: { id: string }[] }; expect(found.photos).toHaveLength(1); expect(found.suggested.map((p) => p.id)).toEqual([next]); expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/search?q=miguel`, headers: bearer(token) })).json() as { total: number }).total).toBe(1); expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/search?q=abc%20aaas`, headers: bearer(token) })).json() as { total: number }).total).toBe(1); expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/search?q=vsc&from=2026-09-24`, headers: bearer(token) })).json() as { total: number }).total).toBe(0); const people = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day2.id}/face-groups`, headers: bearer(token) })).json() as { groups: { suggestion: { id: string } }[] }; await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${groups[0]!.id}/confirm`, headers: bearer(token), payload: { personId: people.groups[0]!.suggestion.id } }); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: next } })).players).toEqual(["Miguel Silva (VSC)"]); }); it("merges two groups of the same person and ignores people not to name", async () => { const { token, day1 } = await setup(); await photo("2026:09:23 21:00:00", [1, 5]); await photo("2026:09:23 21:01:00", [1]); await drain(); const list = async () => ((await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { id: string; size: number; ignored: boolean }[] }).groups; const [big, small] = await list(); const merged = await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${small!.id}/merge`, headers: bearer(token), payload: { into: big!.id } }); expect(merged.statusCode).toBe(200); expect((await list()).map((g) => g.size)).toEqual([3]); await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${big!.id}/ignore`, headers: bearer(token), payload: { ignored: true } }); expect((await list())[0]!.ignored).toBe(true); }); it("only identifies faces in focus: not soft photos, not the blurred crowd behind a sharp player", async () => { const { token, day1 } = await setup(); await photo("2026:09:23 21:00:00", [1]); // The player sharp, two fans in the stand behind him out of focus (textured, but far softer). const withCrowd = await photo("2026:09:23 21:01:00", [1, 8, 9], [400, 60, 50]); await photo("2026:09:23 21:02:00", [8], 12); await photo("2026:09:23 21:03:00", [9], 12); await drain(); const body = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { size: number }[]; unclear: number }; expect(body.groups.map((g) => g.size)).toEqual([2]); expect(await ctx.db.face.count()).toBe(2); const boxes = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${withCrowd}/faces`, headers: bearer(token) })).json() as { faces: unknown[] }; expect(boxes.faces).toHaveLength(1); }); it("learns a person from a reference photo and suggests them from the first match", async () => { const { orgId, token, day1 } = await setup(); const created = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/persons`, headers: bearer(token), payload: { name: "Rui Costa (ABC)", club: "ABC", number: "31" } }); expect(created.statusCode).toBe(201); const person = created.json() as { id: string }; // The fake engine finds faces by the stored file's name: .jpg for references. engine.byColor.set(person.id, { width: 800, height: 1000, faces: [{ x0: 0.3, y0: 0.2, x1: 0.7, y1: 0.6, score: 0.95, sharpness: 300, landmarks: [], embedding: personVector(3) }] }); const jpeg = await sharp({ create: { width: 800, height: 1000, channels: 3, background: "#888" } }).jpeg().toBuffer(); const boundary = "----pr-ref"; const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="rui.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`); const up = await ctx.app.inject({ method: "PUT", url: `/v1/persons/${person.id}/reference`, headers: { ...bearer(token), "content-type": `multipart/form-data; boundary=${boundary}` }, payload: Buffer.concat([head, jpeg, Buffer.from(`\r\n--${boundary}--\r\n`)]), }); expect(up.json()).toMatchObject({ status: "PENDING" }); for (const id of await faces.claimReferences(5)) await faces.processReference(id); const listed = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/persons`, headers: bearer(token) })).json() as { people: { reference: { status: string; url: string } }[] }; expect(listed.people[0]!.reference.status).toBe("DONE"); const file = await ctx.app.inject({ method: "GET", url: listed.people[0]!.reference.url }); expect(file.statusCode).toBe(200); expect(file.headers["content-type"]).toBe("image/jpeg"); await photo("2026:09:23 21:00:00", [3]); await drain(); const { groups } = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { suggestion: { name: string } | null; person: unknown }[] }; expect(groups[0]).toMatchObject({ person: null, suggestion: { name: "Rui Costa (ABC)" } }); }); it("refuses reference photos while biometrics are off", async () => { const { orgId, token } = await setup(false); const person = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/persons`, headers: bearer(token), payload: { name: "Rui Costa (ABC)" } })).json() as { id: string }; const r = await ctx.app.inject({ method: "PUT", url: `/v1/persons/${person.id}/reference`, headers: bearer(token) }); expect(r.json()).toMatchObject({ error: "biometrics_disabled" }); }); it("turns confirmed faces into shirt-number samples to check, and exports the checked ones", async () => { const { token, day1 } = await setup(); await photo("2026:09:23 21:00:00", [1]); await photo("2026:09:23 21:01:00", [1]); await drain(); const g = ((await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { id: string }[] }).groups[0]!; 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(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(512); // Collecting again adds nothing. expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/samples`, headers: bearer(token) })).json() as { collected: number }).collected).toBe(0); const ok = await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[0]!.id}/review`, headers: bearer(token), payload: { status: "CONFIRMED" } }); expect(ok.json()).toMatchObject({ status: "CONFIRMED", label: "7" }); 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 () => { const { token, day1 } = await setup(); const orgId = (await ctx.db.organization.findFirstOrThrow()).id; await ctx.db.person.createMany({ data: [ { organizationId: orgId, name: "Rui Costa", club: "VSC", number: "10" }, { organizationId: orgId, name: "Outro Dez", club: "Benfica", number: "10" }, { organizationId: orgId, name: "Zé Sete", club: "VSC", number: "7" }, ], }); // 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; 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(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 }[]; }; expect(groups).toHaveLength(1); expect(groups[0]!.number).toMatchObject({ value: "10", votes: 2 }); // Benfica's 10 isn't playing; the suggestion waits for someone to confirm it. expect(groups[0]!.suggestion).toMatchObject({ name: "Rui Costa" }); expect(groups[0]!.suggestion!.score).toBeCloseTo(0.855, 3); 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(); }); it("is surer when face and shirt agree on the same player", async () => { const { token, day1, day2 } = await setup(); await photo("2026:09:23 21:00:00", [1]); await drain(); const listed = (eventId: string) => ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/face-groups`, headers: bearer(token) }).then((r) => r.json() as { groups: { id: string; person: unknown; suggestion: { name: string; score: number } | null }[] }); const [g] = (await listed(day1.id)).groups; await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g!.id}/confirm`, headers: bearer(token), payload: { name: "Miguel Silva", club: "VSC", number: "7" } }); // A week later: the face alone. await photo("2026:09:30 21:00:00", [1]); await photo("2026:09:30 21:01:00", [1]); await drain(); const later = (await listed(day2.id)).groups[0]!; const byFace = later.suggestion!; expect(byFace.name).toBe("Miguel Silva"); // The shirt reads 7 too. await ctx.db.face.updateMany({ where: { groupId: later.id }, data: { jerseyNumber: "7", jerseyScore: 0.9 } }); await faces.refreshSuggestions(day2.id); const both = (await listed(day2.id)).groups[0]!.suggestion!; expect(both.name).toBe("Miguel Silva"); expect(both.score).toBeGreaterThan(byFace.score); expect(both.score).toBeLessThanOrEqual(0.99); }); it("claims a boosted photo ahead of an older one", async () => { const { orgId, day1 } = await setup(); await ctx.db.photo.create({ data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: "old.jpg", sha256: "a".repeat(64), byteSize: 1, storageKey: "old", status: "READY", facesStatus: "PENDING", createdAt: new Date("2026-10-01T00:00:00Z") }, }); const newer = await ctx.db.photo.create({ data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: "new.jpg", sha256: "b".repeat(64), byteSize: 1, storageKey: "new", status: "READY", facesStatus: "PENDING", facesBoostedAt: new Date(), createdAt: new Date("2026-10-02T00:00:00Z"), }, }); expect(await faces.claim(1)).toEqual([newer.id]); }); it("reads the last month before an older gallery that arrived later", async () => { const { orgId, day1 } = await setup(); const photo = (name: string, capturedAt: Date, createdAt: Date) => ctx.db.photo.create({ data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: name, sha256: name.padEnd(64, "0"), byteSize: 1, storageKey: name, status: "READY", facesStatus: "PENDING", capturedAt, createdAt, }, }); const archive = await photo("archive.jpg", new Date("2024-03-01T15:00:00Z"), new Date()); const recent = await photo("recent.jpg", new Date(Date.now() - 2 * 24 * 60 * 60_000), new Date(Date.now() - 5 * 24 * 60 * 60_000)); const waiting = await photo("waiting.jpg", new Date("2023-11-01T15:00:00Z"), new Date(Date.now() - 2 * 24 * 60 * 60_000)); expect(await faces.claim(1)).toEqual([recent.id]); // The month is clear: the gallery that just arrived comes before one that has been waiting. expect(await faces.claim(1)).toEqual([archive.id]); expect(await faces.claim(1)).toEqual([waiting.id]); }); it("puts the event at the front of the queue and requeues a face the worker abandoned", async () => { const { orgId, token, day1 } = await setup(); const photoOf = (name: string, facesStatus: "PENDING" | "FAILED" | "RUNNING") => ctx.db.photo.create({ data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: name, sha256: name.padEnd(64, "0"), byteSize: 1, storageKey: name, status: "READY", facesStatus }, }); const pending = await photoOf("pending.jpg", "PENDING"); const failed = await photoOf("failed.jpg", "FAILED"); const fresh = await photoOf("fresh.jpg", "RUNNING"); const stale = await photoOf("stale.jpg", "RUNNING"); const aged = await ctx.db.$executeRaw`UPDATE photos SET updated_at = ${new Date(Date.now() - 60 * 60_000)} WHERE id = ${stale.id}::uuid`; expect(aged).toBe(1); const res = await ctx.app.inject({ method: "POST", url: `/v1/events/${day1.id}/faces/analyse`, headers: bearer(token) }); expect(res.statusCode).toBe(200); expect(res.json()).toEqual({ queued: 3 }); const statusOf = async (id: string) => ctx.db.photo.findUniqueOrThrow({ where: { id }, select: { facesStatus: true, facesBoostedAt: true } }); expect(await statusOf(pending.id)).toMatchObject({ facesStatus: "PENDING" }); expect((await statusOf(pending.id)).facesBoostedAt).not.toBeNull(); expect((await statusOf(failed.id)).facesStatus).toBe("PENDING"); expect((await statusOf(stale.id)).facesStatus).toBe("PENDING"); expect((await statusOf(fresh.id)).facesStatus).toBe("RUNNING"); expect((await statusOf(fresh.id)).facesBoostedAt).toBeNull(); const event = await ctx.db.event.findUniqueOrThrow({ where: { id: day1.id }, select: { faceBoostedAt: true } }); expect(event.faceBoostedAt).not.toBeNull(); const listed = await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) }); expect(listed.json()).toMatchObject({ available: true, pending: 4 }); }); it("says face analysis is unavailable when the worker engine is not running", async () => { const off = await createTestApp({ STORAGE_ROOT: ctx.config.STORAGE_ROOT, INGEST_ROOT: ingestRoot }, broadcaster, undefined, () => false); try { const { token, day1 } = await setup(); const res = await off.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) }); expect(res.statusCode).toBe(200); expect(res.json()).toMatchObject({ available: false, groups: [] }); } finally { await off.app.close(); await off.db.$disconnect(); } }); });