Files
photoreport/apps/api/test/lookup.test.ts
spark 17e5ff4bee
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Failing after 14m22s
Name a face only from the clubs of that game.
A weak likeness was compared with every person in the organisation when the match sheet did not explain it, so a player of one club could be named as a player of another. A known game now stays on its roster, and a past season's squad is stored with the calendar.
2026-10-21 20:12:20 +01:00

248 lines
15 KiB
TypeScript

import { mkdtemp, rm } 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 { buildApp } from "../src/app.js";
import { loadConfig } from "../src/config.js";
import { createDb } from "../src/db.js";
import { normalize } from "../src/faces/math.js";
import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js";
import { bearer, login, resetDb, seedUser } from "./helpers.js";
/** A person's face: a fixed direction (64 dims) plus a little noise per photo. */
function face(seed: number, noise = 0): number[] {
const rand = (k: number) => {
const x = Math.sin(k * 127.1 + 311.7) * 43758.5453;
return (x - Math.floor(x)) * 2 - 1;
};
return normalize(Array.from({ length: 64 }, (_, i) => rand(seed * 1000 + i) + (noise ? rand(noise * 7919 + i) * 0.15 : 0)));
}
/** Answers every search photo with the faces set for the test. */
class FakeEngine implements FaceEngine {
readonly model = "auraface-v1";
next: FaceAnalysis = { width: 800, height: 1000, faces: [] };
async analyse(): Promise<FaceAnalysis> {
return this.next;
}
async close(): Promise<void> {}
}
const found = (seed: number, box = { x0: 0.3, y0: 0.2, x1: 0.7, y1: 0.6 }) => ({ ...box, score: 0.95, sharpness: 300, landmarks: [] as [number, number][], embedding: face(seed) });
describe("search by photo", () => {
const engine = new FakeEngine();
let dir: string;
let app: Awaited<ReturnType<typeof buildApp>>;
let db: ReturnType<typeof createDb>;
let jpeg: Buffer;
beforeAll(async () => {
dir = await mkdtemp(path.join(tmpdir(), "pr-lookup-"));
const config = loadConfig({
NODE_ENV: "test",
DATABASE_URL: process.env.DATABASE_URL_TEST ?? "",
JWT_SECRET: "test-secret-test-secret-test-secret-123",
LOGIN_RATE_LIMIT_PER_MIN: "1000",
STORAGE_ROOT: path.join(dir, "storage"),
});
db = createDb(config.DATABASE_URL);
app = await buildApp({ config, db, faceEngine: engine, jersey: { async read() { return { number: "5", score: 0.95 }; } } });
jpeg = await sharp({ create: { width: 800, height: 1000, channels: 3, background: "#777" } }).jpeg().toBuffer();
});
afterAll(async () => {
await app.close();
await db.$disconnect();
await rm(dir, { recursive: true, force: true });
});
beforeEach(async () => {
await resetDb(db);
engine.next = { width: 800, height: 1000, faces: [] };
});
const multipart = (data: Buffer) => {
const boundary = "----pr-lookup";
const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="selfie.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`);
return { payload: Buffer.concat([head, data, Buffer.from(`\r\n--${boundary}--\r\n`)]), type: `multipart/form-data; boundary=${boundary}` };
};
/** Two games; Rui (seed 1) is in photos 0, 1 (game A) and 3 (game B, a group nobody named); Ana (seed 2) in photo 2. */
async function setup(biometrics = true) {
const { org, user } = await seedUser(db, "[email protected]", { org: "fpa", role: "OWNER" });
const orgId = org!.id;
if (biometrics) await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } });
const token = (await login(app, "[email protected]")).body.accessToken;
const event = (home: string, day: string) =>
db.event.create({ data: { organizationId: orgId, home, away: "AAAS", startsAt: new Date(day), ingestFrom: new Date(day), ingestUntil: new Date(day), iptcTemplate: {}, createdById: user.id } });
const [a, b] = [await event("SCP", "2026-09-20T18:00:00Z"), await event("ABC", "2026-09-27T18:00:00Z")];
const photos: string[] = [];
for (let i = 0; i < 5; i++) {
const p = await db.photo.create({
data: { organizationId: orgId, eventId: i < 3 ? a.id : b.id, source: "UPLOAD", originalName: `P_${i}.jpg`, sha256: String(i).repeat(64), byteSize: 1, storageKey: `k${i}`, status: "READY", width: 6000, height: 4000, capturedAt: new Date(Date.now() - i * 60_000) },
});
photos.push(p.id);
}
const rui = await db.person.create({ data: { organizationId: orgId, name: "Rui Silva", club: "Sporting CP", number: "14", centroid: face(1), model: "auraface-v1" } });
const group = (eventId: string, seed: number, personId: string | null, size: number) =>
db.faceGroup.create({ data: { organizationId: orgId, eventId, centroid: face(seed, 9), model: "auraface-v1", size, personId } });
const ruiA = await group(a.id, 1, rui.id, 2);
const anaA = await group(a.id, 2, null, 1);
const ruiB = await group(b.id, 1, null, 1);
const addFace = (photoId: string, groupId: string, seed: number, noise: number) =>
db.face.create({ data: { organizationId: orgId, photoId, groupId, x0: 0.4, y0: 0.2, x1: 0.5, y1: 0.35, score: 0.9, sharpness: 120, embedding: face(seed, noise), model: "auraface-v1" } });
await addFace(photos[0]!, ruiA.id, 1, 1);
await addFace(photos[1]!, ruiA.id, 1, 2);
await addFace(photos[2]!, anaA.id, 2, 3);
await addFace(photos[3]!, ruiB.id, 1, 4);
return { orgId, token, photos, events: { a: a.id, b: b.id }, rui };
}
it("finds the person and every photo with that face across the events, in the library", async () => {
const { orgId, token, photos, rui } = await setup();
// Two people in the search photo: the largest is used unless another is picked.
engine.next = { width: 800, height: 1000, faces: [found(2, { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 }), found(1)] };
const mp = multipart(jpeg);
let res = await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/lookup`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
expect(res.statusCode).toBe(200);
let body = res.json() as { faces: { box: object }[]; used: number; people: { id: string; level: string }[]; photos: { id: string }[]; matches: { photoId: string; level: string }[]; events: number };
expect(body.faces).toHaveLength(2);
expect(body.used).toBe(0);
expect(body.people[0]).toMatchObject({ id: rui.id, level: "strong" });
expect(new Set(body.photos.map((p) => p.id))).toEqual(new Set([photos[0], photos[1], photos[3]]));
expect(body.events).toBe(2);
expect(body.matches.every((m) => m.level === "strong")).toBe(true);
// The other face of the photo: Ana, one photo.
res = await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/lookup?face=1`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
body = res.json();
expect(body.used).toBe(1);
expect(body.photos.map((p) => p.id)).toEqual([photos[2]]);
});
it("stays in one event when asked, and says when there is no face or no face recognition", async () => {
const { orgId, token, photos, events } = await setup();
engine.next = { width: 800, height: 1000, faces: [found(1)] };
const mp = multipart(jpeg);
let res = await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/lookup?eventId=${events.b}`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
expect((res.json() as { photos: { id: string }[] }).photos.map((p) => p.id)).toEqual([photos[3]]);
engine.next = { width: 800, height: 1000, faces: [] };
res = await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/lookup`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
expect(res.statusCode).toBe(400);
expect(res.json()).toMatchObject({ error: "no_face" });
await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: false } });
res = await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/lookup`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
expect(res.json()).toMatchObject({ error: "biometrics_disabled" });
});
it("reads a card photo without keeping it: the shirt number and the person, or nothing", async () => {
const { orgId, token, events, rui } = await setup();
// High in the frame and small enough that the chest crop stays inside the photo.
engine.next = { width: 800, height: 1000, faces: [found(1, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
const mp = multipart(jpeg);
const post = (id = orgId) => app.inject({ method: "POST", url: `/v1/orgs/${id}/faces/scan?eventId=${events.a}`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
let res = await post();
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: null, faces: [{ number: "5", person: { id: rui.id, name: "Rui Silva", number: "14", level: "strong" } }] });
expect(JSON.stringify(res.json())).not.toContain("embedding");
engine.next = { width: 800, height: 1000, faces: [] };
res = await post();
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: null, faces: [] });
await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: false } });
res = await post();
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: "biometrics_disabled" });
});
it("names only a player of the chosen game, not someone else with the same face", async () => {
const { orgId, token, events, rui } = await setup();
const home = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "gil", sport: "andebol", name: "Gil Eanes", slug: "gil-eanes" } });
const away = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "cdf", sport: "andebol", name: "Feirense", slug: "feirense" } });
const player = await db.sportsPlayer.create({ data: { teamId: home.id, season: "20262027", name: "Rui Silva", externalId: "rui" } });
await db.person.update({ where: { id: rui.id }, data: { sportsPlayerId: player.id } });
await db.person.create({ data: { organizationId: orgId, name: "Outra Pessoa", club: "Outro Clube", centroid: face(1), model: "auraface-v1" } });
await db.event.update({ where: { id: events.a }, data: { homeTeamId: home.id, awayTeamId: away.id } });
engine.next = { width: 800, height: 1000, faces: [found(1, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
const mp = multipart(jpeg);
const res = await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/scan?eventId=${events.a}`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: 1, faces: [{ person: { id: rui.id, name: "Rui Silva" } }] });
});
it("asks the game first, including a referee, and leaves a face the game does not know unnamed", async () => {
const { orgId, token, events, rui } = await setup();
const home = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "gil2", sport: "andebol", name: "Gil Eanes", slug: "gil-eanes-2" } });
const away = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "cdf2", sport: "andebol", name: "Feirense", slug: "feirense-2" } });
const player = await db.sportsPlayer.create({ data: { teamId: home.id, season: "20262027", name: "Rui Silva", externalId: "rui2" } });
await db.person.update({ where: { id: rui.id }, data: { sportsPlayerId: player.id } });
const comp = await db.sportsCompetition.create({ data: { provider: "FPA", externalId: "scan-ref", sport: "andebol", name: "PO", season: "20262027" } });
const fixture = await db.sportsFixture.create({
data: {
competitionId: comp.id,
season: "20262027",
externalId: "165",
homeTeamId: home.id,
awayTeamId: away.id,
startsAt: new Date("2026-09-20T18:00:00Z"),
officials: [{ name: "Carlos Reis", role: "REFEREE" }],
},
});
await db.event.update({ where: { id: events.a }, data: { homeTeamId: home.id, awayTeamId: away.id, fixtureId: fixture.id } });
const referee = await db.person.create({ data: { organizationId: orgId, name: "Carlos Reis", club: "Arbitragem", centroid: face(3), model: "auraface-v1" } });
await db.person.create({ data: { organizationId: orgId, name: "Fora do jogo", club: "Outro", centroid: face(3), model: "auraface-v1" } });
const outsider = await db.person.create({ data: { organizationId: orgId, name: "Só lá fora", club: "Outro", centroid: face(4), model: "auraface-v1" } });
const mp = multipart(jpeg);
const post = () => app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/scan?eventId=${events.a}`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
engine.next = { width: 800, height: 1000, faces: [found(3, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
let res = await post();
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: 2, faces: [{ person: { id: referee.id, name: "Carlos Reis" } }] });
engine.next = { width: 800, height: 1000, faces: [found(4, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
res = await post();
expect(res.json()).toMatchObject({ faces: [{ person: null }] });
expect(JSON.stringify(res.json())).not.toContain(outsider.id);
});
it("names an embedding read on the photographer's computer, without the photo", async () => {
const { orgId, token, rui } = await setup();
const res = await app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/faces/identify`,
headers: { ...bearer(token), "content-type": "application/json" },
payload: { faces: [{ embedding: face(1) }, { embedding: face(9) }] },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: null, people: [{ id: rui.id, name: "Rui Silva" }, null] });
});
it("finds a visitor's face in a public gallery's photos only", async () => {
const { orgId, token, photos } = await setup();
expect((await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/sites`, headers: bearer(token), payload: { domain: "fotos.test", skin: "photoreport", name: "PhotoReport" } })).statusCode).toBe(201);
// The gallery has photos 1, 2 and 3: Rui is in 1 (and 0, which is not in it) and 3.
const g = await db.gallery.create({ data: { organizationId: orgId, slug: "jogo", title: "Jogo", publishedAt: new Date() } });
await db.galleryPhoto.createMany({ data: [1, 2, 3].map((i, position) => ({ galleryId: g.id, photoId: photos[i]!, position })) });
const page = await app.inject({ method: "GET", url: "/v1/public/galleries/jogo", headers: { "x-site-domain": "fotos.test" } });
expect(page.json()).toMatchObject({ findMe: true });
engine.next = { width: 800, height: 1000, faces: [found(1)] };
const mp = multipart(jpeg);
const find = () => app.inject({ method: "POST", url: "/v1/public/galleries/jogo/find", headers: { "x-site-domain": "fotos.test", "content-type": mp.type }, payload: mp.payload });
let res = await find();
expect(res.statusCode).toBe(200);
const body = res.json() as { matches: { photoId: string; level: string }[]; faces: unknown[] };
expect(new Set(body.matches.map((m) => m.photoId))).toEqual(new Set([photos[1], photos[3]]));
expect(body.matches.every((m) => m.level === "strong")).toBe(true);
await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: false } });
res = await find();
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: "find_unavailable" });
});
});