From 96deacd7b6850b0590450be96c1ab878a865e16d Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 17 Oct 2026 19:11:32 +0100 Subject: [PATCH] Folder search: try the game first, then everyone else, on every core. A face is named from the match (players and officials) when one of them matches, and only then from the rest of the organization. The scan runs one face process per spare core so a full folder is read in parallel. --- apps/api/src/app.ts | 24 ++++++++--- apps/api/src/faces/lookup.ts | 16 +++++-- apps/api/src/faces/lookupRoutes.ts | 12 +++--- apps/api/src/faces/numbers.ts | 56 +++++++++++++++++++++---- apps/api/src/jersey/model.ts | 14 +++++++ apps/api/src/lib/engines.ts | 15 +++++++ apps/api/test/lookup.test.ts | 37 +++++++++++++++- apps/app/src/i18n.ts | 7 +++- apps/app/src/library/CardScan.test.tsx | 6 +-- apps/app/src/library/CardScan.tsx | 58 ++++++++++++++++---------- packages/sdk/src/types.ts | 4 +- 11 files changed, 197 insertions(+), 52 deletions(-) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 0bda6dc..98f1930 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -31,10 +31,10 @@ import { DevelopService } from "./develop/service.js"; import { registerFaceRoutes } from "./faces/routes.js"; import { FaceLookup, IdleEngine } from "./faces/lookup.js"; import { registerLookupRoutes } from "./faces/lookupRoutes.js"; -import { type FaceEngine, FaceProcess } from "./faces/process.js"; +import { type FaceEngine, FacePool, FaceProcess } from "./faces/process.js"; import { faceWorkerLive } from "./faces/heartbeat.js"; -import { faceEnginePaths, jerseyModelDir } from "./lib/engines.js"; -import { JerseyModel } from "./jersey/model.js"; +import { faceEnginePaths, jerseyModelDir, scanSlots } from "./lib/engines.js"; +import { JerseyModel, JerseyPool } from "./jersey/model.js"; import type { JerseyReader } from "./faces/lookup.js"; import { registerJerseyRoutes } from "./jersey/routes.js"; import { JerseyService } from "./jersey/service.js"; @@ -155,8 +155,17 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline }); // Search by photo (library and "Encontra-te" on the sites): the API's own face engine, started on demand. const facePaths = faceEnginePaths(config); + const slots = scanSlots(); const lookupEngine = new IdleEngine( - faceEngine ? () => faceEngine : facePaths && config.NODE_ENV !== "test" ? () => new FaceProcess({ bin: facePaths.bin, modelsDir: facePaths.modelsDir, embedder: config.FACES_EMBEDDER }) : null, + faceEngine + ? () => faceEngine + : facePaths && config.NODE_ENV !== "test" + ? () => { + // One process per core: the face engine handles a single photo at a time. + const engines = Array.from({ length: slots }, () => new FaceProcess({ bin: facePaths.bin, modelsDir: facePaths.modelsDir, embedder: config.FACES_EMBEDDER })); + return engines.length === 1 ? engines[0]! : new FacePool(engines); + } + : null, ); app.addHook("onClose", async () => (faceEngine ? undefined : lookupEngine.close())); const lookup = new FaceLookup({ db, engine: () => lookupEngine.get() }); @@ -167,10 +176,15 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give jerseyOnce ??= (async () => { const dir = jerseyModelDir(config); if (!dir) return null; - return JerseyModel.load(dir).catch((err: unknown) => { + const first = await JerseyModel.load(dir).catch((err: unknown) => { app.log.warn({ err }, "jersey model not loaded for card scan"); return null; }); + if (!first) return null; + if (slots === 1) return first; + const rest = await Promise.all(Array.from({ length: slots - 1 }, () => JerseyModel.load(dir).catch(() => null))); + const models = [first, ...rest.filter((model): model is JerseyModel => !!model)]; + return models.length === 1 ? models[0]! : new JerseyPool(models); })(); return jerseyOnce; }; diff --git a/apps/api/src/faces/lookup.ts b/apps/api/src/faces/lookup.ts index 7f4d32b..525a1e3 100644 --- a/apps/api/src/faces/lookup.ts +++ b/apps/api/src/faces/lookup.ts @@ -161,10 +161,18 @@ export class FaceLookup { /** * Named people like the face (their centroid: confirmed faces and reference photo). - * `ids` limits the comparison to one game's squad. Null searches the whole organization. An empty list names no one. + * `prefer`, when set, is the whole search when anyone there matches: the game's players and officials. + * Only a face none of them match is compared with the rest of the organization. */ - async people(orgId: string, embedding: number[], model: string, limit = 5, ids: string[] | null = null) { - if (ids && !ids.length) return []; + async people(orgId: string, embedding: number[], model: string, limit = 5, prefer: string[] | null = null) { + if (prefer?.length) { + const inGame = await this.matchPeople(orgId, embedding, model, limit, prefer); + if (inGame.length) return inGame; + } + return this.matchPeople(orgId, embedding, model, limit, null); + } + + private async matchPeople(orgId: string, embedding: number[], model: string, limit: number, only: string[] | null) { const match = this.threshold(model); const rows = await this.deps.db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; score: number }[]>` SELECT id, name, club, number, score FROM ( @@ -173,7 +181,7 @@ export class FaceLookup { / NULLIF(sqrt((SELECT sum(a * a) FROM unnest(p.centroid) AS u(a))), 0) AS score FROM people p WHERE p.organization_id = ${orgId}::uuid AND p.model = ${model} AND cardinality(p.centroid) = ${embedding.length} - AND (${ids}::uuid[] IS NULL OR p.id = ANY(${ids}::uuid[])) + AND (${only}::uuid[] IS NULL OR p.id = ANY(${only}::uuid[])) ) s WHERE score >= ${match - POSSIBLE_BELOW} ORDER BY score DESC diff --git a/apps/api/src/faces/lookupRoutes.ts b/apps/api/src/faces/lookupRoutes.ts index fa29d41..b2113ee 100644 --- a/apps/api/src/faces/lookupRoutes.ts +++ b/apps/api/src/faces/lookupRoutes.ts @@ -6,6 +6,7 @@ import type { Db } from "../db.js"; import { AppError, badRequest, conflict } from "../lib/errors.js"; import { photoInclude, toSummary } from "../library/serialize.js"; import type { UrlSigner } from "../storage/storage.js"; +import { scanSlots } from "../lib/engines.js"; import { numberContext, numbersIn, rosterOf } from "./numbers.js"; import { type FaceLookup, type JerseyReader, LookupRejected, type MatchLevel, type QueryFace } from "./lookup.js"; @@ -117,11 +118,11 @@ export async function registerLookupRoutes( }; /** - * One photo from a folder, not imported: the clear faces, the shirt number under each, and the known person that - * face is. With a game, the name is chosen only among that game's squad. The file is read and thrown away. - * Nothing is written to the library. + * One photo from a folder, not imported: the clear faces, the shirt number under each, and the known person. + * A game is asked first (its players and officials). Anyone it does not know is looked up in the whole + * organization. The file is read and thrown away. Nothing is written to the library. */ - app.post("/v1/orgs/:orgId/faces/scan", { preHandler: authenticate, config: { rateLimit: { max: 8000, timeWindow: "10 minutes" } } }, async (req) => { + app.post("/v1/orgs/:orgId/faces/scan", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => { const { orgId } = OrgParams.parse(req.params); const eventId = z.object({ eventId: z.uuid().optional() }).parse(req.query).eventId; await requireMembership(db, req, orgId, "PHOTOGRAPHER"); @@ -133,10 +134,11 @@ export async function registerLookupRoutes( const ctx = eventId ? await numberContext(db, eventId) : null; const ids = eventId ? await roster(eventId) : null; const hits = await Promise.all( - read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids))[0] ?? null) : null)), + read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids && ids.length ? ids : null))[0] ?? null) : null)), ); const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map(); return { + slots: scanSlots(), roster: ids ? ids.length : ids, faces: read.faces.map((f, i) => { const hit = hits[i]; diff --git a/apps/api/src/faces/numbers.ts b/apps/api/src/faces/numbers.ts index 6ff8fde..dae0326 100644 --- a/apps/api/src/faces/numbers.ts +++ b/apps/api/src/faces/numbers.ts @@ -145,16 +145,26 @@ export async function numbersIn(db: Db, ctx: NumberContext, personIds: string[], return out; } +/** A match official as stored on the fixture (`{ name, fullName, externalId, role }`). */ +interface FixtureOfficial { + name?: string; + fullName?: string | null; + externalId?: string | null; +} + /** - * Who a folder scan may name in this game. The season's squad of the two teams (the same player, even when their - * person row points at another season of that club). Null when there is no squad to limit to, so the caller - * compares with everyone. An empty list means the squad is known and none of them have a face on file yet. + * Who this game should be asked first: the season's squad of the two teams (the same player, even when their + * person row points at another season) and the match officials who already have a face (referees, table). + * Null when nothing of the game is known, so the caller compares with everyone straight away. An empty list + * means the squad is known and none of them have a face on file yet. */ export async function rosterOf(db: Db, eventId: string): Promise { const ctx = await numberContext(db, eventId); if (!ctx) return null; + const ids = new Set(); + let squad = 0; if (ctx.teamIds.length) { - const squad = await db.sportsPlayer.count({ where: { teamId: { in: ctx.teamIds }, season: ctx.season } }); + squad = await db.sportsPlayer.count({ where: { teamId: { in: ctx.teamIds }, season: ctx.season } }); if (squad > 0) { const rows = await db.$queryRaw<{ id: string }[]>` SELECT DISTINCT p.id @@ -172,9 +182,12 @@ export async function rosterOf(db: Db, eventId: string): Promise r.id); + for (const row of rows) ids.add(row.id); } } + for (const id of await officialsOf(db, eventId, ctx.organizationId)) ids.add(id); + if (ids.size) return [...ids]; + if (squad > 0) return []; // No official squad: people typed against these clubs, and only when that set is small enough to be the game. const event = await db.event.findUnique({ where: { id: eventId }, select: { home: true, away: true, homeShort: true, awayShort: true } }); if (!event) return null; @@ -183,12 +196,39 @@ export async function rosterOf(db: Db, eventId: string): Promise { const club = fold(p.club ?? ""); return club.length > 2 && teams.some((t) => t.length > 2 && (t.includes(club) || club.includes(t))); }) .map((p) => p.id); - if (!ids.length || ids.length > 400) return null; - return ids; + if (!clubIds.length || clubIds.length > 400) return null; + return clubIds; +} + +/** Referees and table officials of this match who already have a face. */ +async function officialsOf(db: Db, eventId: string, organizationId: string): Promise { + const event = await db.event.findUnique({ where: { id: eventId }, select: { fixture: { select: { officials: true } } } }); + const list = Array.isArray(event?.fixture?.officials) ? (event.fixture.officials as FixtureOfficial[]) : []; + const names = [...new Set(list.flatMap((o) => [o.name, o.fullName].filter((n): n is string => !!n)))]; + const externalIds = [...new Set(list.map((o) => o.externalId).filter((id): id is string => !!id))]; + const ids = new Set(); + if (names.length) { + const byName = await db.person.findMany({ + where: { organizationId, name: { in: names }, NOT: { centroid: { isEmpty: true } } }, + select: { id: true }, + }); + for (const person of byName) ids.add(person.id); + } + if (externalIds.length) { + const players = await db.sportsPlayer.findMany({ where: { externalId: { in: externalIds } }, select: { id: true } }); + if (players.length) { + const byLicence = await db.person.findMany({ + where: { organizationId, sportsPlayerId: { in: players.map((p) => p.id) }, NOT: { centroid: { isEmpty: true } } }, + select: { id: true }, + }); + for (const person of byLicence) ids.add(person.id); + } + } + return [...ids]; } diff --git a/apps/api/src/jersey/model.ts b/apps/api/src/jersey/model.ts index 9390e78..3ea4342 100644 --- a/apps/api/src/jersey/model.ts +++ b/apps/api/src/jersey/model.ts @@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import * as ort from "onnxruntime-node"; import sharp from "sharp"; +import { LeastBusy } from "../lib/line-process.js"; import type { Box } from "./crop.js"; interface Meta { @@ -63,3 +64,16 @@ export class JerseyModel { return { number: label === "illegible" ? null : label, score: probs[best]! }; } } + +/** Several copies of the shirt-number model, so a folder scan can read numbers on many cores at once. */ +export class JerseyPool { + private readonly pool: LeastBusy; + + constructor(models: JerseyModel[]) { + this.pool = new LeastBusy(models); + } + + read(original: string, box: Box): Promise { + return this.pool.use((model) => model.read(original, box)); + } +} diff --git a/apps/api/src/lib/engines.ts b/apps/api/src/lib/engines.ts index 9b36804..3202fd7 100644 --- a/apps/api/src/lib/engines.ts +++ b/apps/api/src/lib/engines.ts @@ -1,8 +1,23 @@ import { existsSync } from "node:fs"; +import { availableParallelism, totalmem } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { modelsDir } from "./models.js"; +/** + * How many face processes a folder scan runs at once. Each process is one core (the engine is single-threaded), + * so this is what fills the machine. A few cores stay for the API and the library worker when the box is large. + */ +export function scanSlots(machine: { cpus: number; memoryBytes: number } = { cpus: availableParallelism(), memoryBytes: totalmem() }): number { + const cpus = Math.max(1, machine.cpus); + const spareGb = Math.max(1, machine.memoryBytes / 1e9 - 6); + const byMemory = Math.max(1, Math.floor(spareGb / 0.6)); + let leave = 0; + if (cpus >= 16) leave = 8; + else if (cpus >= 8) leave = 2; + return Math.max(1, Math.min(cpus - leave, byMemory)); +} + /** The shirt-number model, when it was downloaded next to the face models or pointed at by the env. */ export function jerseyModelDir(config: { JERSEY_MODEL_DIR?: string | undefined; STORAGE_ROOT: string }): string | null { if (config.JERSEY_MODEL_DIR && existsSync(join(config.JERSEY_MODEL_DIR, "jersey.onnx"))) return config.JERSEY_MODEL_DIR; diff --git a/apps/api/test/lookup.test.ts b/apps/api/test/lookup.test.ts index f22184a..746f41e 100644 --- a/apps/api/test/lookup.test.ts +++ b/apps/api/test/lookup.test.ts @@ -151,7 +151,7 @@ describe("search by photo", () => { engine.next = { width: 800, height: 1000, faces: [] }; res = await post(); expect(res.statusCode).toBe(200); - expect(res.json()).toEqual({ roster: null, faces: [] }); + expect(res.json()).toMatchObject({ roster: null, faces: [] }); await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: false } }); res = await post(); @@ -174,6 +174,41 @@ describe("search by photo", () => { expect(res.json()).toMatchObject({ roster: 1, faces: [{ person: { id: rui.id, name: "Rui Silva" } }] }); }); + it("asks the game first, including a referee, and the rest of the organization only when the game has no match", 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: { id: outsider.id, name: "Só lá fora" } }] }); + }); + 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); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 244126f..71bbd0f 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -621,8 +621,11 @@ export const t = { title: "Procurar numa pasta", help: "Escolhe uma pasta. As fotos ficam onde estão. Só entram no jogo as que selecionares.", game: "Jogo", - roster: (n: number) => (n === 1 ? "A comparar só com 1 pessoa deste jogo." : `A comparar só com ${n} pessoas deste jogo.`), - rosterNone: "Este jogo tem plantel, mas ainda nenhuma cara conhecida. Mostra o número.", + roster: (n: number) => + n === 1 + ? "Primeiro 1 pessoa deste jogo (jogadores e árbitros). Se não der, o resto." + : `Primeiro as ${n} pessoas deste jogo (jogadores e árbitros). Se não der, o resto.`, + rosterNone: "Este jogo tem plantel, mas ainda nenhuma cara conhecida. Compara com toda a gente.", rosterOpen: "Este jogo não tem plantel: compara com toda a gente.", jpeg: "Só lê JPEG. Os outros ficheiros da pasta ficam de fora.", pick: "Escolher pasta", diff --git a/apps/app/src/library/CardScan.test.tsx b/apps/app/src/library/CardScan.test.tsx index c6f9fa1..83d614f 100644 --- a/apps/app/src/library/CardScan.test.tsx +++ b/apps/app/src/library/CardScan.test.tsx @@ -47,8 +47,8 @@ describe("card folder dialog", () => { }; const scanCard = vi.fn() - .mockResolvedValueOnce({ roster: 2, faces: [face({ number: "5", name: "Inês", club: "Gil Eanes", personNumber: "5" })] }) - .mockResolvedValueOnce({ roster: 2, faces: [] }); + .mockResolvedValueOnce({ slots: 4, roster: 2, faces: [face({ number: "5", name: "Inês", club: "Gil Eanes", personNumber: "5" })] }) + .mockResolvedValueOnce({ slots: 4, roster: 2, faces: [] }); const onImport = vi.fn(); const { container } = render( { expect(screen.getByText(/1 foto sem cara nem número ficou de fora/)).toBeTruthy(); expect(scanCard).toHaveBeenCalledTimes(2); expect(scanCard).toHaveBeenCalledWith("org", expect.anything(), "game"); - expect(screen.getByText("A comparar só com 2 pessoas deste jogo.")).toBeTruthy(); + expect(screen.getByText(/Primeiro as 2 pessoas deste jogo/)).toBeTruthy(); fireEvent.change(screen.getByLabelText("Nome, clube ou número"), { target: { value: "ines 5" } }); fireEvent.click(screen.getByRole("button", { name: /Inês #5/ })); diff --git a/apps/app/src/library/CardScan.tsx b/apps/app/src/library/CardScan.tsx index 54eae63..e5dd0fa 100644 --- a/apps/app/src/library/CardScan.tsx +++ b/apps/app/src/library/CardScan.tsx @@ -142,31 +142,43 @@ export function CardScan({ for (const item of prev) if (item.thumb) URL.revokeObjectURL(item.thumb); return next; }); + // A handful at first; the server says how many it can read at once, and the rest start then. + let width = Math.min(8, next.length); + let running = 0; let cursor = 0; - const worker = async () => { - while (!stop.current) { - const index = cursor++; - const item = next[index]; - if (!item) return; - try { - const small = await previewOf(item.file); - const read = await api.scanCard(orgId, small, gameRef.current); - item.faces = read.faces; - setRoster(read.roster); - if (read.faces.length) item.thumb = URL.createObjectURL(small); - } catch (err) { - item.error = true; - item.faces = []; - if (err instanceof ApiError && (err.code === "biometrics_disabled" || err.code === "engine_unavailable")) { - stop.current = true; - setNote(t.lookup.errors[err.code] ?? t.unexpectedError); - } + await new Promise((resolve) => { + const launch = () => { + while (!stop.current && running < width && cursor < next.length) { + const item = next[cursor++]!; + running++; + void (async () => { + try { + const small = await previewOf(item.file); + const read = await api.scanCard(orgId, small, gameRef.current); + item.faces = read.faces; + setRoster(read.roster); + if (read.slots > width) width = read.slots; + if (read.faces.length) item.thumb = URL.createObjectURL(small); + } catch (err) { + item.error = true; + item.faces = []; + if (err instanceof ApiError && (err.code === "biometrics_disabled" || err.code === "engine_unavailable")) { + stop.current = true; + setNote(t.lookup.errors[err.code] ?? t.unexpectedError); + } + } finally { + running--; + setDone((n) => n + 1); + setItems(next.slice()); + launch(); + if (running === 0 && (stop.current || cursor >= next.length)) resolve(); + } + })(); } - setDone((n) => n + 1); - setItems(next.slice()); - } - }; - await Promise.all([worker(), worker()]); + if (running === 0 && (stop.current || cursor >= next.length)) resolve(); + }; + launch(); + }); setRunning(false); if (next.some((item) => item.error) && !stop.current) setNote(t.cardScan.failed); }; diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 3f05d9d..125828e 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -458,7 +458,9 @@ export interface LookupFace { /** One photo from a folder, read and not kept: clear faces, the shirt number, and the known person. */ export interface CardScan { - /** How many people of the chosen game the face was compared with. Null: that game has no squad, so everyone. */ + /** How many photos the server can read at once. The client keeps that many in flight. */ + slots: number; + /** People of the chosen game asked first. Null: that game has no squad, so everyone is asked together. */ roster: number | null; faces: { box: { x0: number; y0: number; x1: number; y1: number }; -- 2.47.3