Folder search: limit face names to the chosen game #16

Merged
spark merged 1 commits from task/scan-one-game into main 2026-10-17 18:53:47 +01:00
9 changed files with 143 additions and 25 deletions

No files matched your search

+7 -2
View File
@@ -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
+18 -4
View File
@@ -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<string, { at: number; ids: string[] | null }>();
const rosterFor = 10 * 60_000;
const roster = async (eventId: string): Promise<string[] | null> => {
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<string, string>();
return {
roster: ids ? ids.length : ids,
faces: read.faces.map((f, i) => {
const hit = hits[i];
return {
+48
View File
@@ -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<string[] | null> {
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;
}
+17 -2
View File
@@ -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);
+4
View File
@@ -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",
+7 -4
View File
@@ -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(
<CardScan
api={{ scanCard } as unknown as ApiClient}
orgId="org"
eventId="game"
eventTitle="CDE GIL Eanes × CD Feirense"
games={[{ id: "game", home: "CDE GIL Eanes", away: "CD Feirense", homeShort: "GIL", awayShort: "CDF", startsAt: "2026-10-17T15:00:00.000Z" } as EventSummary]}
onImport={onImport}
onClose={() => {}}
/>,
@@ -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();
});
});
+37 -10
View File
@@ -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<Blob> {
* 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<HTMLInputElement>(null);
@@ -87,6 +93,11 @@ export function CardScan({
const [selected, setSelected] = useState<Set<number>>(new Set());
const [note, setNote] = useState<string | null>(null);
const [sent, setSent] = useState<string | null>(null);
const [gameId, setGameId] = useState(eventId);
const [roster, setRoster] = useState<number | null | undefined>(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({
<div role="dialog" aria-modal="true" aria-label={t.cardScan.title} className="fixed inset-0 z-30 flex flex-col bg-black/80 p-4">
<div className="mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col border border-black bg-panel">
<div className="flex flex-wrap items-center gap-3 border-b border-line px-3 py-2">
<div>
<div className="text-[13px] text-ink">{t.cardScan.title}</div>
<div className="text-[11px] text-faint">{eventTitle}</div>
</div>
<div className="text-[13px] text-ink">{t.cardScan.title}</div>
<select
aria-label={t.cardScan.game}
value={gameId}
onChange={(e) => {
setGameId(e.target.value);
setRoster(undefined);
}}
className="h-7 max-w-[280px] border border-black bg-cell px-1.5 text-[12px] text-ink"
>
{choices.map((game) => (
<option key={game.id} value={game.id}>
{gameLabel(game)}
</option>
))}
</select>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
@@ -218,6 +242,9 @@ export function CardScan({
</div>
<p className="px-3 py-2 text-[12px] text-muted">
{t.cardScan.help} {t.cardScan.jpeg}
{roster === null && <span className="ml-2 text-ink">{t.cardScan.rosterOpen}</span>}
{roster === 0 && <span className="ml-2 text-ink">{t.cardScan.rosterNone}</span>}
{typeof roster === "number" && roster > 0 && <span className="ml-2 text-ink">{t.cardScan.roster(roster)}</span>}
{running && <span className="ml-2 font-mono text-ink">{t.cardScan.scanning(done, total)}</span>}
</p>
{note && <p className="px-3 pb-2 text-[12px] text-danger">{note}</p>}
@@ -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());
}}
+2 -2
View File
@@ -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)}
/>
)}
+3 -1
View File
@@ -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;