From 404ef90a3e3a3aa3b6978b2ad7ed858e1c75b45e Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 17 Oct 2026 18:53:24 +0100 Subject: [PATCH] Folder search: name a face only from the chosen game's squad The game was already shown, but each face was compared with every person in the organization. The picker now limits that comparison to the two teams' squad for the season, which is who can be named and a much smaller search. --- apps/api/src/faces/lookup.ts | 9 +++-- apps/api/src/faces/lookupRoutes.ts | 22 +++++++++--- apps/api/src/faces/numbers.ts | 48 ++++++++++++++++++++++++++ apps/api/test/lookup.test.ts | 19 ++++++++-- apps/app/src/i18n.ts | 4 +++ apps/app/src/library/CardScan.test.tsx | 11 +++--- apps/app/src/library/CardScan.tsx | 47 +++++++++++++++++++------ apps/app/src/pages/LibraryPage.tsx | 4 +-- packages/sdk/src/types.ts | 4 ++- 9 files changed, 143 insertions(+), 25 deletions(-) diff --git a/apps/api/src/faces/lookup.ts b/apps/api/src/faces/lookup.ts index f518859..7f4d32b 100644 --- a/apps/api/src/faces/lookup.ts +++ b/apps/api/src/faces/lookup.ts @@ -159,8 +159,12 @@ export class FaceLookup { return rows.map((r) => ({ groupId: r.id, eventId: r.event_id, personId: r.person_id, size: r.size, score: Number(r.score), level: levelOf(Number(r.score), match)! })); } - /** Named people like the face (their centroid: confirmed faces and reference photo). */ - async people(orgId: string, embedding: number[], model: string, limit = 5) { + /** + * 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. + */ + async people(orgId: string, embedding: number[], model: string, limit = 5, ids: string[] | null = null) { + if (ids && !ids.length) return []; 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 ( @@ -169,6 +173,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[])) ) 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 ee7b076..fa29d41 100644 --- a/apps/api/src/faces/lookupRoutes.ts +++ b/apps/api/src/faces/lookupRoutes.ts @@ -6,7 +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 { numberContext, numbersIn } from "./numbers.js"; +import { numberContext, numbersIn, rosterOf } from "./numbers.js"; import { type FaceLookup, type JerseyReader, LookupRejected, type MatchLevel, type QueryFace } from "./lookup.js"; const OrgParams = z.object({ orgId: z.uuid() }); @@ -105,9 +105,21 @@ export async function registerLookupRoutes( }; }); + // A folder is thousands of photos of one game. The squad does not change between them, so it is read once. + const rosters = new Map(); + const rosterFor = 10 * 60_000; + const roster = async (eventId: string): Promise => { + const hit = rosters.get(eventId); + if (hit && Date.now() - hit.at < rosterFor) return hit.ids; + const ids = await rosterOf(db, eventId); + rosters.set(eventId, { at: Date.now(), ids }); + return ids; + }; + /** - * One photo from a card, not imported: the clear faces, the shirt number under each, and the known person that - * face is. The file is read and thrown away. A card is thousands of these; 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 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. */ app.post("/v1/orgs/:orgId/faces/scan", { preHandler: authenticate, config: { rateLimit: { max: 8000, timeWindow: "10 minutes" } } }, async (req) => { const { orgId } = OrgParams.parse(req.params); @@ -119,11 +131,13 @@ export async function registerLookupRoutes( const jersey = (await deps.jersey?.()) ?? null; const read = await lookup.inspect(image, jersey).catch(lookupFailed); 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))[0] ?? null) : null)), + read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids))[0] ?? null) : null)), ); const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map(); return { + roster: ids ? ids.length : ids, faces: read.faces.map((f, i) => { const hit = hits[i]; return { diff --git a/apps/api/src/faces/numbers.ts b/apps/api/src/faces/numbers.ts index c273ba6..6ff8fde 100644 --- a/apps/api/src/faces/numbers.ts +++ b/apps/api/src/faces/numbers.ts @@ -144,3 +144,51 @@ export async function numbersIn(db: Db, ctx: NumberContext, personIds: string[], } return out; } + +/** + * 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. + */ +export async function rosterOf(db: Db, eventId: string): Promise { + const ctx = await numberContext(db, eventId); + if (!ctx) return null; + if (ctx.teamIds.length) { + const 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 + FROM people p + JOIN sports_players mine ON mine.id = p.sports_player_id + WHERE p.organization_id = ${ctx.organizationId}::uuid + AND cardinality(p.centroid) > 0 + AND EXISTS ( + SELECT 1 FROM sports_players squad + WHERE squad.team_id = ANY(${ctx.teamIds}::uuid[]) + AND squad.season = ${ctx.season} + AND ( + squad.id = mine.id + OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id) + OR (squad.team_id = mine.team_id AND squad.name = mine.name) + ) + )`; + return rows.map((r) => r.id); + } + } + // 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; + const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(fold); + const people = await db.person.findMany({ + where: { organizationId: ctx.organizationId, club: { not: null }, NOT: { centroid: { isEmpty: true } } }, + select: { id: true, club: true }, + }); + const ids = people + .filter((p) => { + 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; +} diff --git a/apps/api/test/lookup.test.ts b/apps/api/test/lookup.test.ts index 9c6fdde..f22184a 100644 --- a/apps/api/test/lookup.test.ts +++ b/apps/api/test/lookup.test.ts @@ -145,13 +145,13 @@ describe("search by photo", () => { 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({ faces: [{ number: "5", person: { id: rui.id, name: "Rui Silva", number: "14", level: "strong" } }] }); + 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()).toEqual({ faces: [] }); + expect(res.json()).toEqual({ roster: null, faces: [] }); await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: false } }); res = await post(); @@ -159,6 +159,21 @@ describe("search by photo", () => { 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("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 e1d24a6..244126f 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -620,6 +620,10 @@ export const t = { button: "Procurar numa pasta", 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.", + 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", search: "Nome, clube ou número", diff --git a/apps/app/src/library/CardScan.test.tsx b/apps/app/src/library/CardScan.test.tsx index 2743b77..c6f9fa1 100644 --- a/apps/app/src/library/CardScan.test.tsx +++ b/apps/app/src/library/CardScan.test.tsx @@ -1,5 +1,5 @@ import { fireEvent, render, screen } from "@testing-library/react"; -import type { ApiClient } from "@photoreport/sdk"; +import type { ApiClient, EventSummary } from "@photoreport/sdk"; import { describe, expect, it, vi } from "vitest"; import { CardScan, cardMatches } from "./CardScan.js"; @@ -47,15 +47,15 @@ describe("card folder dialog", () => { }; const scanCard = vi.fn() - .mockResolvedValueOnce({ faces: [face({ number: "5", name: "Inês", club: "Gil Eanes", personNumber: "5" })] }) - .mockResolvedValueOnce({ faces: [] }); + .mockResolvedValueOnce({ roster: 2, faces: [face({ number: "5", name: "Inês", club: "Gil Eanes", personNumber: "5" })] }) + .mockResolvedValueOnce({ roster: 2, faces: [] }); const onImport = vi.fn(); const { container } = render( {}} />, @@ -73,6 +73,8 @@ describe("card folder dialog", () => { expect(await screen.findByRole("button", { name: /Inês #5/ })).toBeTruthy(); 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(); fireEvent.change(screen.getByLabelText("Nome, clube ou número"), { target: { value: "ines 5" } }); fireEvent.click(screen.getByRole("button", { name: /Inês #5/ })); @@ -80,6 +82,7 @@ describe("card folder dialog", () => { expect(onImport).toHaveBeenCalledTimes(1); const sent = onImport.mock.calls[0]![0] as File[]; expect(sent.map((f) => f.name)).toEqual(["a.jpg"]); + expect(onImport.mock.calls[0]![1]).toBe("game"); expect(screen.getByText("1 foto a entrar no jogo.")).toBeTruthy(); }); }); diff --git a/apps/app/src/library/CardScan.tsx b/apps/app/src/library/CardScan.tsx index 16d3af9..54eae63 100644 --- a/apps/app/src/library/CardScan.tsx +++ b/apps/app/src/library/CardScan.tsx @@ -1,4 +1,4 @@ -import type { ApiClient, CardScan as CardReading } from "@photoreport/sdk"; +import type { ApiClient, CardScan as CardReading, EventSummary } from "@photoreport/sdk"; import { ApiError } from "@photoreport/sdk"; import { useEffect, useMemo, useRef, useState } from "react"; import { t } from "../i18n.js"; @@ -62,19 +62,25 @@ async function previewOf(file: File): Promise { * Look through a folder on this computer for faces and shirt numbers, without importing it. * The photographer then sends only the photos they pick into the event. */ +const gameLabel = (e: EventSummary) => { + const day = e.startsAt.slice(0, 10).split("-").reverse().join("/"); + const teams = [e.homeShort || e.home, e.away ? e.awayShort || e.away : ""].filter(Boolean).join(" × "); + return `${day} ${teams}`; +}; + export function CardScan({ api, orgId, eventId, - eventTitle, + games, onImport, onClose, }: { api: ApiClient; orgId: string; eventId: string; - eventTitle: string; - onImport: (files: File[]) => void; + games: EventSummary[]; + onImport: (files: File[], eventId: string) => void; onClose: () => void; }) { const input = useRef(null); @@ -87,6 +93,11 @@ export function CardScan({ const [selected, setSelected] = useState>(new Set()); const [note, setNote] = useState(null); const [sent, setSent] = useState(null); + const [gameId, setGameId] = useState(eventId); + const [roster, setRoster] = useState(undefined); + const gameRef = useRef(gameId); + gameRef.current = gameId; + const choices = useMemo(() => [...games].sort((a, b) => b.startsAt.localeCompare(a.startsAt)), [games]); useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -139,8 +150,9 @@ export function CardScan({ if (!item) return; try { const small = await previewOf(item.file); - const read = await api.scanCard(orgId, small, eventId); + 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; @@ -172,10 +184,22 @@ export function CardScan({
-
-
{t.cardScan.title}
-
{eventTitle}
-
+
{t.cardScan.title}
+ setQuery(e.target.value)} @@ -218,6 +242,9 @@ export function CardScan({

{t.cardScan.help} {t.cardScan.jpeg} + {roster === null && {t.cardScan.rosterOpen}} + {roster === 0 && {t.cardScan.rosterNone}} + {typeof roster === "number" && roster > 0 && {t.cardScan.roster(roster)}} {running && {t.cardScan.scanning(done, total)}}

{note &&

{note}

} @@ -256,7 +283,7 @@ export function CardScan({ disabled={selected.size === 0} onClick={() => { const files = [...selected].flatMap((index) => (items[index] ? [items[index].file] : [])); - onImport(files); + onImport(files, gameId); setSent(t.cardScan.sent(files.length)); setSelected(new Set()); }} diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index 11f8b39..869a15f 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -586,8 +586,8 @@ export function LibraryPage() { api={api} orgId={orgId} eventId={uploadInto} - eventTitle={[openEvent.home, openEvent.away].filter(Boolean).join(" × ")} - onImport={(files) => uploads.add(files, uploadInto)} + games={events.some((e) => e.id === openEvent.id) ? events : [openEvent, ...events]} + onImport={(files, id) => uploads.add(files, id)} onClose={() => setCardOpen(false)} /> )} diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 8d71959..3f05d9d 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -456,8 +456,10 @@ export interface LookupFace { clear: boolean; } -/** One photo from a card, read and not kept: clear faces, the shirt number, and the known person. */ +/** 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. */ + roster: number | null; faces: { box: { x0: number; y0: number; x1: number; y1: number }; number: string | null; -- 2.47.3