Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96deacd7b6 | ||
|
|
ad06967bdb | ||
|
|
404ef90a3e | ||
|
|
333652caba |
No files matched your search
+19
-5
@@ -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;
|
||||
};
|
||||
|
||||
@@ -159,8 +159,20 @@ 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).
|
||||
* `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, 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 (
|
||||
@@ -169,6 +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 (${only}::uuid[] IS NULL OR p.id = ANY(${only}::uuid[]))
|
||||
) s
|
||||
WHERE score >= ${match - POSSIBLE_BELOW}
|
||||
ORDER BY score DESC
|
||||
|
||||
@@ -6,7 +6,8 @@ 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 { 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";
|
||||
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
@@ -105,11 +106,23 @@ 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.
|
||||
* 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");
|
||||
@@ -119,11 +132,14 @@ 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 && ids.length ? ids : null))[0] ?? null) : null)),
|
||||
);
|
||||
const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>();
|
||||
return {
|
||||
slots: scanSlots(),
|
||||
roster: ids ? ids.length : ids,
|
||||
faces: read.faces.map((f, i) => {
|
||||
const hit = hits[i];
|
||||
return {
|
||||
|
||||
@@ -144,3 +144,91 @@ 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 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<string[] | null> {
|
||||
const ctx = await numberContext(db, eventId);
|
||||
if (!ctx) return null;
|
||||
const ids = new Set<string>();
|
||||
let squad = 0;
|
||||
if (ctx.teamIds.length) {
|
||||
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)
|
||||
)
|
||||
)`;
|
||||
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;
|
||||
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 clubIds = 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 (!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<string[]> {
|
||||
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<string>();
|
||||
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];
|
||||
}
|
||||
@@ -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<JerseyModel>;
|
||||
|
||||
constructor(models: JerseyModel[]) {
|
||||
this.pool = new LeastBusy(models);
|
||||
}
|
||||
|
||||
read(original: string, box: Box): Promise<JerseyReading> {
|
||||
return this.pool.use((model) => model.read(original, box));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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()).toMatchObject({ roster: null, faces: [] });
|
||||
|
||||
await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: false } });
|
||||
res = await post();
|
||||
@@ -159,6 +159,56 @@ 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("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);
|
||||
|
||||
@@ -620,6 +620,13 @@ 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
|
||||
? "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",
|
||||
search: "Nome, clube ou número",
|
||||
|
||||
@@ -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({ 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(
|
||||
<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(/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/ }));
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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) => {
|
||||
@@ -131,30 +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, eventId);
|
||||
item.faces = read.faces;
|
||||
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<void>((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);
|
||||
};
|
||||
@@ -172,10 +196,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 +254,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 +295,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());
|
||||
}}
|
||||
|
||||
@@ -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)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -456,8 +456,12 @@ 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 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 };
|
||||
number: string | null;
|
||||
|
||||
Reference in new issue
Block a user