Compare commits

..
Author SHA1 Message Date
spark 6e956f0ff8 Keep reading a Liga season when one month of the calendar is slow.
ci / rust (pull_request) Successful in 11m31s
ci / typescript (pull_request) Successful in 15m14s
A single timed-out month aborted the whole year and left a few games stored, which then hid the rest. That month is tried again and the other months are still saved.
2026-10-19 04:21:59 +01:00
spark a8f6a0f03d Keep each Liga season's matches, because Liga reuses the same fixture code every year.
ci / typescript (pull_request) Successful in 15m23s
ci / rust (pull_request) Successful in 12m0s
10101 is one game in 2023 and a different game in 2025. Storing the code alone let the later import overwrite the earlier year.
2026-10-19 04:09:22 +01:00
spark ec9679c609 Read a past Liga season again when its league calendar is only partly stored.
ci / rust (pull_request) Successful in 10m59s
ci / typescript (pull_request) Successful in 14m51s
A cup already saved, or a few games from the wrong year, was enough to skip the rest of that season. A finished league is 306 games, so a past season under that is fetched again.
2026-10-19 03:59:13 +01:00
spark 22dda8726e Keep a Liga game in the season Liga named, never the season we asked for.
ci / rust (pull_request) Successful in 10m5s
ci / typescript (pull_request) Successful in 14m23s
A fixture id is updated in place. Writing a season the calendar did not stamp would move that game into another year.
2026-10-19 03:44:15 +01:00
spark 68c4f48cd6 Read every Liga sponsor as the same league, and review one person across their games.
ci / rust (pull_request) Successful in 10m46s
ci / typescript (pull_request) Successful in 13m36s
Liga Portugal bwin, Liga NOS, SABSEG and LigaPro are the leagues already stored under today's names, so an old folder can meet its real match. Confirming a face updates the other games of that person, and the review shows their photos large.
2026-10-19 03:40:26 +01:00
spark 5cdfc19bf8 Keep a Liga game in the season Liga named when an older calendar is read.
ci / rust (pull_request) Successful in 11m9s
ci / typescript (pull_request) Successful in 15m31s
Asking for 2022/23 was writing that season onto fixtures that belong to another year, because the same fixture id is updated in place.
2026-10-19 03:18:07 +01:00
spark 11cbf64608 Index Liga bwin galleries by their glued codes, and name faces from the match sheet first.
ci / rust (pull_request) Successful in 10m10s
ci / typescript (pull_request) Successful in 14m23s
A folder such as CPACxRAFC was stored as one name with no championship. Editors who can edit a folder can now pick another person, with the official face, club and number. Failed face reads are retried a few at a time.
2026-10-19 03:04:14 +01:00
tiago-neves d95d3f7c3a Archive download retries a Nextcloud blip instead of failing the whole index.
ci / rust (push) Successful in 4m13s
ci / typescript (push) Successful in 7m37s
A locked file (423) or the cloud briefly unavailable (503) under load used to surface
as a hard failure on the first try. CloudClient.call now retries transient statuses
(network error, 408, 423, 429, 5xx) with backoff before giving up.

Paperclip-Issue: BIT-31491
Paperclip-Run: 79e93869-908c-4688-a101-47b0555470a9
2026-10-19 02:50:55 +01:00
spark 2ccbce13d7 Merge pull request 'Read the last month of photos before the older archive' (#35) from task/faces-recent-month into main
ci / rust (push) Failing after 14m40s
ci / typescript (push) Failing after 14m42s
2026-10-19 02:31:49 +01:00
spark 07300f592b Read the last month of photos before the older archive.
ci / rust (pull_request) Failing after 14m52s
ci / typescript (pull_request) Failing after 14m54s
The face queue was ordered by when a file arrived, so a scan of past seasons jumped ahead of this month's games.
2026-10-19 02:31:22 +01:00
spark 2fc1f73254 Merge pull request 'CI green, archive teams no longer time out, own address behind NPM' (#33) from task/ci-green into main
ci / rust (push) Successful in 7m57s
ci / typescript (push) Successful in 11m3s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 17m5s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 17m18s
Merge pull request 'CI green, archive teams no longer time out, own address behind NPM' (#33) from task/ci-green into main
2026-10-19 01:23:49 +01:00
20 changed files with 694 additions and 101 deletions

No files matched your search

@@ -0,0 +1,36 @@
-- The face queue finishes the last month of photos (when they were taken, or the game's date) before the older
-- archive. `created_at` is when the file arrived, so a scan of an old season was jumping ahead of this month.
ALTER TABLE "photos" ADD COLUMN "taken_at" TIMESTAMP(3);
CREATE OR REPLACE FUNCTION photos_set_taken_at() RETURNS trigger AS $$
DECLARE
game timestamp(3);
BEGIN
IF NEW.captured_at IS NULL AND NEW.event_id IS NOT NULL THEN
SELECT starts_at INTO game FROM events WHERE id = NEW.event_id;
END IF;
NEW.taken_at := COALESCE(NEW.captured_at, game, NEW.created_at, CURRENT_TIMESTAMP);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER photos_taken_at
BEFORE INSERT OR UPDATE OF captured_at, event_id ON photos
FOR EACH ROW EXECUTE FUNCTION photos_set_taken_at();
UPDATE photos AS p
SET taken_at = COALESCE(p.captured_at, e.starts_at, p.created_at)
FROM events e
WHERE p.event_id = e.id;
UPDATE photos
SET taken_at = COALESCE(captured_at, created_at)
WHERE taken_at IS NULL;
ALTER TABLE "photos" ALTER COLUMN "taken_at" SET NOT NULL;
ALTER TABLE "photos" ALTER COLUMN "taken_at" SET DEFAULT CURRENT_TIMESTAMP;
-- Recent photos: boosted first, then the newest game. The older archive keeps the created_at index.
CREATE INDEX "photos_faces_pending_taken_idx"
ON "photos" ("faces_boosted_at" DESC NULLS LAST, "taken_at" DESC)
WHERE "faces_status" = 'PENDING';
+3
View File
@@ -373,6 +373,9 @@ model Photo {
width Int?
height Int?
capturedAt DateTime? @map("captured_at")
/// When it was taken, or the game's start, or when the file arrived. Face analysis finishes the last month of
/// this before the older archive.
takenAt DateTime @default(now()) @map("taken_at")
cameraMake String? @map("camera_make")
cameraModel String? @map("camera_model")
cameraSerial String? @map("camera_serial")
+15 -3
View File
@@ -27,11 +27,22 @@ export interface FolderGame {
}
const LIGA_FOLDERS: [RegExp, string][] = [
[/^lp\s*betclic\b|^liga\s*portugal\s*betclic\b|^i\s*liga\b/i, "ligaportugalbetclic"],
[/^lp\s*betclic\b|^liga\s*portugal\s*betclic\b|^i\s*liga\b|^lp\s*bwin\b|^liga\s*portugal\s*bwin\b/i, "ligaportugalbetclic"],
[/^lp\s*meu\s*super\b|^liga\s*portugal\s*(2\s*)?meu\s*super\b|^ii\s*liga\b|^liga\s*2\b/i, "ligaportugalmeusuper"],
[/^allianz\s*cup\b|^taca\s*da\s*liga\b|^taça\s*da\s*liga\b/i, "allianzcup"],
];
/** The name shown on a gallery when the folder names a Liga competition and the official game is not in yet. */
const LIGA_NAMES: Record<string, string> = {
ligaportugalbetclic: "Liga Portugal Betclic",
ligaportugalmeusuper: "Liga Portugal Meu Super",
allianzcup: "Allianz Cup",
};
export function competitionLabel(id: string | null): string | null {
return id ? (LIGA_NAMES[id.toLowerCase()] ?? null) : null;
}
const toSeason = (a: string, b: string): string | null => {
const start = a.length === 2 ? 2000 + Number(a) : Number(a);
const end = b.length === 2 ? 2000 + Number(b) : Number(b);
@@ -53,8 +64,9 @@ function teamsIn(name: string, dashOk = false): { home: string; away: string } |
const m =
/^(.+?)\s+(?:x|vs\.?|va|v)\s+(.+)$/i.exec(name.trim()) ??
(dashOk || codes ? dash : null) ??
// "POR_FRA", "PTxES": two codes
/^([A-Z]{2,3})(?:_|\s*x\s*)([A-Z]{2,3})$/.exec(name.trim());
// "POR_FRA", "PTxES": two codes. "CPACxRAFC", "1.GVFCxPSC": the Liga's old folders glue the siglas.
/^([A-Z]{2,3})(?:_|\s*x\s*)([A-Z]{2,3})$/.exec(name.trim()) ??
/^([A-Za-z]{2,6})x([A-Za-z]{2,6})$/.exec(name.trim());
if (!m) return null;
const clean = (s: string) => s.replace(/\s*[([].*?[)\]]\s*$/, "").replace(/\s+/g, " ").trim();
// "1ª J - FCG x VFC", "Champions - FCP x HCMZ": the home side is after the last dash; "SCP x SLB - Final": the
+23 -5
View File
@@ -1,7 +1,11 @@
import { createWriteStream } from "node:fs";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { NextcloudError } from "../delivery/nextcloud.js";
import { isTransientStatus, NextcloudError } from "../delivery/nextcloud.js";
/** Backoff before retrying a transient failure (a locked file, Nextcloud briefly unavailable): one request, then up to three retries. */
const RETRY_DELAYS_MS = [200, 600, 1500];
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
/**
* Reading a Nextcloud for the archive: list folders (WebDAV PROPFIND with Nextcloud's file ids and etags),
@@ -180,11 +184,25 @@ export class CloudClient {
return `${this.base}${this.davRoot}${encodePath(path.startsWith("/") ? path : `/${path}`)}`;
}
/**
* One photo's 423 (locked while the owner's client syncs it) or a cloud's 503 under load is usually gone a
* moment later: retried here so it never reaches the caller as a failure, instead of one error per blip.
*/
private async call(method: string, url: string, init: RequestInit = {}): Promise<Response> {
try {
return await this.fetchImpl(url, { ...init, method, headers: { authorization: this.authHeader, ...(init.headers ?? {}) } });
} catch (err) {
throw new NextcloudError(`network error: ${(err as Error).message}`, 0);
for (let attempt = 0; ; attempt++) {
let res: Response;
try {
res = await this.fetchImpl(url, { ...init, method, headers: { authorization: this.authHeader, ...(init.headers ?? {}) } });
} catch (err) {
if (attempt >= RETRY_DELAYS_MS.length) throw new NextcloudError(`network error: ${(err as Error).message}`, 0);
await sleep(RETRY_DELAYS_MS[attempt]!);
continue;
}
if (isTransientStatus(res.status) && attempt < RETRY_DELAYS_MS.length) {
await sleep(RETRY_DELAYS_MS[attempt]!);
continue;
}
return res;
}
}
+39 -1
View File
@@ -38,6 +38,7 @@ const ReviewQuery = z.object({
limit: z.coerce.number().int().min(1).max(120).default(60),
});
const Act = z.object({ action: z.enum(["confirm", "reject", "ignore", "undo"]), personId: z.uuid().optional() });
const ChooseQuery = z.object({ q: z.string().trim().min(2).max(80) });
const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean().default(false) });
export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: Deps) {
@@ -74,6 +75,43 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
return { name: v.n, canReview, canManagePeople: editable === "all", pending };
});
/**
* People an editor may name a face as. The official face, the club and the shirt number travel with the name,
* so two players who share a name are not the same choice.
*/
app.get("/v1/archive/:sourceId/people/search", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
const { q } = ChooseQuery.parse(req.query);
if (!(await editScope(v))) throw forbidden("archive_edit_required");
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true } });
if (!source) throw notFound("source_not_found");
const like = `%${q.replace(/[\\%_]/g, "")}%`;
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean }[]>`
SELECT p.id, p.name,
COALESCE(p.club, t.name) AS club,
COALESCE(p.number, sp.number) AS number,
p.reference_key IS NOT NULL AS reference
FROM people p
LEFT JOIN sports_players sp ON sp.id = p.sports_player_id
LEFT JOIN sports_teams t ON t.id = sp.team_id
WHERE p.organization_id = ${source.organizationId}::uuid
AND p.recognition_off_at IS NULL
AND (
p.name ILIKE ${like}
OR COALESCE(p.club, '') ILIKE ${like}
OR COALESCE(t.name, '') ILIKE ${like}
OR COALESCE(sp.full_name, '') ILIKE ${like}
OR p.number = ${q}
OR sp.number = ${q}
)
ORDER BY (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
LIMIT 8`;
return {
people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null })),
};
});
/**
* Face groups to review in the viewer's editable folders, one card per group: its sharpest faces, who it is
* (named) or might be (suggested, with how sure), its event; and the people with suggestions waiting.
@@ -132,7 +170,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
row_number() OVER (PARTITION BY f.group_id ORDER BY f.sharpness DESC NULLS LAST, f.score DESC) AS rank
FROM faces f JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql}
WHERE f.group_id = ANY(${ids}::uuid[])
) s WHERE rank <= 4`
) s WHERE rank <= 8`
: [];
const photos = await db.photo.findMany({
where: { id: { in: [...new Set(samples.map((s) => s.photo_id))] } },
+12 -5
View File
@@ -14,8 +14,7 @@ import type { IngestLogger, IngestService } from "../ingest/service.js";
import { ingestWindow } from "../library/events.js";
import { waitUntil } from "../lib/idle.js";
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
import { describeFolder, type FolderGame, isInitials, isTeamName, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf } from "./match.js";
import { canonicalTeam, exhibitionName, isExhibition } from "./match.js";
import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf } from "./match.js";
export const IMAGE = /\.(jpe?g)$/i;
/** How long the person has to authorise in their cloud (Nextcloud keeps the flow 20 minutes). */
@@ -24,6 +23,8 @@ const LOGIN_TTL_MS = 20 * 60_000;
export const RESCAN_EVERY_MS = 6 * 3600_000;
const MAX_ATTEMPTS = 3;
const DAY_MS = 86_400_000;
/** A finished Liga Portugal league (18 clubs, 34 rounds). A past season with fewer games was only partly read. */
const LIGA_LEAGUE_FULL = 280;
/** Played FPA games of a season above which it counts as read (a national season has well over a thousand). */
const FPA_SEASON_KNOWN = 300;
/** The season ("20252026", July to June) a game's day falls in. */
@@ -373,7 +374,7 @@ export class ArchiveService {
if (fixture) return { eventId: await this.eventForFixture(source, fixture), matchedBy: "FIXTURE" };
const teams = await this.teamNames(game, source);
const day = game.day ?? (game.month ? `${game.month}-15` : null);
return { eventId: await this.eventForName(source, { ...teams, competition: game.competition, competitionName: exhibitionName(game), round: game.round, season: game.season }, day, modified, folder.eventId), matchedBy: "NAME" };
return { eventId: await this.eventForName(source, { ...teams, competition: game.competition, competitionName: exhibitionName(game) ?? competitionLabel(game.competition), round: game.round, season: game.season }, day, modified, folder.eventId), matchedBy: "NAME" };
}
return { eventId: await this.eventForOccasion(source, folder, modified), matchedBy: "FOLDER" };
}
@@ -615,8 +616,14 @@ export class ArchiveService {
const season = game.season ?? (day ? seasonOfDay(day) : null);
if (season && liga && this.deps.ligaSeason && !this.seasonsAsked.has(`LIGA|${season}`)) {
this.seasonsAsked.add(`LIGA|${season}`);
const known = await this.deps.db.sportsFixture.count({ where: { season, competition: { provider: "LIGA" } } });
if (!known) await this.deps.ligaSeason(season).catch((err) => this.deps.log.warn({ err, season }, "archive: liga season not read"));
// One read brings the league and the cup. A cup already stored, or a league only partly read, must not hide
// the rest of that year: a finished league is 306 games, and a past season under that is read again.
const league = await this.deps.db.sportsFixture.count({
where: { season, competition: { provider: "LIGA", externalId: "ligaportugalbetclic" } },
});
const past = season.replace(/\D/g, "") < seasonOf(lisbonDay(new Date()));
if ((past && league < LIGA_LEAGUE_FULL) || (!past && league === 0))
await this.deps.ligaSeason(season).catch((err) => this.deps.log.warn({ err, season }, "archive: liga season not read"));
}
if (season && !liga && this.deps.fpaSeason && !this.seasonsAsked.has(`FPA|${season}`)) {
this.seasonsAsked.add(`FPA|${season}`);
+4 -2
View File
@@ -8,6 +8,9 @@ export interface NextcloudAuth {
password: string;
}
/** Worth retrying: network trouble, rate limits and server errors (a locked file, Nextcloud under load). Auth and path errors are not. */
export const isTransientStatus = (status: number): boolean => status === 0 || status === 408 || status === 423 || status === 429 || status >= 500;
export class NextcloudError extends Error {
constructor(
message: string,
@@ -16,9 +19,8 @@ export class NextcloudError extends Error {
super(message);
}
/** Worth retrying: network trouble, rate limits and server errors. Auth and path errors are not. */
get transient(): boolean {
return this.status === 0 || this.status === 408 || this.status === 423 || this.status === 429 || this.status >= 500;
return isTransientStatus(this.status);
}
}
+39
View File
@@ -109,6 +109,45 @@ export async function registerFaceRoutes(
return { groups: out, pending, unclear, available: deps.engineOnline ? deps.engineOnline() : true };
});
/** Suggested faces across the library, one row per group, so an editor can clear them while others are selecting. */
app.get("/v1/orgs/:orgId/face-review", { preHandler: authenticate }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
await requireMembership(db, req, orgId, "INGESTER");
const groups = await db.faceGroup.findMany({
where: { organizationId: orgId, personId: null, ignoredAt: null, suggestedPersonId: { not: null } },
orderBy: [{ suggestionScore: "desc" }, { size: "desc" }],
take: 80,
include: {
suggested: true,
event: { select: { home: true, away: true, startsAt: true } },
faces: {
take: SAMPLES,
orderBy: [{ sharpness: { sort: "desc", nulls: "last" } }, { score: "desc" }],
select: { id: true, photoId: true, x0: true, y0: true, x1: true, y1: true, photo: { select: { width: true, height: true } } },
},
},
});
return {
groups: groups.map((g) => ({
id: g.id,
eventId: g.eventId,
size: g.size,
suggestion: g.suggested && g.suggestionScore !== null ? { ...personOut(g.suggested)!, score: g.suggestionScore } : null,
event: { title: g.event.away ? `${g.event.home} x ${g.event.away}` : g.event.home, startsAt: g.event.startsAt },
samples: g.faces.map((f) => ({
faceId: f.id,
photoId: f.photoId,
x0: f.x0,
y0: f.y0,
x1: f.x1,
y1: f.y1,
aspect: f.photo.width && f.photo.height ? f.photo.width / f.photo.height : 1.5,
preview: signer.url(f.photoId, "preview"),
})),
})),
};
});
app.post("/v1/face-groups/:groupId/confirm", { preHandler: authenticate }, async (req) => {
const { groupId } = GroupParams.parse(req.params);
const body = ConfirmFaceGroup.parse(req.body);
+76 -36
View File
@@ -1,5 +1,6 @@
import { expandCodes, parseCodeList } from "@photoreport/metadata";
import type { Db } from "../db.js";
import { Prisma } from "../generated/prisma/client.js";
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import type { FaceGroup, Person } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
@@ -16,7 +17,7 @@ export { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
import { numberContext, numbersIn, type NumberContext } from "./numbers.js";
import { numberContext, numbersIn, rosterOf, type NumberContext } from "./numbers.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
import type { FaceEngine } from "./process.js";
@@ -24,6 +25,8 @@ import type { FaceEngine } from "./process.js";
const MIN_FACE_SIDE = 0.012;
/** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */
export const STALE_RUNNING_MS = 10 * 60_000;
/** Photos taken inside this window (or just arrived, when they have no date) are read before the older archive. */
const RECENT_FACES = Prisma.sql`interval '30 days'`;
export class FaceRejected extends Error {
constructor(readonly code: string) {
@@ -55,11 +58,29 @@ export class FaceService {
async claim(limit: number): Promise<string[]> {
if (limit <= 0) return [];
// Asked for by hand ("Analisar caras"), whatever the date.
const boosted = await this.claimWhere(limit, Prisma.sql`faces_boosted_at IS NOT NULL`, Prisma.sql`faces_boosted_at DESC`);
let left = limit - boosted.length;
if (left <= 0) return boosted;
// The last month, newest game first. A gallery that just arrived of a current game is in here.
const recent = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at >= now() - ${RECENT_FACES}`, Prisma.sql`taken_at DESC`);
left -= recent.length;
if (left <= 0) return [...boosted, ...recent];
// The older archive, only once that month is clear. A folder that just arrived still comes before one that has been waiting.
const rest = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at < now() - ${RECENT_FACES}`, Prisma.sql`created_at DESC`);
return [...boosted, ...recent, ...rest];
}
/** Locks and takes the next pending photos matching `where`, in `order`. */
private async claimWhere(limit: number, where: Prisma.Sql, order: Prisma.Sql): Promise<string[]> {
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
UPDATE photos SET faces_status = 'RUNNING', updated_at = now()
WHERE id IN (
SELECT id FROM photos WHERE faces_status = 'PENDING' AND status = 'READY'
ORDER BY faces_boosted_at DESC NULLS LAST, created_at DESC LIMIT ${limit} FOR UPDATE SKIP LOCKED
SELECT id FROM photos
WHERE faces_status = 'PENDING' AND status = 'READY' AND ${where}
ORDER BY ${order}
LIMIT ${limit}
FOR UPDATE SKIP LOCKED
)
RETURNING id`;
return rows.map((r) => r.id);
@@ -78,6 +99,27 @@ export class FaceService {
return r.count;
}
/**
* Photos whose analysis failed, a few at a time, once they have been quiet for a few hours. Recent games first.
* A photo that fails again waits before the next try, so one bad file does not sit at the front forever.
*/
async requeueFailed(limit = 40, now = new Date()): Promise<number> {
const quietSince = new Date(now.getTime() - 6 * 3600_000);
return Number(
await this.deps.db.$executeRaw`
UPDATE photos AS p
SET faces_status = 'PENDING', updated_at = now()
WHERE p.id IN (
SELECT ph.id FROM photos ph
JOIN organizations org ON org.id = ph.organization_id
WHERE ph.faces_status = 'FAILED' AND ph.status = 'READY' AND org.biometrics_enabled
AND ph.updated_at < ${quietSince}
ORDER BY ph.taken_at DESC
LIMIT ${limit}
)`,
);
}
/**
* Photos left without analysis in an organization that has face analysis on (they arrived while it was off, or
* while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute.
@@ -96,8 +138,8 @@ export class FaceService {
}
/**
* The "Analisar caras" button: this event's photos go ahead of the oldest-first backlog, including ones already
* pending. A photo the worker is analysing right now (RUNNING, recently touched) is left alone; one it abandoned
* The "Analisar caras" button: this event's photos go ahead of the queue, including ones already pending.
* A photo the worker is analysing right now (RUNNING, recently touched) is left alone; one it abandoned
* is queued again.
*/
async boostEvent(eventId: string, now = new Date()): Promise<number> {
@@ -271,9 +313,10 @@ export class FaceService {
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
// Numbers as worn in this event's season and competition (another season, a cup, the national team: another).
const ctx = await numberContext(db, eventId);
// A game linked to its two clubs: only those squads. Another club's player who looks alike is not a guess.
const squadIds = ctx?.teamIds.length ? await playerIdsOnSquads(db, ctx.teamIds, ctx.season) : null;
const candidates = squadIds ? people.filter((p) => p.sportsPlayerId !== null && squadIds.has(p.sportsPlayerId)) : people;
// A game: the match sheet first (players, coaches, referees who already have a face). A session has no sheet,
// so the face is compared with everyone of that sport. The wider list is only for a face the sheet does not explain.
const sheet = await rosterOf(db, eventId);
const onSheet = sheet && sheet.length ? new Set(sheet) : null;
const worn = new Map<string, string | null>();
const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => {
const missing = ids.filter((id) => !worn.has(id));
@@ -283,10 +326,10 @@ export class FaceService {
}
return worn;
};
for (const g of groups) {
const pick = async (pool: typeof people, g: (typeof groups)[number], allowNumber: boolean) => {
const { match, margin } = this.thresholds(g.model);
const rejected = notThem.get(g.id);
const ranked = candidates
const ranked = pool
.filter((p) => p.model === g.model && !rejected?.has(p.id))
.map((p) => ({ p, s: cosine(p.centroid, g.centroid) }))
.sort((a, b) => b.s - a.s);
@@ -302,7 +345,7 @@ export class FaceService {
} else if (ok && read && firstNumber === read.number) {
// Face and shirt agree on the same player: surer than either alone.
suggestionScore = Math.round(Math.min(0.99, first.s + 0.15 * read.score) * 1000) / 1000;
} else if (!ok && read) {
} else if (!ok && read && allowNumber) {
// The face alone is not sure (too weak, or two people too close): the number decides among the near ones,
// and when two of them wear it (one per team), the kit colour.
const close = ranked.filter((r) => r.s >= match * 0.8);
@@ -326,6 +369,13 @@ export class FaceService {
suggestedPersonId = null;
suggestionScore = null;
}
return { suggestedPersonId, suggestionScore };
};
for (const g of groups) {
const first = onSheet ? people.filter((p) => onSheet.has(p.id)) : people;
let { suggestedPersonId, suggestionScore } = await pick(first, g, true);
// Nobody on the sheet: only then a face from outside it. The shirt stays with the two clubs.
if (!suggestedPersonId && onSheet) ({ suggestedPersonId, suggestionScore } = await pick(people, g, false));
if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) {
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
}
@@ -484,6 +534,15 @@ export class FaceService {
const photoIds = (await db.face.findMany({ where: { groupId }, select: { photoId: true } })).map((f) => f.photoId);
await this.nameConfirmedPhotos([...new Set(photoIds)]);
await this.refreshSuggestions(group.eventId);
// The same person suggested in other games: their cards are read again with this face included, so confirming
// one pulls the rest together instead of leaving a separate guess in every event.
const others = await db.faceGroup.findMany({
where: { suggestedPersonId: person.id, personId: null, ignoredAt: null, eventId: { not: group.eventId } },
select: { eventId: true },
distinct: ["eventId"],
take: 25,
});
for (const other of others) await this.refreshSuggestions(other.eventId);
this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId });
return person;
}
@@ -712,31 +771,6 @@ export function normSport(s: string | null | undefined): string | null {
return v;
}
/**
* Squad entries of these teams this season, plus the same player written under another season (the federation id,
* or the same name at the same club). Null when this season's squad is not here yet: then a face may still be
* matched more widely. An empty set means the squad is known and nobody outside it is a candidate.
*/
async function playerIdsOnSquads(db: Db, teamIds: string[], season: string): Promise<Set<string> | null> {
const squad = await db.sportsPlayer.findMany({
where: { teamId: { in: teamIds }, season },
select: { id: true, teamId: true, name: true, externalId: true },
});
if (!squad.length) return null;
const externalIds = [...new Set(squad.map((s) => s.externalId).filter((x): x is string => !!x))];
const same = await db.sportsPlayer.findMany({
where: {
OR: [
{ id: { in: squad.map((s) => s.id) } },
...squad.map((s) => ({ teamId: s.teamId, name: s.name })),
...(externalIds.length ? [{ externalId: { in: externalIds } }] : []),
],
},
select: { id: true },
});
return new Set(same.map((s) => s.id));
}
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
const rows = await db.$queryRaw<{ sport: string | null }[]>`
@@ -810,6 +844,7 @@ export class FaceWorker {
start(): void {
void this.service.requeueStale();
let missedAt = 0;
let failedAt = 0;
const tick = async () => {
this.ticking = true;
try {
@@ -819,6 +854,11 @@ export class FaceWorker {
const n = await this.service.queueMissed();
if (n) this.opts.log.info({ photos: n }, "faces: queued photos left without analysis");
}
if (Date.now() - failedAt > 3_600_000) {
failedAt = Date.now();
const n = await this.service.requeueFailed();
if (n) this.opts.log.info({ photos: n }, "faces: failed photos queued again");
}
for (const id of await this.service.claimReferences(5)) await this.service.processReference(id);
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
for (const id of ids) {
+20 -9
View File
@@ -42,6 +42,8 @@ export interface FixtureData {
competitionName?: string;
gender?: string | null;
season: string;
/** Liga named this season on the fixture. Absent means the caller asked for a season and Liga did not confirm it. */
seasonNamed?: boolean;
home: TeamData;
away: TeamData;
startsAt: Date;
@@ -68,8 +70,8 @@ export interface OfficialData {
const TIMEOUT_MS = 20_000;
async function get(fetcher: Fetch, url: string, headers: Record<string, string>, as: "json" | "text") {
const res = await fetcher(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
async function get(fetcher: Fetch, url: string, headers: Record<string, string>, as: "json" | "text", timeoutMs = TIMEOUT_MS) {
const res = await fetcher(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
if (!res.ok) throw new Error(`${new URL(url).host} ${new URL(url).pathname} ${res.status}`);
return as === "json" ? res.json() : res.text();
}
@@ -111,11 +113,14 @@ const url = (...vs: unknown[]): string | null => {
// --- Liga Portugal ------------------------------------------------------------------------------------------------
export const LIGA_COMPETITIONS = [
{ externalId: "ligaportugalbetclic", name: "Liga Portugal Betclic", aliases: ["Liga Portugal Betclic"] },
{ externalId: "ligaportugalmeusuper", name: "Liga Portugal Meu Super", aliases: ["Liga Portugal Meu Super", "Liga Portugal 2 Meu Super"] },
{ externalId: "allianzcup", name: "Allianz Cup", aliases: ["Allianz Cup"] },
// The same two leagues, under every sponsor Liga has used. A 2022 folder is "bwin"; 2026 is "Betclic".
{ externalId: "ligaportugalbetclic", name: "Liga Portugal Betclic", aliases: ["Liga Portugal Betclic", "Liga Portugal bwin", "Liga NOS"] },
{ externalId: "ligaportugalmeusuper", name: "Liga Portugal Meu Super", aliases: ["Liga Portugal Meu Super", "Liga Portugal 2 Meu Super", "Liga Portugal SABSEG", "LigaPro"] },
{ externalId: "allianzcup", name: "Allianz Cup", aliases: ["Allianz Cup", "Allianz CUP", "Taça da Liga", "Taca da Liga"] },
] as const;
const foldComp = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
export class LigaProvider {
static readonly BASE = "https://www.ligaportugal.pt/api/v1";
private static readonly HEADERS = { accept: "application/json", "accept-language": "pt-PT,pt;q=0.9", locale: "pt-PT", "x-client-platform": "web" };
@@ -125,7 +130,8 @@ export class LigaProvider {
private async api(path: string, params: Record<string, string>): Promise<unknown> {
const u = new URL(`${LigaProvider.BASE}/${path}`);
for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v);
return get(this.fetcher, u.toString(), LigaProvider.HEADERS, "json");
// The calendar is slow from the archive host. A short timeout used to abort a whole season after one month.
return get(this.fetcher, u.toString(), LigaProvider.HEADERS, "json", 45_000);
}
async teams(competition: string, season: string): Promise<TeamData[]> {
@@ -219,18 +225,23 @@ export class LigaProvider {
for (const day of days as { date?: string; fixtures?: Record<string, unknown>[] }[]) {
for (const f of day.fixtures ?? []) {
const name = str(f.competitionName) ?? "";
const comp = LIGA_COMPETITIONS.find((c) => (c.aliases as readonly string[]).includes(name));
const comp = LIGA_COMPETITIONS.find((c) => c.aliases.some((a) => foldComp(a) === foldComp(name)));
const home = ligaTeam(f.homeTeam);
const away = ligaTeam(f.awayTeam);
const when = str(f.matchDate) ?? str(f.fixtureDate) ?? day.date;
if (!comp || !home || !away || !when || f.canceledFixture) continue;
const code = str(f.fixtureCode) ?? `${f.round ?? f.matchweekNumber}-${home.externalId}-${away.externalId}`;
const finished = typeof f.fixtureStateTypeId === "number" && f.fixtureStateTypeId >= 5;
const named = str(f.seasonCode);
// Liga reuses fixtureCode every season: 10101 is a different match in 2023 and in 2025. The season is part
// of the id, or the later year's import overwrites the earlier year.
const seasonKey = named ?? season;
out.push({
externalId: code,
externalId: `${seasonKey}-${code}`,
competition: comp.externalId,
competitionName: comp.name,
season: str(f.seasonCode) ?? season,
season: seasonKey,
seasonNamed: named !== null,
home,
away,
startsAt: new Date(when),
+19 -3
View File
@@ -161,11 +161,27 @@ export class SportsService {
async importLigaSeason(season: string): Promise<number> {
const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "LIGA" } });
const byExternal = new Map(comps.map((c) => [c.externalId, c]));
const asked = season.replace(/\D/g, "");
let saved = 0;
for (const month of [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]) {
for (const f of await this.liga.month(month, season)) {
// One slow month must not drop the rest of the year. It is tried twice; the months already read stay.
let fixtures: Awaited<ReturnType<LigaProvider["month"]>> = [];
for (let attempt = 0; attempt < 2; attempt++) {
try {
fixtures = await this.liga.month(month, season);
break;
} catch (err) {
fixtures = [];
this.deps.log.warn({ err, season, month, attempt }, "sports: liga month not read");
}
}
for (const f of fixtures) {
// Only a season Liga itself named. The fixture id includes that season, so another year is another row.
if (!f.seasonNamed) continue;
const theirs = f.season.replace(/\D/g, "");
if (theirs !== asked) continue;
const c = byExternal.get(f.competition);
if (c) saved += await this.saveFixture(c, "LIGA", { ...f, season });
if (c) saved += await this.saveFixture(c, "LIGA", f);
}
}
this.deps.log.info({ season, saved }, "sports: liga season imported");
@@ -848,7 +864,7 @@ export class SportsService {
const fixture = event.fixture;
if (!named.length && fixture?.competition.provider === "LIGA" && fixture.round) {
try {
named = await this.liga.referees(fixture.competition.externalId, fixture.competition.season, fixture.round, fixture.externalId);
named = await this.liga.referees(fixture.competition.externalId, fixture.competition.season, fixture.round, fixture.externalId.replace(/^\d{8}-/, ""));
if (named.length) await db.sportsFixture.update({ where: { id: fixture.id }, data: { officials: named as unknown as object } });
} catch (err) {
log.warn({ err, fixture: fixture.id }, "sports: liga referees failed");
+61 -1
View File
@@ -5,7 +5,7 @@ import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { canonicalTeam, describeFolder, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, type FixtureCandidate } from "../src/archive/match.js";
import { parseMultistatus } from "../src/archive/nextcloud.js";
import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js";
import { ArchiveService, localDirs } from "../src/archive/service.js";
import { SecretBox } from "../src/delivery/secrets.js";
import { IngestService } from "../src/ingest/service.js";
@@ -29,6 +29,29 @@ describe("archive folder names", () => {
expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO09A/20251102 - Madeira SAD x Colégio de Gaia")?.competition).toBe("PO09A");
});
it("reads Liga bwin folders whose teams are written as one code", () => {
expect(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")).toMatchObject({
home: "CPAC",
away: "RAFC",
day: null,
season: "20222023",
competition: "ligaportugalbetclic",
round: "11",
});
expect(parseFolder("/LPbwin - 22-23/JORNADA 1/1.GVFCxPSC")).toMatchObject({ home: "GVFC", away: "PSC", round: "1", competition: "ligaportugalbetclic" });
const t = (name: string, abbreviation: string) => ({ name, abbreviation, slug: name.toLowerCase() });
const fixture: FixtureCandidate = {
id: "cpac",
startsAt: new Date("2022-10-29T19:30:00Z"),
season: "20222023",
round: "11",
competition: { externalId: "ligaportugalbetclic" },
homeTeam: t("Casa Pia AC", "CPAC"),
awayTeam: t("Rio Ave FC", "RAFC"),
};
expect(pickFixture(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")!, [fixture], new Date("2026-10-19T00:00:00Z"))?.id).toBe("cpac");
});
it("reads Liga folders: competition and season from the top, matchday, numbered games", () => {
expect(parseFolder("/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga")).toMatchObject({
home: "Sporting CP",
@@ -271,6 +294,43 @@ describe("WebDAV listing", () => {
});
});
describe("CloudClient retries transient failures", () => {
const whoami = (url: URL) => (url.pathname.endsWith("/ocs/v2.php/cloud/user") ? Response.json({ ocs: { data: { id: "peter" } } }) : null);
it("retries a 423/503 blip on a download and succeeds, instead of failing on the first try", async () => {
let calls = 0;
const fetchImpl: typeof fetch = async (input) => {
const url = new URL(String(input));
const who = whoami(url);
if (who) return who;
calls++;
return calls <= 2 ? new Response(null, { status: 503 }) : new Response(new Uint8Array(Buffer.from("hello")), { status: 200 });
};
const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl);
const dir = await mkdtemp(path.join(tmpdir(), "pr-retry-test-"));
try {
await client.download("/a.jpg", path.join(dir, "out.jpg"));
expect(calls).toBe(3);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
it("gives up after exhausting retries and throws a transient NextcloudError", async () => {
const fetchImpl: typeof fetch = async (input) => {
const url = new URL(String(input));
return whoami(url) ?? new Response(null, { status: 503 });
};
const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl);
const dir = await mkdtemp(path.join(tmpdir(), "pr-retry-test-"));
try {
await expect(client.download("/a.jpg", path.join(dir, "out.jpg"))).rejects.toMatchObject({ status: 503 });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
interface Node {
id: string;
data?: Buffer;
+27
View File
@@ -490,6 +490,33 @@ describe("faces", () => {
expect(await faces.claim(1)).toEqual([newer.id]);
});
it("reads the last month before an older gallery that arrived later", async () => {
const { orgId, day1 } = await setup();
const photo = (name: string, capturedAt: Date, createdAt: Date) =>
ctx.db.photo.create({
data: {
organizationId: orgId,
eventId: day1.id,
source: "UPLOAD",
originalName: name,
sha256: name.padEnd(64, "0"),
byteSize: 1,
storageKey: name,
status: "READY",
facesStatus: "PENDING",
capturedAt,
createdAt,
},
});
const archive = await photo("archive.jpg", new Date("2024-03-01T15:00:00Z"), new Date());
const recent = await photo("recent.jpg", new Date(Date.now() - 2 * 24 * 60 * 60_000), new Date(Date.now() - 5 * 24 * 60 * 60_000));
const waiting = await photo("waiting.jpg", new Date("2023-11-01T15:00:00Z"), new Date(Date.now() - 2 * 24 * 60 * 60_000));
expect(await faces.claim(1)).toEqual([recent.id]);
// The month is clear: the gallery that just arrived comes before one that has been waiting.
expect(await faces.claim(1)).toEqual([archive.id]);
expect(await faces.claim(1)).toEqual([waiting.id]);
});
it("puts the event at the front of the queue and requeues a face the worker abandoned", async () => {
const { orgId, token, day1 } = await setup();
const photoOf = (name: string, facesStatus: "PENDING" | "FAILED" | "RUNNING") =>
+2
View File
@@ -5,6 +5,7 @@ import { t } from "./i18n.js";
import { ArchivePage } from "./pages/ArchivePage.js";
import { DevelopPage } from "./pages/DevelopPage.js";
import { DeliveryPage } from "./pages/DeliveryPage.js";
import { FacesQueuePage } from "./pages/FacesQueuePage.js";
import { NumbersPage } from "./pages/NumbersPage.js";
import { PrintPage } from "./pages/PrintPage.js";
import { ShopPage } from "./pages/ShopPage.js";
@@ -33,6 +34,7 @@ function Gate() {
<Route path="delivery" element={<DeliveryPage />} />
<Route path="shop" element={<ShopPage />} />
<Route path="print" element={<PrintPage />} />
<Route path="faces" element={<FacesQueuePage />} />
<Route path="numbers" element={<NumbersPage />} />
<Route path="members" element={<MembersPage />} />
<Route path="preferences" element={<PreferencesPage />} />
+2
View File
@@ -31,6 +31,8 @@ export const t = {
develop: "Revelar",
metadata: "Metadados",
archiveNav: "Arquivo",
facesNav: "Caras",
numbersNav: "Camisolas",
delivery: "Entregar",
soon: "Em breve",
events: "Eventos",
+114
View File
@@ -0,0 +1,114 @@
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router";
import { useAuth } from "../auth.js";
import { FaceCrop } from "../library/FacesView.js";
import { t } from "../i18n.js";
import { PageHeader } from "./Shell.js";
interface Sample {
faceId: string;
x0: number;
y0: number;
x1: number;
y1: number;
aspect: number;
preview: string;
}
interface Row {
id: string;
eventId: string;
size: number;
suggestion: { id: string; name: string; club: string | null; number: string | null; score: number } | null;
event: { title: string; startsAt: string };
samples: Sample[];
}
/**
* Faces waiting across the library, grouped by the person they seem to be. Confirming one names every game of
* that person on this page and teaches the next match. Shirt numbers are checked on Camisolas.
*/
export function FacesQueuePage() {
const { api, organization } = useAuth();
const orgId = organization?.id ?? "";
const [rows, setRows] = useState<Row[] | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [open, setOpen] = useState<Sample[] | null>(null);
const [at, setAt] = useState(0);
const load = useCallback(async () => {
if (!orgId) return;
const body = await api.request<{ groups: Row[] }>("GET", `/v1/orgs/${orgId}/face-review`);
setRows(body.groups);
}, [api, orgId]);
useEffect(() => {
void load().catch(() => setRows([]));
}, [load]);
const piles = new Map<string, Row[]>();
for (const row of rows ?? []) {
const key = row.suggestion?.id ?? row.id;
piles.set(key, [...(piles.get(key) ?? []), row]);
}
const confirm = async (pile: Row[]) => {
const personId = pile[0]?.suggestion?.id;
if (!personId) return;
setBusy(personId);
try {
for (const row of pile) await api.request("POST", `/v1/face-groups/${row.id}/confirm`, { personId });
setRows((cur) => cur?.filter((r) => !pile.some((p) => p.id === r.id)) ?? null);
} finally {
setBusy(null);
}
};
return (
<div className="flex h-full flex-col">
<PageHeader title={t.faces.title} />
<p className="px-4 pt-3 text-[13px] text-muted">
As caras por confirmar, juntas por pessoa. As camisolas ensinam-se em <Link to="/numbers" className="underline">{t.numbersNav}</Link>.
</p>
<div className="grid flex-1 content-start gap-3 overflow-auto p-4 sm:grid-cols-2 xl:grid-cols-3">
{rows === null && <p className="text-sm text-muted">A carregar…</p>}
{rows?.length === 0 && <p className="text-sm text-muted">Nada por confirmar.</p>}
{[...piles.values()].map((pile) => {
const who = pile[0]!.suggestion;
const faces = pile.flatMap((r) => r.samples);
return (
<article key={who?.id ?? pile[0]!.id} className="flex flex-col gap-2 border border-[#151516] bg-cell p-2">
<button type="button" className="flex flex-wrap gap-1 text-left" onClick={() => (setOpen(faces), setAt(0))}>
{faces.slice(0, 6).map((s) => (
<FaceCrop key={s.faceId} src={api.absolute(s.preview)} box={s} aspect={s.aspect} size={faces.length > 3 ? 52 : 72} />
))}
</button>
<div className="text-[13px]">
<p className="text-ink">{who?.name}</p>
<p className="text-[11px] text-faint">
{[who?.number && `nº ${who.number}`, who?.club, `${pile.reduce((n, r) => n + r.size, 0)} fotos`, pile.length > 1 ? `${pile.length} jogos` : pile[0]!.event.title]
.filter(Boolean)
.join(" · ")}
</p>
</div>
<button type="button" className="h-8 border border-black bg-accent text-[12px] text-ink" disabled={busy === who?.id} onClick={() => void confirm(pile)}>
Confirmar
</button>
</article>
);
})}
</div>
{open && open[at] && (
<div className="fixed inset-0 z-40 flex items-center justify-center gap-4 bg-black/80 p-6" onClick={() => setOpen(null)}>
<button type="button" className="h-12 w-12 rounded-full bg-white text-2xl" onClick={(e) => (e.stopPropagation(), setAt((at + open.length - 1) % open.length))} aria-label="Anterior">
‹
</button>
<span onClick={(e) => e.stopPropagation()}>
<FaceCrop src={api.absolute(open[at].preview)} box={open[at]} aspect={open[at].aspect} size={420} />
</span>
<button type="button" className="h-12 w-12 rounded-full bg-white text-2xl" onClick={(e) => (e.stopPropagation(), setAt((at + 1) % open.length))} aria-label="Seguinte">
›
</button>
</div>
)}
</div>
);
}
+12
View File
@@ -97,6 +97,18 @@ export function Shell() {
<NavLink to="/archive" className={moduleClass}>
{t.archiveNav}
</NavLink>
<span aria-hidden="true" className="text-[#3a3a3a]">
|
</span>
<NavLink to="/faces" className={moduleClass}>
{t.facesNav}
</NavLink>
<span aria-hidden="true" className="text-[#3a3a3a]">
|
</span>
<NavLink to="/numbers" className={moduleClass}>
{t.numbersNav}
</NavLink>
</>
)}
</nav>
+126 -34
View File
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { call, fold, forget, Forbidden, shortDay, Unauthorised, type Me, type PeopleList, type ReviewGroup, type ReviewResult, type ReviewStatus } from "./api";
import { useCallback, useEffect, useState } from "react";
import { call, forget, Forbidden, shortDay, Unauthorised, type Me, type ReviewGroup, type ReviewPerson, type ReviewResult, type ReviewStatus } from "./api";
import { FaceCrop, Icon, Loading, PersonFace } from "./parts";
const STATUS: [ReviewStatus, string][] = [
@@ -26,7 +26,10 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
const [selected, setSelected] = useState<Set<string>>(new Set());
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0);
const [everyone, setEveryone] = useState<PeopleList["people"] | null>(null);
const searchPeople = useCallback(async (q: string): Promise<ReviewPerson[]> => {
const { body } = await call<{ people: ReviewPerson[] }>(`/v1/archive/${sourceId}/people/search?q=${encodeURIComponent(q)}`, token);
return body.people;
}, [sourceId, token]);
useEffect(() => {
let cancel = false;
@@ -47,12 +50,6 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
};
}, [sourceId, token, status, person, onExpired, attempt]);
// Names to give an unnamed face: the people of the archive.
useEffect(() => {
if (status !== "unnamed" || everyone) return;
call<PeopleList>(`/v1/archive/${sourceId}/people`, token).then(({ body }) => setEveryone(body.people), () => setEveryone([]));
}, [status, everyone, sourceId, token]);
const act = useCallback(
async (ids: string[], action: Action, personId?: string) => {
setError(null);
@@ -83,7 +80,14 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
[sourceId, token, status, onExpired, onChanged],
);
const toggle = (id: string) => setSelected((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id])));
const togglePile = (pile: ReviewGroup[]) =>
setSelected((s) => {
const on = pile.every((g) => s.has(g.id));
const next = new Set(s);
for (const g of pile) if (on) next.delete(g.id);
else next.add(g.id);
return next;
});
const chosen = data?.people.find((p) => p.id === person) ?? null;
const ids = [...selected];
@@ -154,9 +158,19 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
{!data && !error && <Loading cards />}
{data && data.groups.length === 0 && <p className="arq-empty">{status === "suggested" ? "Nada por confirmar aqui. Bom trabalho." : "Nada nesta lista."}</p>}
<div className="arq-review">
{data?.groups.map((g) => (
<Card key={g.id} g={g} status={status} busy={busy.has(g.id)} selected={selected.has(g.id)} onToggle={() => toggle(g.id)} onAct={(a, p) => void act([g.id], a, p)} everyone={everyone} />
))}
{data &&
piles(data.groups, status).map((pile) => (
<Card
key={pile.map((g) => g.id).join("-")}
groups={pile}
status={status}
busy={pile.some((g) => busy.has(g.id))}
selected={pile.every((g) => selected.has(g.id))}
onToggle={() => togglePile(pile)}
onAct={(a, p) => void act(pile.map((g) => g.id), a, p)}
searchPeople={searchPeople}
/>
))}
</div>
</div>
</div>
@@ -199,27 +213,88 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
);
}
function NameSearch({ placeholder, searchPeople, onPick }: { placeholder: string; searchPeople: (q: string) => Promise<ReviewPerson[]>; onPick: (id: string) => void }) {
const [q, setQ] = useState("");
const [hits, setHits] = useState<ReviewPerson[]>([]);
useEffect(() => {
const query = q.trim();
if (query.length < 2) {
setHits([]);
return;
}
let cancel = false;
const timer = setTimeout(() => {
searchPeople(query).then(
(rows) => {
if (!cancel) setHits(rows);
},
() => {
if (!cancel) setHits([]);
},
);
}, 200);
return () => {
cancel = true;
clearTimeout(timer);
};
}, [q, searchPeople]);
return (
<span className="arq-name-it">
<input type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={placeholder} aria-label={placeholder} />
{hits.map((p) => (
<button key={p.id} type="button" className="arq-name-hit" onClick={() => onPick(p.id)}>
<PersonFace p={{ reference: p.reference, face: null, name: p.name }} size={36} />
<span>
<strong>{p.name}</strong>
<small>{[p.number ? `nº ${p.number}` : null, p.club].filter(Boolean).join(" · ")}</small>
</span>
</button>
))}
</span>
);
}
/** The same person in several games is one card: confirming once names all of them and teaches the next match. */
function piles(groups: ReviewGroup[], status: ReviewStatus): ReviewGroup[][] {
if (status !== "suggested" && status !== "confirmed") return groups.map((g) => [g]);
const order: string[] = [];
const by = new Map<string, ReviewGroup[]>();
for (const g of groups) {
const who = status === "confirmed" ? g.person : g.suggested;
const key = who?.id ?? g.id;
const list = by.get(key);
if (list) list.push(g);
else {
by.set(key, [g]);
order.push(key);
}
}
return order.map((key) => by.get(key)!);
}
function Card({
g,
groups,
status,
busy,
selected,
onToggle,
onAct,
everyone,
searchPeople,
}: {
g: ReviewGroup;
groups: ReviewGroup[];
status: ReviewStatus;
busy: boolean;
selected: boolean;
onToggle: () => void;
onAct: (a: Action, personId?: string) => void;
everyone: PeopleList["people"] | null;
searchPeople: (q: string) => Promise<ReviewPerson[]>;
}) {
const [q, setQ] = useState("");
const g = groups[0]!;
const who = g.person ?? g.suggested;
const [first, ...rest] = g.faces;
const matches = useMemo(() => (q.trim().length < 2 ? [] : (everyone ?? []).filter((p) => fold(`${p.name} ${p.club ?? ""} ${p.number ?? ""}`).includes(fold(q.trim()))).slice(0, 6)), [q, everyone]);
const faces = groups.flatMap((item) => item.faces);
const photos = groups.reduce((n, item) => n + item.photos, 0);
const [open, setOpen] = useState<number | null>(null);
const [first, ...rest] = faces;
const onKey = (e: React.KeyboardEvent) => {
if (busy || e.target instanceof HTMLInputElement) return;
const k = e.key.toLowerCase();
@@ -232,9 +307,9 @@ function Card({
};
return (
<article className={`arq-rcard${selected ? " on" : ""}${busy ? " busy" : ""}`} tabIndex={0} onKeyDown={onKey} aria-label={who ? who.name : "Rosto sem nome"}>
<button type="button" className="arq-rfaces" onClick={onToggle} aria-pressed={selected} aria-label={selected ? "Tirar da seleção" : "Selecionar"}>
<button type="button" className="arq-rfaces" onClick={() => first && setOpen(0)} aria-label={who ? `Ver as fotos de ${who.name}` : "Ver as fotos"}>
{first ? <FaceCrop src={first.src} box={first.box} aspect={first.aspect} size={160} round={false} /> : <span className="arq-crop" style={{ width: 160, height: 160 }} />}
<span className="arq-check" aria-hidden="true">
<span className="arq-check" role="checkbox" aria-checked={selected} aria-label={selected ? "Tirar da seleção" : "Selecionar"} onClick={(e) => (e.stopPropagation(), onToggle())}>
{selected ? "✓" : ""}
</span>
{g.score !== null && status === "suggested" && <span className="arq-badge dark arq-conf">{Math.round(g.score * 100)}%</span>}
@@ -249,20 +324,21 @@ function Card({
<div className="arq-rbody">
<strong>{who ? who.name : "Sem nome"}</strong>
<small>
{[who?.number && `nº ${who.number}`, who?.club, `${g.photos} ${g.photos === 1 ? "foto" : "fotos"}`].filter(Boolean).join(" · ")}
{[who?.number && `nº ${who.number}`, who?.club, `${photos} ${photos === 1 ? "foto" : "fotos"}`, groups.length > 1 ? `${groups.length} jogos` : null].filter(Boolean).join(" · ")}
</small>
{g.event && <small>{[g.event.title, g.event.startsAt ? shortDay.format(new Date(g.event.startsAt)) : null].filter(Boolean).join(" · ")}</small>}
{groups.length === 1 && g.event && <small>{[g.event.title, g.event.startsAt ? shortDay.format(new Date(g.event.startsAt)) : null].filter(Boolean).join(" · ")}</small>}
{groups.length > 1 && (
<small>
{groups
.map((item) => item.event?.title)
.filter(Boolean)
.slice(0, 4)
.join(" · ")}
</small>
)}
{g.notThem.length > 0 && <small>Não é: {g.notThem.map((n) => n.name).join(", ")}</small>}
{status === "unnamed" && (
<span className="arq-name-it">
<input type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Quem é? Nome ou número" aria-label="Quem é?" />
{matches.map((p) => (
<button key={p.id} type="button" className="arq-pill" onClick={() => onAct("confirm", p.id)}>
{p.name}
{p.number && <span className="arq-n">{p.number}</span>}
</button>
))}
</span>
{(status === "unnamed" || status === "suggested") && (
<NameSearch placeholder={status === "unnamed" ? "Quem é? Nome, clube ou número" : "Outro nome, clube ou número"} searchPeople={searchPeople} onPick={(id) => onAct("confirm", id)} />
)}
</div>
<div className="arq-ractions">
@@ -291,6 +367,22 @@ function Card({
</button>
)}
</div>
{open !== null && faces[open] && (
<div className="arq-lightbox" role="dialog" aria-modal="true" aria-label={who ? who.name : "Fotos do grupo"} onClick={() => setOpen(null)}>
<button type="button" className="arq-lightbox-x" onClick={() => setOpen(null)} aria-label="Fechar">
×
</button>
<button type="button" className="arq-lightbox-nav" aria-label="Foto anterior" onClick={(e) => (e.stopPropagation(), setOpen((open + faces.length - 1) % faces.length))}>
‹
</button>
<span onClick={(e) => e.stopPropagation()}>
<FaceCrop src={faces[open].src} box={faces[open].box} aspect={faces[open].aspect} size={420} round={false} eager />
</span>
<button type="button" className="arq-lightbox-nav" aria-label="Foto seguinte" onClick={(e) => (e.stopPropagation(), setOpen((open + 1) % faces.length))}>
›
</button>
</div>
)}
</article>
);
}
@@ -1627,6 +1627,57 @@
border: 1px solid var(--line);
background: var(--card);
}
.arq-name-hit {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 4px 10px 4px 4px;
border-radius: 999px;
border: 1px solid var(--line);
background: var(--card);
text-align: left;
color: inherit;
}
.arq-name-hit > span {
display: flex;
flex-direction: column;
min-width: 0;
}
.arq-name-hit strong {
font-size: 14px;
}
.arq-name-hit small {
font-size: 12px;
color: var(--muted);
}
.arq-lightbox {
position: fixed;
inset: 0;
z-index: 40;
display: flex;
align-items: center;
justify-content: center;
gap: 16px;
padding: 24px;
background: rgba(0, 0, 0, 0.86);
}
.arq-lightbox-nav,
.arq-lightbox-x {
width: 48px;
height: 48px;
border: 0;
border-radius: 999px;
background: #fff;
color: #111;
font-size: 28px;
line-height: 1;
}
.arq-lightbox-x {
position: absolute;
top: 16px;
right: 16px;
}
.arq-ractions {
display: grid;
grid-auto-flow: column;
+13 -2
View File
@@ -184,7 +184,13 @@ it when files must be served from more than one host.
## Faces
Only for organizations whose owner switched it on with a recorded legal basis (biometric data, GDPR art. 9).
Each photo that arrives is queued (`photos.faces_status`); the worker runs `workers/faces` on the original:
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
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:
YuNet finds faces, each is aligned to the ArcFace template and embedded by AuraFace (512 numbers, Apache-2.0;
model files pinned and checked by SHA-256, `infra/faces/download-models.sh`). Faces of the same person within an
event are grouped (cosine to the group's mean, threshold per model). An editor names a group once (the
@@ -228,8 +234,13 @@ number for that event's context:
- **Season:** the official match's, or the event's day (July to June). The squad read is that season's, so an
old game gets the number worn then, even for players who have since left.
- **Official match (linked to its teams):** that season's squad first; then what the shirts clearly read (three
- **Official match (linked to its teams):** the match sheet first — that season's players and coaches, and the
referees of the fixture, when they already have a face. A face none of them explains is then compared with
everyone of that sport. A session (no away side) has no sheet: the face alone, against everyone of the sport.
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 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
number.
- **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's
squad.
- **National team** (a country on either side, or a "Seleção" folder): club squads and club numbers never apply,