From ac88d2445d0e823b82d7e3d92d13e84807577324 Mon Sep 17 00:00:00 2001 From: spark Date: Wed, 21 Oct 2026 20:37:41 +0100 Subject: [PATCH] Recognize a player from the club they were at that season. The same person keeps one record when they change club, and the shirt number stays the one worn that season. Liga squads are read for every season still published, and face processes grow until the CPU is about 99% full. --- apps/api/src/faces/numbers.ts | 5 + apps/api/src/faces/process.ts | 4 +- apps/api/src/faces/service.ts | 46 ++++++- apps/api/src/lib/capacity.ts | 7 +- apps/api/src/sports/identity.test.ts | 31 +++++ apps/api/src/sports/identity.ts | 22 ++++ apps/api/src/sports/service.ts | 183 ++++++++++++++++++++++++--- apps/api/src/worker.ts | 9 +- apps/api/test/capacity.test.ts | 4 +- docs/ARCHITECTURE.md | 15 ++- 10 files changed, 289 insertions(+), 37 deletions(-) create mode 100644 apps/api/src/sports/identity.test.ts create mode 100644 apps/api/src/sports/identity.ts diff --git a/apps/api/src/faces/numbers.ts b/apps/api/src/faces/numbers.ts index 97304d8..ac29aa8 100644 --- a/apps/api/src/faces/numbers.ts +++ b/apps/api/src/faces/numbers.ts @@ -232,6 +232,11 @@ export async function rosterOf(db: Db, eventId: string): Promise r.id); } + /** + * Games to look at again after a new headshot. A player is only compared with games of clubs they have + * played for. Someone typed by hand (no squad row) is still compared with the last 45 days. + */ + private async eventsForReference(person: { organizationId: string; sportsPlayerId: string | null }, since: Date) { + const { db } = this.deps; + const recent = () => db.event.findMany({ where: { organizationId: person.organizationId, startsAt: { gte: since } }, select: { id: true } }); + if (!person.sportsPlayerId) return recent(); + const mine = await db.sportsPlayer.findUnique({ + where: { id: person.sportsPlayerId }, + select: { teamId: true, externalId: true, birthDate: true, fullName: true }, + }); + if (!mine) return recent(); + const match: ({ teamId: string } | { externalId: string } | { birthDate: string; fullName: string })[] = [{ teamId: mine.teamId }]; + if (mine.externalId) match.push({ externalId: mine.externalId }); + if (mine.birthDate && mine.fullName) match.push({ birthDate: mine.birthDate, fullName: mine.fullName }); + const mates = await db.sportsPlayer.findMany({ where: { OR: match }, select: { teamId: true } }); + const teamIds = [...new Set(mates.map((m) => m.teamId))]; + if (!teamIds.length) return recent(); + return db.event.findMany({ + where: { + organizationId: person.organizationId, + startsAt: { gte: since }, + OR: [{ homeTeamId: { in: teamIds } }, { awayTeamId: { in: teamIds } }], + }, + select: { id: true }, + }); + } + /** Reads a reference photo: the largest face becomes the person's reference. Never throws. */ async processReference(personId: string): Promise { const { db, storage, engine, log } = this.deps; @@ -928,7 +957,7 @@ export class FaceService { await this.recomputePerson(personId); // Open groups of the last weeks may now have a suggestion. const since = new Date(Date.now() - 45 * 86_400_000); - const events = await db.event.findMany({ where: { organizationId: person.organizationId, startsAt: { gte: since } }, select: { id: true } }); + const events = await this.eventsForReference(person, since); for (const e of events) { await this.refreshSuggestions(e.id); this.deps.broadcaster.library(person.organizationId, { type: "faces.updated", eventId: e.id }); @@ -1167,9 +1196,15 @@ export class FaceWorker { constructor( private readonly service: FaceService, - private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger; heartbeat?: () => void }, + private readonly opts: { concurrency: number | (() => number); intervalMs: number; log: IngestLogger; heartbeat?: () => void }, ) {} + /** Places to keep busy. A function follows a pool that grows as the CPU stays under its limit. */ + private places(): number { + const n = typeof this.opts.concurrency === "function" ? this.opts.concurrency() : this.opts.concurrency; + return Math.max(1, n); + } + /** Lets the API tell a dead worker from a long queue. Throttled: the tick itself is every second. */ private beat(): void { if (!this.opts.heartbeat) return; @@ -1219,9 +1254,10 @@ export class FaceWorker { }); } }; - const shared = this.opts.concurrency > 1; - if (shared && this.videosInFlight === 0 && this.inFlight < this.opts.concurrency) await startVideo(); - const ids = await this.service.claim(this.opts.concurrency - this.inFlight - (shared ? this.videosInFlight : 0)); + const places = this.places(); + const shared = places > 1; + if (shared && this.videosInFlight === 0 && this.inFlight < places) await startVideo(); + const ids = await this.service.claim(places - this.inFlight - (shared ? this.videosInFlight : 0)); for (const id of ids) { this.inFlight++; void this.service.process(id).finally(() => { diff --git a/apps/api/src/lib/capacity.ts b/apps/api/src/lib/capacity.ts index f170e80..d37f6a6 100644 --- a/apps/api/src/lib/capacity.ts +++ b/apps/api/src/lib/capacity.ts @@ -45,10 +45,9 @@ export function planCapacity( return { cpus, memoryGb: Math.round(memoryGb * 10) / 10, - // Face binaries use the cores and wait idle when there is nothing to analyse. Their results are committed - // by this one Node thread, which also uploads to ZeroZero. Dozens at once stall that thread: deliveries - // fail with "fetch failed" and face transactions expire. FACES_PROCESSES in the environment still overrides. - faces: set.faces ?? clamp(Math.min(cpus * 0.9, byMemory("faces", 0.5)), 2, 6), + // One face process per core, added while the CPU is under about 99% (GrowingFacePool). The model is + // about 0.8 GB, so a small container stops sooner. FACES_PROCESSES in the environment still overrides. + faces: set.faces ?? Math.max(1, Math.min(Math.max(1, Math.floor(cpus * 0.99)), byMemory("faces", 0.7))), ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32), archive: set.archive ?? clamp(Math.min(cpus * 0.3, byMemory("archive", 0.2)), 2, 32), // A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share. diff --git a/apps/api/src/sports/identity.test.ts b/apps/api/src/sports/identity.test.ts new file mode 100644 index 0000000..73dbc28 --- /dev/null +++ b/apps/api/src/sports/identity.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { samePlayer, type PlayerIdentity } from "./identity.js"; + +const row = (over: Partial): PlayerIdentity => ({ + externalId: null, + birthDate: null, + fullName: null, + teamId: "team", + name: "Zalazar", + ...over, +}); + +describe("samePlayer", () => { + it("follows the federation id from one club to another", () => { + const then = row({ externalId: "p1", teamId: "feirense", name: "Zalazar", fullName: "Rodrigo Zalazar" }); + const now = row({ externalId: "p1", teamId: "sporting", name: "Zalazar", fullName: "Rodrigo Zalazar Martinez" }); + expect(samePlayer(then, now)).toBe(true); + }); + + it("uses the birth date and full name when the id differs", () => { + const then = row({ birthDate: "1999-08-12", fullName: "Rodrigo Zalazar Martínez", teamId: "feirense" }); + const now = row({ externalId: "other", birthDate: "1999-08-12", fullName: "Rodrigo Zalazar Martinez", teamId: "sporting" }); + expect(samePlayer(then, now)).toBe(true); + }); + + it("does not treat two shirt names at different clubs as one person", () => { + const a = row({ name: "Silva", fullName: "Rui Silva", teamId: "a" }); + const b = row({ name: "Silva", fullName: "João Silva", teamId: "b" }); + expect(samePlayer(a, b)).toBe(false); + }); +}); diff --git a/apps/api/src/sports/identity.ts b/apps/api/src/sports/identity.ts new file mode 100644 index 0000000..5198937 --- /dev/null +++ b/apps/api/src/sports/identity.ts @@ -0,0 +1,22 @@ +/** A squad row, enough to tell one human from another across clubs and seasons. */ +export interface PlayerIdentity { + externalId: string | null; + birthDate: string | null; + fullName: string | null; + teamId: string; + name: string; +} + +const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim(); + +/** + * The same human: the federation's id (stable when they change club), or the same birth date and full name. + * The same shirt name in the same club is the last resort. A shirt name alone is not, and neither is today's club. + */ +export function samePlayer(a: PlayerIdentity, b: PlayerIdentity): boolean { + if (a.externalId && a.externalId === b.externalId) return true; + const left = fold(a.fullName ?? ""); + const right = fold(b.fullName ?? ""); + if (a.birthDate && left && a.birthDate === b.birthDate && left === right) return true; + return a.teamId === b.teamId && a.name === b.name; +} diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index e0f2eeb..527e48a 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -9,6 +9,7 @@ import { badRequest, notFound } from "../lib/errors.js"; import { waitUntil } from "../lib/idle.js"; import type { LocalStorage } from "../storage/storage.js"; import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js"; +import { samePlayer } from "./identity.js"; import { tallyOf, tallySquadPhotos } from "./squadPhotos.js"; import { type Fetch, @@ -193,6 +194,8 @@ export class SportsService { /** Squads already on file are skipped. An empty or failed read is tried again next process, not in a loop. */ private readonly squadClaimed = new Set(); + /** Competition-seasons whose team lists were read to the end. The current season is never marked done while empty. */ + private readonly registerDone = new Set(); /** * Liga squads for seasons whose games are already stored but whose player lists were never read. @@ -231,6 +234,79 @@ export class SportsService { return changed; } + /** + * Every Liga club and every player the federation still publishes, season by season, newest first. + * A photo of a club five years ago then has that season's squad, including players who have since moved. + * Stops at the first past season that lists no teams. The current season being empty (pre-season) does not stop it. + * `stopped` is checked between requests so a shutdown leaves within one call. + */ + async backfillLigaRegister(stopped: () => boolean): Promise { + await this.ensureCatalog(); + const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "LIGA" } }); + let season = seasonOf(new Date()); + let saved = 0; + for (let year = 0; year < 25 && !stopped(); year++) { + let sawTeams = false; + let failed = 0; + for (const c of comps) { + if (stopped()) return saved; + const key = `${c.externalId}:${season}`; + if (this.registerDone.has(key)) { + sawTeams = true; + continue; + } + let teams: TeamData[]; + try { + teams = await this.liga.teams(c.externalId, season); + } catch (err) { + const missing = err instanceof ProviderHttpError ? err.status === 404 : err instanceof Error && err.message.startsWith("liga: unexpected"); + if (missing) { + this.registerDone.add(key); + continue; + } + failed++; + this.deps.log.warn({ err, competition: c.externalId, season }, "sports: liga teams not read"); + continue; + } + if (!teams.length) { + this.registerDone.add(key); + continue; + } + sawTeams = true; + let complete = true; + for (const t of teams) { + if (stopped()) return saved; + const teamId = await this.upsertTeam("LIGA", t); + await this.deps.db.sportsCompetitionTeam.upsert({ + where: { competitionId_teamId_season: { competitionId: c.id, teamId, season } }, + create: { competitionId: c.id, teamId, season }, + update: {}, + }); + const have = await this.deps.db.sportsPlayer.count({ where: { teamId, season } }); + if (have > 0) continue; + const claim = `${teamId}:${season}`; + if (this.squadClaimed.has(claim)) continue; + this.squadClaimed.add(claim); + try { + saved += await this.savePlayers(teamId, season, await this.liga.squad(t.externalId, season), "api"); + } catch (err) { + complete = false; + this.squadClaimed.delete(claim); + this.deps.log.warn({ err, team: t.name, season }, "sports: liga squad not read"); + } + } + if (complete) this.registerDone.add(key); + } + if (failed === comps.length && comps.length) break; + if (year > 0 && !sawTeams) break; + const start = Number(season.slice(0, 4)) - 1; + if (!Number.isFinite(start) || start < 2000) break; + season = `${start}${start + 1}`; + } + if (saved) this.deps.log.info({ saved }, "sports: liga register imported"); + return saved; + } + /** * A whole past FPA season (the archive's folders of other seasons): the federation's national games of every * level, club by club. It starts from the clubs of today's agenda and follows every club met in those games, so @@ -787,10 +863,12 @@ export class SportsService { // --- squads ----------------------------------------------------------------------------------------------------- - /** A team's current squad: its latest season, without the players who left. */ - async squad(teamId: string) { + /** A team's squad for one season, or its latest when none is asked. Players who left are left out. */ + async squad(teamId: string, season?: string) { // Season, not updatedAt: reading an old season must not make it look like the current squad. - const latest = await this.deps.db.sportsPlayer.findFirst({ where: { teamId }, orderBy: { season: "desc" }, select: { season: true } }); + const latest = season + ? { season } + : await this.deps.db.sportsPlayer.findFirst({ where: { teamId }, orderBy: { season: "desc" }, select: { season: true } }); if (!latest) return []; const players = await this.deps.db.sportsPlayer.findMany({ where: { teamId, season: latest.season, goneAt: null } }); // Shirt numbers, then the handball officials by letter (A, B, …), then those without either. @@ -801,7 +879,10 @@ export class SportsService { /** Both teams of an event, with the person each player is in the organisation (for tagging by number). */ async eventSquads(eventId: string) { const { db } = this.deps; - const event = await db.event.findUnique({ where: { id: eventId }, include: { homeTeam: true, awayTeam: true } }); + const event = await db.event.findUnique({ + where: { id: eventId }, + include: { homeTeam: true, awayTeam: true, fixture: { select: { season: true } } }, + }); if (!event) throw notFound("event_not_found"); const sides = [] as { side: "home" | "away"; team: { id: string; name: string; abbreviation: string | null; logoUrl: string | null }; players: unknown[] }[]; // Photos of each person in this event: faces confirmed as them, and faces the system takes for them (the @@ -820,12 +901,9 @@ export class SportsService { ["away", event.awayTeam], ] as const) { if (!team) continue; - const players = await this.squad(team.id); - const people = await db.person.findMany({ - where: { organizationId: event.organizationId, sportsPlayerId: { in: players.map((p) => p.id) } }, - select: { id: true, sportsPlayerId: true }, - }); - const personOf = new Map(people.map((p) => [p.sportsPlayerId, p.id])); + const season = event.fixture?.season ?? seasonOf(event.startsAt); + const players = await this.squad(team.id, season); + const personOf = await this.peopleOf(event.organizationId, players); sides.push({ side, team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl }, @@ -873,7 +951,7 @@ export class SportsService { include: { homeTeam: true, awayTeam: true, - fixture: { select: { id: true, externalId: true, round: true, officials: true, competition: { select: { provider: true, externalId: true, season: true } } } }, + fixture: { select: { id: true, season: true, externalId: true, round: true, officials: true, competition: { select: { provider: true, externalId: true, season: true } } } }, organization: { select: { biometricsEnabled: true, codeGenerator: true } }, }, }); @@ -883,10 +961,10 @@ export class SportsService { const result = { created: 0, updated: 0, headshots: 0 }; const headshots: { personId: string; url: string }[] = []; // Liga squads are read again right now (players and coaching staff), not only on the 6-hourly refresh. + const season = event.fixture?.season ?? seasonOf(event.startsAt); for (const team of [event.homeTeam, event.awayTeam]) { if (team?.provider !== "LIGA") continue; try { - const season = event.fixture?.competition.provider === "LIGA" ? event.fixture.competition.season : seasonOf(new Date()); await this.savePlayers(team.id, season, await this.liga.squad(team.externalId, season), "api"); } catch (err) { log.warn({ err, team: team.id }, "sports: liga squad re-read failed"); @@ -895,7 +973,7 @@ export class SportsService { for (const team of [event.homeTeam, event.awayTeam]) { if (!team) continue; const club = settings.teamNames[team.id] ?? team.name; - for (const p of await this.squad(team.id)) { + for (const p of await this.squad(team.id, season)) { await this.linkSquadPerson(orgId, team, club, p, event.organization.biometricsEnabled, headshots, result); } } @@ -987,6 +1065,7 @@ export class SportsService { const { db, log } = this.deps; let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } }); let created = false; + if (!person) person = await this.personForIdentity(orgId, p); if (!person) { const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } }); if (byName && !byName.sportsPlayerId && (!byName.club || byName.club === club || byName.club === team.name)) person = byName; @@ -1009,8 +1088,10 @@ export class SportsService { } } } + const linkedSeason = person.sportsPlayerId === p.id ? p.season : await this.seasonOfLinked(person.sportsPlayerId); + const newer = !linkedSeason || p.season >= linkedSeason; if (created) result.created++; - else if (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id) { + else if (newer && (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id)) { person = await db.person.update({ where: { id: person.id }, data: { club, number: p.number, sportsPlayerId: p.id } }); result.updated++; } @@ -1027,6 +1108,55 @@ export class SportsService { if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo }); } + /** The person already created for this human at another club or in another season. */ + private async personForIdentity(orgId: string, p: SportsPlayer) { + const match: ({ externalId: string } | { birthDate: string; fullName: string })[] = []; + if (p.externalId) match.push({ externalId: p.externalId }); + if (p.birthDate && p.fullName) match.push({ birthDate: p.birthDate, fullName: p.fullName }); + if (!match.length) return null; + const rows = await this.deps.db.sportsPlayer.findMany({ where: { OR: match }, select: { id: true } }); + if (!rows.length) return null; + return this.deps.db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: rows.map((r) => r.id) } } }); + } + + private async seasonOfLinked(sportsPlayerId: string | null): Promise { + if (!sportsPlayerId) return null; + const linked = await this.deps.db.sportsPlayer.findUnique({ where: { id: sportsPlayerId }, select: { season: true } }); + return linked?.season ?? null; + } + + /** Which person is each squad row: the row itself, or the same human at the club they play for now. */ + private async peopleOf(orgId: string, players: SportsPlayer[]): Promise> { + const out = new Map(); + if (!players.length) return out; + const externalIds = [...new Set(players.map((p) => p.externalId).filter((id): id is string => !!id))]; + const births = players.filter((p): p is SportsPlayer & { birthDate: string; fullName: string } => !!p.birthDate && !!p.fullName); + const keys = await this.deps.db.sportsPlayer.findMany({ + where: { + OR: [ + { id: { in: players.map((p) => p.id) } }, + ...(externalIds.length ? [{ externalId: { in: externalIds } }] : []), + ...births.map((p) => ({ birthDate: p.birthDate, fullName: p.fullName })), + ], + }, + select: { id: true, externalId: true, birthDate: true, fullName: true, teamId: true, name: true }, + }); + if (!keys.length) return out; + const people = await this.deps.db.person.findMany({ + where: { organizationId: orgId, sportsPlayerId: { in: keys.map((k) => k.id) } }, + select: { id: true, sportsPlayerId: true }, + }); + const personByPlayer = new Map(people.map((p) => [p.sportsPlayerId, p.id])); + for (const player of players) { + const hit = keys.find((k) => k.id && personByPlayer.has(k.id) && samePlayer(k, player)); + if (hit?.id) { + const personId = personByPlayer.get(hit.id); + if (personId) out.set(player.id, personId); + } + } + return out; + } + /** * Squad rows that no person of the organisation represents yet become people (and, a few at a time, reference * photos). A player already known by the federation's id is not created again under an old club. Only @@ -1047,6 +1177,11 @@ export class SportsService { AND ( mine.id = sp.id OR (sp.external_id IS NOT NULL AND mine.external_id = sp.external_id) + OR ( + sp.birth_date IS NOT NULL AND sp.full_name IS NOT NULL + AND mine.birth_date = sp.birth_date + AND lower(mine.full_name) = lower(sp.full_name) + ) OR (mine.team_id = sp.team_id AND mine.name = sp.name) ) ) @@ -1182,6 +1317,7 @@ export class SportsWorker { private timer: ReturnType | undefined; private stopped = false; private ticking = false; + private filling = false; private lastRefresh = 0; constructor( @@ -1190,6 +1326,7 @@ export class SportsWorker { ) {} start(): void { + void this.fillRegister(); const tick = async () => { this.ticking = true; try { @@ -1211,10 +1348,26 @@ export class SportsWorker { this.timer = setTimeout(tick, 5_000); } + /** Past seasons of every Liga club, then the people those rows are. One pass per process; the tick keeps up afterwards. */ + private async fillRegister(): Promise { + this.filling = true; + try { + await this.service.backfillLigaRegister(() => this.stopped); + while (!this.stopped) { + const n = await this.service.linkStoredSquads(24); + if (!n) break; + } + } catch (err) { + this.opts.log.warn({ err }, "sports: register not filled"); + } finally { + this.filling = false; + } + } + async stop(timeoutMs = 25_000): Promise { this.stopped = true; if (this.timer) clearTimeout(this.timer); - const drained = await waitUntil(() => !this.ticking, { timeoutMs }); + const drained = await waitUntil(() => !this.ticking && !this.filling, { timeoutMs }); if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running"); } } diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index d499124..c27b44c 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -14,7 +14,7 @@ import { SecretBox } from "./delivery/secrets.js"; import { DeliveryService, DeliveryWorker } from "./delivery/service.js"; import { RenderPool, RenderProcess } from "./develop/engine.js"; import { DevelopService, RenderWorker } from "./develop/service.js"; -import { FacePool, FaceProcess } from "./faces/process.js"; +import { FaceProcess, GrowingFacePool } from "./faces/process.js"; import { AutopilotService, AutopilotWorker } from "./autopilot/service.js"; import { SportsService, SportsWorker } from "./sports/service.js"; import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js"; @@ -126,15 +126,16 @@ const invoices = new InvoicingWorker(new InvoicingService({ db, secrets, log, no const faceEngine = config.FACES_BIN && config.FACES_MODELS_DIR - ? new FacePool( - Array.from({ length: capacity.faces }, () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER })), + ? new GrowingFacePool( + () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER }), + capacity.faces, ) : undefined; const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined; if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded"); const faces = faceEngine ? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), { - concurrency: capacity.faces, + concurrency: () => faceEngine?.size ?? 1, intervalMs: 1000, log, heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT), diff --git a/apps/api/test/capacity.test.ts b/apps/api/test/capacity.test.ts index 170b6a7..e24f6cd 100644 --- a/apps/api/test/capacity.test.ts +++ b/apps/api/test/capacity.test.ts @@ -8,8 +8,8 @@ describe("capacity", () => { const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB }); const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * GB }); expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, autopilot: 2, delivery: 4 }); - expect(big).toMatchObject({ cpus: 32, faces: 6, ingest: 8, archive: 9, archiveBurst: 91, render: 16, autopilot: 16, delivery: 8 }); - expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 6, archiveBurst: 91, archiveDownloads: 960 }); + expect(big).toMatchObject({ cpus: 32, faces: 31, ingest: 8, archive: 9, archiveBurst: 91, render: 16, autopilot: 16, delivery: 8 }); + expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 47, archiveBurst: 91, archiveDownloads: 960 }); // A fixed ARCHIVE_CONCURRENCY never holds a backlog back; downloads run many at once even on a small machine. expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 }); }); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7763992..d0ea82f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -187,7 +187,8 @@ Only for organizations whose owner switched it on with a recorded legal basis (b Each photo that arrives is queued (`photos.faces_status`); the worker reads the last 30 days first (when the photo was taken, or the game's date when the camera wrote none), newest game first, and only then the older archive. A folder of an old season that has just been indexed waits until that month is clear, then comes ahead of the -archive that has been waiting. Asking to analyse one event still puts it first. A photo whose analysis failed is +archive that has been waiting. The worker starts a few face processes and adds more while the CPU stays under +about 99%, stopping sooner when memory (the model) runs short. Asking to analyse one event still puts it first. A photo whose analysis failed is queued again a few at a time, after it has been quiet for six hours, recent games first. Confirming a face improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the detector that finds a face in the photo is not retrained. The worker runs `workers/faces` on the original: @@ -236,7 +237,9 @@ number for that event's context: old game gets the number worn then, even for players who have since left. - **A game whose two clubs are known** (teams already stored, or the home and away names matching one team of that sport each): only that season's squad — players and coaches — and the referees of the fixture, when they - already have a face. A face none of them explains stays unnamed. It is never someone from another club. + already have a face. A player who has since moved is included when that season's list has them (the same + federation id, or the same birth date and full name), with the shirt number of that season. A face none of + them explains stays unnamed. It is never someone who was not at either club that season. A session (no away side), an exhibition, or a name that matches no team has no sheet: the face alone, against everyone of that sport, and only a clearly stronger match. The shirt, when it is read, stays with those two clubs. Then what the shirts clearly read (three or more clear readings) in the person's confirmed photos of the same @@ -259,7 +262,8 @@ hand-drawn boxes. every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation: - **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup. Gives teams, squads (numbers, - positions, official headshots) and the season's fixtures. + positions, official headshots) and the season's fixtures. On start the worker walks every season the federation + still publishes, club by club, so a past season keeps the squad and the shirt numbers of that year. - **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence @@ -297,8 +301,9 @@ What organisations do with it: from public https hosts (private, loopback and link-local addresses refused, redirects checked again, 5 MB, 10 s) and cached 5 minutes. For a generic event the form lists the day's entries; picking one fills name, venue, city and time and suggests a caption ("Title, Venue, City.") to edit. Repeating entries show their first date only. -- **People from squads:** squads become people (club, number, `sportsPlayerId`). With biometrics on, the Liga - headshot becomes the reference photo, and number suggestions for faces use the event's squads. +- **People from squads:** one person per human. A later season at another club updates the club and the shirt + number; an older season does not. The number shown on a photo is still that season's. With biometrics on, the + Liga headshot becomes the reference photo, and number suggestions for faces use the event's squads. ## Working without a network (desktop app) -- 2.47.3