From 37211014c7d71c53f838cf153d990c0e4e759a75 Mon Sep 17 00:00:00 2001 From: spark Date: Wed, 21 Oct 2026 21:40:16 +0100 Subject: [PATCH] Send already-read photographs back through faces once the season squads are in, newest first. A folder taken off the archive site stays off, including folders found inside it later. --- .../migration.sql | 2 + apps/api/prisma/schema.prisma | 2 + apps/api/src/archive/service.ts | 4 +- apps/api/src/faces/service.ts | 61 ++++++++++++++++++- apps/api/src/faces/worker.test.ts | 1 + apps/api/src/sports/service.ts | 9 +-- apps/api/src/worker.ts | 17 +++++- apps/app/src/i18n.ts | 4 +- apps/app/src/pages/ArchivePage.tsx | 2 +- apps/app/src/pages/SiteFolders.tsx | 14 ++++- docs/ARCHITECTURE.md | 12 ++-- docs/archive.md | 6 ++ 12 files changed, 114 insertions(+), 20 deletions(-) create mode 100644 apps/api/prisma/migrations/20261021220000_faces_squad_pass/migration.sql diff --git a/apps/api/prisma/migrations/20261021220000_faces_squad_pass/migration.sql b/apps/api/prisma/migrations/20261021220000_faces_squad_pass/migration.sql new file mode 100644 index 0000000..8137e4f --- /dev/null +++ b/apps/api/prisma/migrations/20261021220000_faces_squad_pass/migration.sql @@ -0,0 +1,2 @@ +-- Photos read before the season squads can be sent through face analysis again, newest first, once. +ALTER TABLE "photos" ADD COLUMN "faces_pass" INTEGER NOT NULL DEFAULT 0; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index b27be17..464d082 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -401,6 +401,8 @@ model Photo { embeddedIptc Json? @map("embedded_iptc") /// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED. facesStatus FacesStatus @default(NONE) @map("faces_status") + /// Which squad-aware reread this photo has been sent through. 0: read before the season squads. + facesPass Int @default(0) @map("faces_pass") /// When the event was asked to the front of the face queue. Null waits behind every boosted photo. facesBoostedAt DateTime? @map("faces_boosted_at") /// Autopilot queue (docs/photo-editing-rules.md): NONE unless the event's autopilot took this photo. diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index 5e9e802..bafa42a 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -326,7 +326,9 @@ export class ArchiveService { } let folder = known ? await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } }) - : await db.cloudFolder.create({ data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null } }); + : await db.cloudFolder.create({ + data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) }, + }); const dirs = children.filter((c) => c.isDir); const images = children.filter((c) => !c.isDir && IMAGE.test(c.name)); diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 4dc2854..370a662 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -32,6 +32,10 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { extractFrames, type VideoTools } from "../archive/video.js"; +/** Photos read before the season squads. Each worker start, after the register, sends another batch back. */ +const SQUAD_FACE_PASS = 1; +const SQUAD_FACE_BATCH = 30_000; + /** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */ const MIN_FACE_SIDE = 0.012; /** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */ @@ -100,8 +104,8 @@ export class FaceService { 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`); + // The older archive, only once that month is clear, still newest game first. + const rest = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at < now() - ${RECENT_FACES}`, Prisma.sql`taken_at DESC`); return [...boosted, ...recent, ...rest]; } @@ -140,6 +144,25 @@ export class FaceService { return r.count; } + /** + * Photographs already read, sent through face analysis again so the season's squad can name them. + * Newest first, one batch per start: the next start continues with the next batch. A confirmed face + * stays on its group when the new reading still matches it. + */ + async requeueForSquad(): Promise { + return Number( + await this.deps.db.$executeRaw` + UPDATE photos SET faces_status = 'PENDING', faces_pass = ${SQUAD_FACE_PASS}, updated_at = now() + WHERE id IN ( + SELECT id FROM photos + WHERE faces_status = 'DONE' AND status = 'READY' AND faces_pass < ${SQUAD_FACE_PASS} + AND organization_id IN (SELECT id FROM organizations WHERE biometrics_enabled) + ORDER BY taken_at DESC NULLS LAST + LIMIT ${SQUAD_FACE_BATCH} + )`, + ); + } + /** * 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. @@ -231,7 +254,7 @@ export class FaceService { return small && chest ? kitColour(small, chest) : null; }); await db.$transaction(async (tx) => { - await tx.face.deleteMany({ where: { photoId } }); + await releasePhotoFaces(tx, photoId); for (const [i, f] of faces.entries()) { const n = numbers.get(i); await tx.face.create({ @@ -1312,6 +1335,38 @@ export async function dropOffRosterSuggestions(db: Db, refresh?: (eventId: strin return n; } +type FaceTx = Pick; + +/** + * Takes this photo's faces out of their groups before they are read again. A confirmed group keeps its + * centroid, so the new reading rejoins it when it is still the same person. An empty group nobody named goes. + */ +async function releasePhotoFaces(tx: FaceTx, photoId: string): Promise { + const previous = await tx.face.findMany({ where: { photoId }, select: { groupId: true } }); + await tx.face.deleteMany({ where: { photoId } }); + const groupIds = [...new Set(previous.map((face) => face.groupId).filter((id): id is string => !!id))]; + for (const groupId of groupIds) { + const group = await tx.faceGroup.findUnique({ where: { id: groupId }, select: { id: true, personId: true } }); + if (!group) continue; + const left = await tx.face.findMany({ where: { groupId }, select: { embedding: true } }); + const videos = await tx.videoFace.count({ where: { groupId } }); + if (left.length === 0 && videos === 0) { + if (group.personId) await tx.faceGroup.update({ where: { id: groupId }, data: { size: 1 } }); + else await tx.faceGroup.delete({ where: { id: groupId } }); + continue; + } + if (left.length === 0) { + await tx.faceGroup.update({ where: { id: groupId }, data: { size: videos } }); + continue; + } + const centroid = mergeMeans(left.filter((face) => face.embedding.length > 0).map((face) => ({ mean: face.embedding, count: 1 }))); + await tx.faceGroup.update({ + where: { id: groupId }, + data: { size: left.length + videos, ...(centroid.length > 0 ? { centroid } : {}) }, + }); + } +} + /** Keeps `processes` face engines busy. */ export class FaceWorker { private inFlight = 0; diff --git a/apps/api/src/faces/worker.test.ts b/apps/api/src/faces/worker.test.ts index da8f02b..35c4fd6 100644 --- a/apps/api/src/faces/worker.test.ts +++ b/apps/api/src/faces/worker.test.ts @@ -14,6 +14,7 @@ function busyQueue() { requeueFailed: async () => 0, requeueVideos: async () => 0, requeueStale: async () => 0, + refreshLineupEvents: async () => 0, claimReferences: async () => [], processReference: async () => {}, claim: async (limit: number) => Array.from({ length: Math.max(0, limit) }, (_, i) => `p${i}`), diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 668ab36..22759ff 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -251,7 +251,7 @@ export class SportsService { seasons = await this.liga.seasons(); } catch (err) { this.deps.log.warn({ err }, "sports: liga seasons not read"); - return 0; + return -1; } let saved = 0; for (const season of seasons) { @@ -1339,7 +1339,7 @@ export class SportsWorker { constructor( private readonly service: SportsService, - private readonly opts: { log: IngestLogger; lineupEveryMs?: number; refreshCheckMs?: number }, + private readonly opts: { log: IngestLogger; lineupEveryMs?: number; refreshCheckMs?: number; afterRegister?: () => Promise }, ) {} start(): void { @@ -1369,11 +1369,12 @@ export class SportsWorker { private async fillRegister(): Promise { this.filling = true; try { - await this.service.backfillLigaRegister(() => this.stopped); - while (!this.stopped) { + const saved = await this.service.backfillLigaRegister(() => this.stopped); + while (!this.stopped && saved >= 0) { const n = await this.service.linkStoredSquads(24); if (!n) break; } + if (!this.stopped && saved >= 0 && this.opts.afterRegister) await this.opts.afterRegister(); } catch (err) { this.opts.log.warn({ err }, "sports: register not filled"); } finally { diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index c27b44c..2e1ee4f 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -133,8 +133,11 @@ const faceEngine = : undefined; const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined; if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded"); -const faces = faceEngine - ? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), { +const faceService = faceEngine + ? new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }) + : undefined; +const faces = faceService + ? new FaceWorker(faceService, { concurrency: () => faceEngine?.size ?? 1, intervalMs: 1000, log, @@ -149,7 +152,15 @@ const autopilot = new AutopilotWorker( { concurrency: capacity.autopilot, intervalMs: 200, log }, ); -const sports = config.SPORTS_SYNC === "on" ? new SportsWorker(sportsService, { log }) : undefined; +const sports = config.SPORTS_SYNC === "on" + ? new SportsWorker(sportsService, { + log, + afterRegister: async () => { + const n = await faceService?.requeueForSquad(); + if (n) log.info({ photos: n }, "faces: read photographs queued again, newest first"); + }, + }) + : undefined; scanner.start(); if (secrets) archive.start(); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 63268d6..92e9591 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -643,7 +643,9 @@ export const t = { diskShort: (min: string) => `Não chega: aumenta o disco do servidor. A indexação pára sozinha quando ficarem menos de ${min} livres.`, diskPaused: (min: string) => `Indexação em pausa: o disco tem menos de ${min} livres. Aumenta o disco e continua sozinha.`, siteFolders: "Pastas no site", - siteFoldersHelp: "Por defeito entram todas. Tira o visto a uma pasta para ela deixar de aparecer no site, mesmo que a cloud a partilhe. Vale também para as pastas que estão dentro.", + siteFoldersHelp: "Por defeito entram todas. Tira o visto a uma pasta para ela deixar de aparecer no site, mesmo que a cloud a partilhe. As que já estão dentro, e as que forem lidas depois, ficam na mesma.", + siteFoldersMore: (left: number) => `Mostrar mais (${left})`, + siteFoldersHidden: (n: number) => (n === 1 ? "1 pasta fora do site" : `${n} pastas fora do site`), siteFoldersSearch: "Procurar pasta…", siteFoldersEmpty: "Ainda não há pastas indexadas.", siteFoldersLoading: "A carregar…", diff --git a/apps/app/src/pages/ArchivePage.tsx b/apps/app/src/pages/ArchivePage.tsx index 61372a6..ec98632 100644 --- a/apps/app/src/pages/ArchivePage.tsx +++ b/apps/app/src/pages/ArchivePage.tsx @@ -73,8 +73,8 @@ export function ArchivePage() { /> ))} {isAdmin ? setSources((list) => [...(list ?? []), s])} /> :

{A.adminOnly}

} - {current && current.status !== "LOGIN" && } {current && current.status !== "LOGIN" && canEdit && } + {current && current.status !== "LOGIN" && } ); diff --git a/apps/app/src/pages/SiteFolders.tsx b/apps/app/src/pages/SiteFolders.tsx index 0dd30aa..520a3b0 100644 --- a/apps/app/src/pages/SiteFolders.tsx +++ b/apps/app/src/pages/SiteFolders.tsx @@ -3,6 +3,7 @@ import { useEffect, useMemo, useState } from "react"; import { t } from "../i18n.js"; const A = t.archive; +const ROOTS_PAGE = 100; const errorText = (code: string | null) => (code ? (A.errors[code] ?? code) : null); const errorOf = (err: unknown) => errorText(err instanceof ApiError ? err.code : null) ?? t.unexpectedError; @@ -125,7 +126,8 @@ function Check({ box, disabled, label, onChange }: { box: Box; disabled: boolean * Everything starts published. Unchecking a folder hides it and the folders inside it. */ export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSource }) { - const [open, setOpen] = useState(false); + const [open, setOpen] = useState(true); + const [rootLimit, setRootLimit] = useState(ROOTS_PAGE); const [rows, setRows] = useState(null); const [query, setQuery] = useState(""); const [expanded, setExpanded] = useState>(new Set()); @@ -145,6 +147,8 @@ export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSour }, [api, source.id, open, rows]); const tree = useMemo(() => filterTree(treeOf(rows ?? []), query), [rows, query]); + const visible = tree.slice(0, rootLimit); + const hidden = (rows ?? []).filter((row) => !row.published).length; const shown = query.trim() ? new Set(collect(tree)) : expanded; const toggle = (path: string) => { @@ -186,6 +190,7 @@ export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSour {open && (

{A.siteFoldersHelp}

+ {hidden > 0 &&

{A.siteFoldersHidden(hidden)}

} setQuery(event.target.value)} @@ -197,11 +202,16 @@ export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSour {rows && tree.length === 0 &&

{A.siteFoldersEmpty}

} {rows && tree.length > 0 && (
    - {tree.map((node) => ( + {visible.map((node) => ( ))}
)} + {visible.length < tree.length && ( + + )}
)} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9a32372..21ee6cd 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -185,9 +185,10 @@ it when files must be served from more than one host. 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 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. The worker starts a few face processes and adds more while the CPU stays under +was taken, or the game's date when the camera wrote none), newest game first, and only then the older archive, +also newest game first. Once the season squads have been read, photographs already analysed go back through the +queue (`photos.faces_pass`), thirty thousand per worker start, newest first, so the squad of that year can name +them. A confirmed face keeps its group, and the new reading rejoins it when it is still the same person. The worker starts a few face processes and adds more while the CPU stays under about 99%, stopping sooner when memory (the model) runs short. Asking to analyse one event still puts it first. A photo whose analysis failed is queued again a few at a time, after it has been quiet for six hours, recent games first. Confirming a face improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the @@ -271,8 +272,9 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati - **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup stay on the six-hour refresh. Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. On start the worker reads every season the federation still lists, under the name that league had that year (Liga NOS, Liga Sagres, LigaPro), - so a past season keeps the squad and the shirt numbers of that year. The archive's people list is everyone; a - season narrows it to the people in that season's photographs. + so a past season keeps the squad and the shirt numbers of that year. When that read finishes, the newest + photographs already analysed are queued again for faces (thirty thousand per start). The archive's people list + is everyone; a season narrows it to the people in that season's photographs. - **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence diff --git a/docs/archive.md b/docs/archive.md index deea32a..a722b62 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -32,6 +32,12 @@ never reaches PhotoReport. A revoked app password puts the source back to LOGIN downloaded as before; deliveries and the 100% view read from the mount too. - The editor's 100% view (`GET /v1/photos/:id/original`) and deliveries read the original from the cloud. +## Which folders are on the site + +App → Arquivo → "Pastas no site", above the galleries. Every folder starts on the site. Unchecking one hides that +folder and everything inside it, including folders the next scan finds there. Checking it again publishes them. +The public site only lists photos whose folder is still published. + ## Matching galleries to games `archive/match.ts` reads the place and name of each folder with images: -- 2.47.3