Files
photoreport/apps/api/test/faces.test.ts
T
sparkandClaude Opus 5.5 57ed2154be
ci / rust (push) Successful in 6m54s
ci / typescript (push) Successful in 7m47s
feat(faces): shirt numbers from our own model
Torso crops reviewed in the app; a ResNet18 trained on Mac (MPS) and exported to ONNX.
The worker reads numbers when JERSEY_MODEL_DIR is set.
A group with no face match is suggested a player by shirt number when exactly one player of the two teams wears it.
The faces worker now applies EXIF orientation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-11 23:31:00 +01:00

303 lines
19 KiB
TypeScript

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<string, FaceAnalysis>();
calls = 0;
async analyse(file: string): Promise<FaceAnalysis> {
this.calls++;
const sha = path.basename(file).split(".")[0]!;
return this.byColor.get(sha) ?? { width: 600, height: 400, faces: [] };
}
async close(): Promise<void> {}
}
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, "[email protected]", { org: "fpa", role: "OWNER" });
const token = (await login(ctx.app, "[email protected]")).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 = 200): Promise<string> {
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, 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("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("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("keeps blurred faces out of the groups, and says how many", 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 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(body.unclear).toBe(2);
expect(await ctx.db.face.count()).toBe(4);
});
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: <personId>.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(2);
expect(list.samples[0]).toMatchObject({ suggested: "07", 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);
// 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"]);
});
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" },
],
});
// The number model reads 10, 10 and (once, less sure) 16 on this player's shirt.
const readings = ["10", "10", "16"];
let calls = 0;
const reader = { read: async () => ({ number: readings[calls++ % 3]!, score: calls === 3 ? 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);
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);
});
});