Compare commits

...
Author SHA1 Message Date
spark 8f6af48055 Keep national teams and sessions off the club squads.
ci / rust (pull_request) Successful in 13m11s
ci / typescript (pull_request) Failing after 14m56s
A FPA seleção is its own list for the season: the women's team, the men's team and an age group do not share a roster or a shirt number. A session of that team has no match number. A gala still has no list.
2026-10-21 20:52:54 +01:00
spark ac88d2445d Recognize a player from the club they were at that season.
ci / rust (pull_request) Successful in 12m25s
ci / typescript (pull_request) Failing after 14m4s
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.
2026-10-21 20:37:41 +01:00
spark 81faa115ec Merge pull request 'Clear wrong face names without re-scoring every game' (#98) from task/faces-roster into main
ci / rust (push) Successful in 12m14s
ci / typescript (push) Failing after 15m56s
2026-10-21 20:19:00 +01:00
spark 528666c13c Merge pull request 'Name a face only from the clubs of that game' (#97) from task/faces-roster into main
ci / rust (push) Successful in 11m48s
ci / typescript (push) Failing after 14m50s
Name a face only from the clubs of that game.
2026-10-21 20:12:54 +01:00
12 changed files with 443 additions and 48 deletions

No files matched your search

+96 -5
View File
@@ -1,6 +1,7 @@
import { isExhibition, isNationalSide, seasonOf, teamsNamed } from "../archive/match.js"; import { isExhibition, isNationalSide, seasonOf, teamsNamed } from "../archive/match.js";
import type { Db } from "../db.js"; import type { Db } from "../db.js";
import { normLabel } from "../jersey/service.js"; import { normLabel } from "../jersey/service.js";
import { selectionKey, selectionNeedles } from "./selection.js";
import { eventSport } from "./sport.js"; import { eventSport } from "./sport.js";
import { JERSEY_MIN_SCORE, majorityNumber } from "./votes.js"; import { JERSEY_MIN_SCORE, majorityNumber } from "./votes.js";
@@ -18,6 +19,11 @@ export interface NumberContext {
competition: string; competition: string;
/** A national team's game or session: club numbers never apply. */ /** A national team's game or session: club numbers never apply. */
national: boolean; national: boolean;
/**
* The national team when the folder names one ("snaf", "snam", "m18").
* Null when the event only says "Portugal": the country is not an age group.
*/
side: string | null;
/** The season now: only then does the number typed on the person (with no season of its own) apply. */ /** The season now: only then does the number typed on the person (with no season of its own) apply. */
current: boolean; current: boolean;
/** Linked to an official fixture: that competition's squad numbers come before what other shirts read. */ /** Linked to an official fixture: that competition's squad numbers come before what other shirts read. */
@@ -51,12 +57,19 @@ export async function numberContext(db: Db, eventId: string, now = new Date()):
// An event that is not a game (a gala, a session, a presentation): nobody is known by a shirt there, only by face. // An event that is not a game (a gala, a session, a presentation): nobody is known by a shirt there, only by face.
if (!e || !e.away?.trim()) return null; if (!e || !e.away?.trim()) return null;
const season = e.fixture?.season ?? seasonOf(day(e.startsAt)); const season = e.fixture?.season ?? seasonOf(day(e.startsAt));
const national = isNationalEvent(e);
let side: string | null = null;
if (national) {
const folders = await db.cloudFolder.findMany({ where: { eventId }, select: { path: true }, take: 8 });
side = selectionKey([e.home, e.away ?? "", e.competition ?? "", ...folders.map((f) => f.path)]);
}
return { return {
organizationId: e.organizationId, organizationId: e.organizationId,
eventId, eventId,
season, season,
competition: competitionKey(e), competition: competitionKey(e),
national: isNationalEvent(e), national,
side,
current: season === seasonOf(day(now)), current: season === seasonOf(day(now)),
official: !!e.fixture, official: !!e.fixture,
teamIds: [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t), teamIds: [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t),
@@ -153,7 +166,10 @@ export async function numbersIn(db: Db, ctx: NumberContext, personIds: string[],
where: { organizationId: ctx.organizationId, startsAt: { gte: from, lt: to } }, where: { organizationId: ctx.organizationId, startsAt: { gte: from, lt: to } },
select: { id: true, home: true, away: true, competition: true, competitionCode: true }, select: { id: true, home: true, away: true, competition: true, competitionCode: true },
}); });
const same = events.filter((e) => competitionKey(e) === ctx.competition && isNationalEvent(e) === ctx.national).map((e) => e.id); const onSide = ctx.national && ctx.side ? new Set(await eventsOfSide(db, ctx.organizationId, ctx.season, ctx.side)) : null;
const same = events
.filter((e) => (onSide ? onSide.has(e.id) : competitionKey(e) === ctx.competition && isNationalEvent(e) === ctx.national))
.map((e) => e.id);
if (same.length) { if (same.length) {
const faces = await db.face.findMany({ const faces = await db.face.findMany({
where: { photo: { eventId: { in: same } }, group: { personId: { in: rest } }, jerseyNumber: { not: null }, jerseyScore: { gte: JERSEY_MIN_SCORE } }, where: { photo: { eventId: { in: same } }, group: { personId: { in: rest } }, jerseyNumber: { not: null }, jerseyScore: { gte: JERSEY_MIN_SCORE } },
@@ -197,6 +213,51 @@ interface FixtureOfficial {
externalId?: string | null; externalId?: string | null;
} }
/** Events of one national team in a season (the women's senior team is not the men's, and not an age group). */
async function eventsOfSide(db: Db, organizationId: string, season: string, side: string): Promise<string[]> {
const { from, to } = seasonRange(season);
const needles = selectionNeedles(side);
const events = await db.event.findMany({
where: {
organizationId,
startsAt: { gte: from, lt: to },
OR: needles.flatMap((needle) => [
{ home: { contains: needle, mode: "insensitive" } },
{ away: { contains: needle, mode: "insensitive" } },
{ competition: { contains: needle, mode: "insensitive" } },
{ cloudFolders: { some: { path: { contains: needle, mode: "insensitive" } } } },
]),
},
select: { id: true, home: true, away: true, competition: true, cloudFolders: { select: { path: true }, take: 4 } },
});
return events
.filter((e) => selectionKey([e.home, e.away ?? "", e.competition ?? "", ...e.cloudFolders.map((f) => f.path)]) === side)
.map((e) => e.id);
}
/** People already confirmed, with a face, on that national team this season. */
async function peopleConfirmedOnSide(db: Db, organizationId: string, season: string, side: string): Promise<string[]> {
const eventIds = await eventsOfSide(db, organizationId, season, side);
if (!eventIds.length) return [];
const rows = await db.faceGroup.findMany({
where: { eventId: { in: eventIds }, personId: { not: null }, ignoredAt: null },
select: { personId: true, person: { select: { centroid: true } } },
});
return [...new Set(rows.filter((r) => r.personId && r.person && r.person.centroid.length > 0).map((r) => r.personId!))];
}
/** People a session's folders name ("7 - Bebiana Sabino"), when that person already has a face. */
async function peopleNamedHere(db: Db, eventId: string, organizationId: string): Promise<string[]> {
const photos = await db.photo.findMany({ where: { eventId }, select: { players: true } });
const names = [...new Set(photos.flatMap((p) => p.players).map((n) => n.trim()).filter(Boolean))];
if (!names.length) return [];
const people = await db.person.findMany({
where: { organizationId, name: { in: names } },
select: { id: true, centroid: true },
});
return people.filter((p) => p.centroid.length > 0).map((p) => p.id);
}
/** The people a suggestion may name. Null: this event has no roster, so the caller uses the whole list. An empty list is a known squad that has no face on file yet. */ /** The people a suggestion may name. Null: this event has no roster, so the caller uses the whole list. An empty list is a known squad that has no face on file yet. */
export function peopleOnRoster<T extends { id: string }>(people: T[], roster: string[] | null): T[] | null { export function peopleOnRoster<T extends { id: string }>(people: T[], roster: string[] | null): T[] | null {
if (!roster) return null; if (!roster) return null;
@@ -212,6 +273,31 @@ export function peopleOnRoster<T extends { id: string }>(people: T[], roster: st
*/ */
export async function rosterOf(db: Db, eventId: string): Promise<string[] | null> { export async function rosterOf(db: Db, eventId: string): Promise<string[] | null> {
await bindEventTeams(db, eventId); await bindEventTeams(db, eventId);
const event = await db.event.findUnique({
where: { id: eventId },
select: {
organizationId: true,
home: true,
away: true,
competition: true,
startsAt: true,
cloudFolders: { select: { path: true }, take: 8 },
},
});
if (!event) return null;
const side = selectionKey([event.home, event.away ?? "", event.competition ?? "", ...event.cloudFolders.map((f) => f.path)]);
const game = !!event.away?.trim();
// A session, a training, a studio day, or a national team: never a club's squad.
// A gala or a press day names no team, so the caller compares the face on its own.
if (!game && !side) return null;
if (!game || side || isNationalEvent(event)) {
const ids = new Set<string>();
const season = seasonOf(day(event.startsAt));
if (side) for (const id of await peopleConfirmedOnSide(db, event.organizationId, season, side)) ids.add(id);
if (!game) for (const id of await peopleNamedHere(db, eventId, event.organizationId)) ids.add(id);
if (game) for (const id of await officialsOf(db, eventId, event.organizationId)) ids.add(id);
return [...ids];
}
const ctx = await numberContext(db, eventId); const ctx = await numberContext(db, eventId);
if (!ctx) return null; if (!ctx) return null;
const ids = new Set<string>(); const ids = new Set<string>();
@@ -232,6 +318,11 @@ export async function rosterOf(db: Db, eventId: string): Promise<string[] | null
AND ( AND (
squad.id = mine.id squad.id = mine.id
OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id) OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id)
OR (
squad.birth_date IS NOT NULL AND squad.full_name IS NOT NULL
AND mine.birth_date = squad.birth_date
AND lower(mine.full_name) = lower(squad.full_name)
)
OR (squad.team_id = mine.team_id AND squad.name = mine.name) OR (squad.team_id = mine.team_id AND squad.name = mine.name)
) )
)`; )`;
@@ -242,9 +333,9 @@ export async function rosterOf(db: Db, eventId: string): Promise<string[] | null
if (ids.size) return [...ids]; if (ids.size) return [...ids];
if (squad > 0) return []; if (squad > 0) return [];
// No official squad: people typed against these clubs, and only when that set is small enough to be the game. // 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 } }); const named = await db.event.findUnique({ where: { id: eventId }, select: { home: true, away: true, homeShort: true, awayShort: true } });
if (!event) return null; if (!named) return null;
const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(fold); const teams = [named.home, named.away, named.homeShort, named.awayShort].filter((t): t is string => !!t).map(fold);
const people = await db.person.findMany({ const people = await db.person.findMany({
where: { organizationId: ctx.organizationId, club: { not: null }, NOT: { centroid: { isEmpty: true } } }, where: { organizationId: ctx.organizationId, club: { not: null }, NOT: { centroid: { isEmpty: true } } },
select: { id: true, club: true }, select: { id: true, club: true },
+2 -2
View File
@@ -1,8 +1,8 @@
import { cpus } from "node:os"; import { cpus } from "node:os";
import { LeastBusy, LineProcess } from "../lib/line-process.js"; import { LeastBusy, LineProcess } from "../lib/line-process.js";
/** Stop adding face processes once the machine is this full. */ /** Stop adding face processes once the machine is this full. One percent stays free for the rest of the system. */
const CPU_TARGET = 0.97; const CPU_TARGET = 0.99;
interface CpuTimes { interface CpuTimes {
idle: number; idle: number;
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { selectionKey } from "./selection.js";
describe("selectionKey", () => {
it("treats the women's and men's national teams as different teams, whatever the folder calls them", () => {
const women = selectionKey(["/FPA/Fotos/2025_2026/Seleções Nacionais/SNAF/20260409 - POR x MNE"]);
const womenTitle = selectionKey(["Seleção Nacional A Feminina · Sessão"]);
const men = selectionKey(["/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/20250122 - SWE x POR"]);
expect(women).toBe("snaf");
expect(womenTitle).toBe(women);
expect(men).toBe("snam");
expect(men).not.toBe(women);
});
it("keeps an age group apart from the senior teams", () => {
expect(selectionKey(["/FPA/Fotos/2025_2026/Seleções Nacionais/M18/Torneio Tiby/POR_FRA"])).toBe("m18");
});
it("names no team for a club game, a gala, or a gathering", () => {
expect(selectionKey(["Sporting CP", "ABC de Braga", "Andebol 1"])).toBeNull();
expect(selectionKey(["Portugal", "França"])).toBeNull();
expect(selectionKey(["Gala 20250614"])).toBeNull();
expect(selectionKey(["Encontro Nacional sub-14 · Dia 2"])).toBeNull();
});
});
+26
View File
@@ -0,0 +1,26 @@
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
/**
* Which national team a folder or a title is, when it names one.
* "SNAF" and "Seleção Nacional A Feminina" are the same team. A country name alone is not:
* Portugal against France can be the senior women, the senior men, or an age group.
* A gala, a press day, or "Encontro Nacional sub-14" names no team.
*/
export function selectionKey(texts: string[]): string | null {
const f = fold(texts.filter(Boolean).join("\n"));
if (!f) return null;
if (/\bsnaf\b/.test(f) || /selecao nacional a feminina/.test(f) || /selecao feminina/.test(f)) return "snaf";
if (/\bsnam\b/.test(f) || /selecao nacional a masculina/.test(f) || /selecao masculina/.test(f)) return "snam";
if (/\bsna\b/.test(f)) return "snam";
const coded = /\b([mw])(\d{2})\b/.exec(f);
if (coded && /selec/.test(f)) return `${coded[1]}${coded[2]}`;
return null;
}
/** Strings a stored path or title may contain for this team. */
export function selectionNeedles(key: string): string[] {
if (key === "snaf") return ["SNAF", "Seleção Nacional A Feminina", "Seleção Feminina"];
if (key === "snam") return ["SNAM", "SNA", "Seleção Nacional A Masculina", "Seleção Masculina"];
if (/^[mw]\d{2}$/.test(key)) return [key.toUpperCase()];
return [key];
}
+45 -7
View File
@@ -552,8 +552,8 @@ export class FaceService {
const sport = await eventSport(db, eventId); const sport = await eventSport(db, eventId);
const sports = sport ? await peopleSports(db, everyone) : new Map<string, string>(); const sports = sport ? await peopleSports(db, everyone) : new Map<string, string>();
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport); const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
// A game whose clubs are known is named only from that squad. A session (no roster) is compared with // A club game is named only from that season's squad. A national team or a session of one is named only
// everyone of the sport, and only a clearly stronger face: a weak likeness is not a name. // from that team. A gala has no list: the face alone, and only a clearly stronger match.
const sheet = await rosterOf(db, eventId); const sheet = await rosterOf(db, eventId);
const bounded = sheet !== null; const bounded = sheet !== null;
const pool = peopleOnRoster(people, sheet) ?? people; const pool = peopleOnRoster(people, sheet) ?? people;
@@ -636,6 +636,8 @@ export class FaceService {
*/ */
private async suggestByNumber(groupId: string, ctx: NumberContext, read: NumberVote): Promise<{ personId: string; score: number } | null> { private async suggestByNumber(groupId: string, ctx: NumberContext, read: NumberVote): Promise<{ personId: string; score: number } | null> {
const { db } = this.deps; const { db } = this.deps;
// A national team wears its own numbers. The club who has that number this season is someone else.
if (ctx.national) return null;
const eventId = ctx.eventId; const eventId = ctx.eventId;
const event = await db.event.findUnique({ const event = await db.event.findUnique({
where: { id: eventId }, where: { id: eventId },
@@ -904,6 +906,35 @@ export class FaceService {
return rows.map((r) => r.id); return rows.map((r) => 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. */ /** Reads a reference photo: the largest face becomes the person's reference. Never throws. */
async processReference(personId: string): Promise<void> { async processReference(personId: string): Promise<void> {
const { db, storage, engine, log } = this.deps; const { db, storage, engine, log } = this.deps;
@@ -928,7 +959,7 @@ export class FaceService {
await this.recomputePerson(personId); await this.recomputePerson(personId);
// Open groups of the last weeks may now have a suggestion. // Open groups of the last weeks may now have a suggestion.
const since = new Date(Date.now() - 45 * 86_400_000); 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) { for (const e of events) {
await this.refreshSuggestions(e.id); await this.refreshSuggestions(e.id);
this.deps.broadcaster.library(person.organizationId, { type: "faces.updated", eventId: e.id }); this.deps.broadcaster.library(person.organizationId, { type: "faces.updated", eventId: e.id });
@@ -1167,9 +1198,15 @@ export class FaceWorker {
constructor( constructor(
private readonly service: FaceService, 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. */ /** Lets the API tell a dead worker from a long queue. Throttled: the tick itself is every second. */
private beat(): void { private beat(): void {
if (!this.opts.heartbeat) return; if (!this.opts.heartbeat) return;
@@ -1219,9 +1256,10 @@ export class FaceWorker {
}); });
} }
}; };
const shared = this.opts.concurrency > 1; const places = this.places();
if (shared && this.videosInFlight === 0 && this.inFlight < this.opts.concurrency) await startVideo(); const shared = places > 1;
const ids = await this.service.claim(this.opts.concurrency - this.inFlight - (shared ? this.videosInFlight : 0)); 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) { for (const id of ids) {
this.inFlight++; this.inFlight++;
void this.service.process(id).finally(() => { void this.service.process(id).finally(() => {
+3 -4
View File
@@ -45,10 +45,9 @@ export function planCapacity(
return { return {
cpus, cpus,
memoryGb: Math.round(memoryGb * 10) / 10, memoryGb: Math.round(memoryGb * 10) / 10,
// Face binaries use the cores and wait idle when there is nothing to analyse. Their results are committed // One face process per core, added while the CPU is under about 99% (GrowingFacePool). The model is
// by this one Node thread, which also uploads to ZeroZero. Dozens at once stall that thread: deliveries // about 0.8 GB, so a small container stops sooner. FACES_PROCESSES in the environment still overrides.
// fail with "fetch failed" and face transactions expire. 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))),
faces: set.faces ?? clamp(Math.min(cpus * 0.9, byMemory("faces", 0.5)), 2, 6),
ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32), 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), 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. // A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share.
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { samePlayer, type PlayerIdentity } from "./identity.js";
const row = (over: Partial<PlayerIdentity>): 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);
});
});
+22
View File
@@ -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;
}
+168 -15
View File
@@ -9,6 +9,7 @@ import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js"; import { waitUntil } from "../lib/idle.js";
import type { LocalStorage } from "../storage/storage.js"; import type { LocalStorage } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.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 { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
import { import {
type Fetch, 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. */ /** 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<string>(); private readonly squadClaimed = new Set<string>();
/** Competition-seasons whose team lists were read to the end. The current season is never marked done while empty. */
private readonly registerDone = new Set<string>();
/** /**
* Liga squads for seasons whose games are already stored but whose player lists were never read. * 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; 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<number> {
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 * 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 * 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 ----------------------------------------------------------------------------------------------------- // --- squads -----------------------------------------------------------------------------------------------------
/** A team's current squad: its latest season, without the players who left. */ /** A team's squad for one season, or its latest when none is asked. Players who left are left out. */
async squad(teamId: string) { async squad(teamId: string, season?: string) {
// Season, not updatedAt: reading an old season must not make it look like the current squad. // 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 []; if (!latest) return [];
const players = await this.deps.db.sportsPlayer.findMany({ where: { teamId, season: latest.season, goneAt: null } }); 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. // 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). */ /** Both teams of an event, with the person each player is in the organisation (for tagging by number). */
async eventSquads(eventId: string) { async eventSquads(eventId: string) {
const { db } = this.deps; 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"); 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[] }[]; 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 // 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], ["away", event.awayTeam],
] as const) { ] as const) {
if (!team) continue; if (!team) continue;
const players = await this.squad(team.id); const season = event.fixture?.season ?? seasonOf(event.startsAt);
const people = await db.person.findMany({ const players = await this.squad(team.id, season);
where: { organizationId: event.organizationId, sportsPlayerId: { in: players.map((p) => p.id) } }, const personOf = await this.peopleOf(event.organizationId, players);
select: { id: true, sportsPlayerId: true },
});
const personOf = new Map(people.map((p) => [p.sportsPlayerId, p.id]));
sides.push({ sides.push({
side, side,
team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl }, team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl },
@@ -873,7 +951,7 @@ export class SportsService {
include: { include: {
homeTeam: true, homeTeam: true,
awayTeam: 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 } }, organization: { select: { biometricsEnabled: true, codeGenerator: true } },
}, },
}); });
@@ -883,10 +961,10 @@ export class SportsService {
const result = { created: 0, updated: 0, headshots: 0 }; const result = { created: 0, updated: 0, headshots: 0 };
const headshots: { personId: string; url: string }[] = []; const headshots: { personId: string; url: string }[] = [];
// Liga squads are read again right now (players and coaching staff), not only on the 6-hourly refresh. // 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]) { for (const team of [event.homeTeam, event.awayTeam]) {
if (team?.provider !== "LIGA") continue; if (team?.provider !== "LIGA") continue;
try { 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"); await this.savePlayers(team.id, season, await this.liga.squad(team.externalId, season), "api");
} catch (err) { } catch (err) {
log.warn({ err, team: team.id }, "sports: liga squad re-read failed"); 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]) { for (const team of [event.homeTeam, event.awayTeam]) {
if (!team) continue; if (!team) continue;
const club = settings.teamNames[team.id] ?? team.name; 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); await this.linkSquadPerson(orgId, team, club, p, event.organization.biometricsEnabled, headshots, result);
} }
} }
@@ -987,6 +1065,7 @@ export class SportsService {
const { db, log } = this.deps; const { db, log } = this.deps;
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } }); let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
let created = false; let created = false;
if (!person) person = await this.personForIdentity(orgId, p);
if (!person) { if (!person) {
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } }); 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; 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++; 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 } }); person = await db.person.update({ where: { id: person.id }, data: { club, number: p.number, sportsPlayerId: p.id } });
result.updated++; result.updated++;
} }
@@ -1027,6 +1108,55 @@ export class SportsService {
if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo }); 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<string | null> {
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<Map<string, string>> {
const out = new Map<string, string>();
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 * 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 * 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 ( AND (
mine.id = sp.id mine.id = sp.id
OR (sp.external_id IS NOT NULL AND mine.external_id = sp.external_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) OR (mine.team_id = sp.team_id AND mine.name = sp.name)
) )
) )
@@ -1182,6 +1317,7 @@ export class SportsWorker {
private timer: ReturnType<typeof setTimeout> | undefined; private timer: ReturnType<typeof setTimeout> | undefined;
private stopped = false; private stopped = false;
private ticking = false; private ticking = false;
private filling = false;
private lastRefresh = 0; private lastRefresh = 0;
constructor( constructor(
@@ -1190,6 +1326,7 @@ export class SportsWorker {
) {} ) {}
start(): void { start(): void {
void this.fillRegister();
const tick = async () => { const tick = async () => {
this.ticking = true; this.ticking = true;
try { try {
@@ -1211,10 +1348,26 @@ export class SportsWorker {
this.timer = setTimeout(tick, 5_000); 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<void> {
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<void> { async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true; this.stopped = true;
if (this.timer) clearTimeout(this.timer); 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"); if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running");
} }
} }
+5 -4
View File
@@ -14,7 +14,7 @@ import { SecretBox } from "./delivery/secrets.js";
import { DeliveryService, DeliveryWorker } from "./delivery/service.js"; import { DeliveryService, DeliveryWorker } from "./delivery/service.js";
import { RenderPool, RenderProcess } from "./develop/engine.js"; import { RenderPool, RenderProcess } from "./develop/engine.js";
import { DevelopService, RenderWorker } from "./develop/service.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 { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
import { SportsService, SportsWorker } from "./sports/service.js"; import { SportsService, SportsWorker } from "./sports/service.js";
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/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 = const faceEngine =
config.FACES_BIN && config.FACES_MODELS_DIR config.FACES_BIN && config.FACES_MODELS_DIR
? new FacePool( ? new GrowingFacePool(
Array.from({ length: capacity.faces }, () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER })), () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER }),
capacity.faces,
) )
: undefined; : undefined;
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : 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"); if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
const faces = faceEngine const faces = faceEngine
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), { ? 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, intervalMs: 1000,
log, log,
heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT), heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT),
+2 -2
View File
@@ -8,8 +8,8 @@ describe("capacity", () => {
const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB }); const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB });
const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * 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(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(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: 6, archiveBurst: 91, archiveDownloads: 960 }); 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. // 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 }); expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 });
}); });
+18 -9
View File
@@ -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 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. 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 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 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 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: detector that finds a face in the photo is not retrained. The worker runs `workers/faces` on the original:
@@ -236,17 +237,23 @@ number for that event's context:
old game gets the number worn then, even for players who have since left. 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 - **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 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
A session (no away side), an exhibition, or a name that matches no team has no sheet: the face alone, against federation id, or the same birth date and full name), with the shirt number of that season. A face none of
everyone of that sport, and only a clearly stronger match. The shirt, when it is read, stays with those two clubs. them explains stays unnamed. It is never someone who was not at either club that season.
A session, a training day or a studio day of a national team (FPA: SNAF, SNAM, M18, and the same team under
its long name) uses that team only: people already confirmed there this season, and the athletes the session
folders name. There is no match number. A gala or a press day names no team: 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 Then what the shirts clearly read (three or more clear readings) in the person's confirmed photos of the same
season and competition. season and competition.
- An editor of the folder can give a face another name. The list shows the official face, the club and the shirt - An editor of the folder can give a face another name. The list shows the official face, the club and the shirt
number. number.
- **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's - **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's
squad. squad.
- **National team** (a country on either side, or a "Seleção" folder): club squads and club numbers never apply, - **National team** (a country on either side, or a seleção folder): club squads and club numbers never apply.
only what was read in national games of that season. The women's senior team, the men's, and an age group are different lists. A photo is named from people already
confirmed on that same team this season. The shirt number is the one read on that team's games, and an older
Portugal game with no team in the folder still shares what was read for Portugal that season.
- **The number typed on the person** has no season: used only in the current season and never for a national - **The number typed on the person** has no season: used only in the current season and never for a national
team. Training samples never take the model's own readings as labels. team. Training samples never take the model's own readings as labels.
@@ -259,7 +266,8 @@ hand-drawn boxes.
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation: 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, - **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 - **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 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 match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence
@@ -297,8 +305,9 @@ What organisations do with it:
from public https hosts (private, loopback and link-local addresses refused, redirects checked again, 5 MB, 10 s) 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 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. 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 - **People from squads:** one person per human. A later season at another club updates the club and the shirt
headshot becomes the reference photo, and number suggestions for faces use the event's squads. 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) ## Working without a network (desktop app)