diff --git a/apps/api/prisma/migrations/20261020190000_archive_video_faces/migration.sql b/apps/api/prisma/migrations/20261020190000_archive_video_faces/migration.sql new file mode 100644 index 0000000..8e9ed87 --- /dev/null +++ b/apps/api/prisma/migrations/20261020190000_archive_video_faces/migration.sql @@ -0,0 +1,33 @@ +-- Faces in archive videos: appearances (a face followed through frames) in the events' face groups. +ALTER TABLE "cloud_videos" ADD COLUMN "faces_status" "FacesStatus" NOT NULL DEFAULT 'NONE'; +CREATE INDEX "cloud_videos_faces_status_idx" ON "cloud_videos"("faces_status"); + +CREATE TABLE "video_faces" ( + "id" UUID NOT NULL, + "video_id" UUID NOT NULL, + "group_id" UUID, + "start_ms" INTEGER NOT NULL, + "end_ms" INTEGER NOT NULL, + "at_ms" INTEGER NOT NULL, + "x0" DOUBLE PRECISION NOT NULL, + "y0" DOUBLE PRECISION NOT NULL, + "x1" DOUBLE PRECISION NOT NULL, + "y1" DOUBLE PRECISION NOT NULL, + "score" DOUBLE PRECISION NOT NULL, + "sharpness" DOUBLE PRECISION, + "embedding" DOUBLE PRECISION[] DEFAULT ARRAY[]::DOUBLE PRECISION[], + "model" TEXT NOT NULL, + "frames" INTEGER NOT NULL, + "frame_key" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "video_faces_pkey" PRIMARY KEY ("id") +); +CREATE INDEX "video_faces_video_id_idx" ON "video_faces"("video_id"); +CREATE INDEX "video_faces_group_id_idx" ON "video_faces"("group_id"); +ALTER TABLE "video_faces" ADD CONSTRAINT "video_faces_video_id_fkey" FOREIGN KEY ("video_id") REFERENCES "cloud_videos"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "video_faces" ADD CONSTRAINT "video_faces_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "face_groups"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- Videos already made, in organizations with face recognition on (as their photos): their faces are found next. +UPDATE "cloud_videos" v SET "faces_status" = 'PENDING' +FROM "cloud_sources" s JOIN "organizations" o ON o."id" = s."organization_id" +WHERE v."source_id" = s."id" AND o."biometrics_enabled" AND v."status" = 'DONE'; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index b3e2314..48358b2 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -695,6 +695,7 @@ model FaceGroup { person Person? @relation("confirmed", fields: [personId], references: [id], onDelete: SetNull) suggested Person? @relation("suggested", fields: [suggestedPersonId], references: [id], onDelete: SetNull) faces Face[] + videoFaces VideoFace[] rejections FaceGroupRejection[] @@index([eventId]) @@ -1747,18 +1748,58 @@ model CloudVideo { storageKey String? @map("storage_key") /// Size of the web copy. webBytes BigInt? @map("web_bytes") + /// Faces in the video (frames through the same engine as the photos): NONE (organization without biometrics), + /// PENDING, RUNNING, DONE, FAILED. + facesStatus FacesStatus @default(NONE) @map("faces_status") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) folder CloudFolder @relation(fields: [folderId], references: [id], onDelete: Cascade) + faces VideoFace[] @@unique([sourceId, fileId]) @@index([status, sourceId]) @@index([folderId, status, path]) + @@index([facesStatus]) @@map("cloud_videos") } +/// One appearance of a face in an archive video: the same face followed through consecutive frames (each frame +/// analysed by the same engine as the photos). It joins the event's face groups like a photo's face, so naming, +/// suggestions, "não é" and false positives are the photos' own. +model VideoFace { + id String @id @default(uuid()) @db.Uuid + videoId String @map("video_id") @db.Uuid + groupId String? @map("group_id") @db.Uuid + /// When it is on screen (ms from the start), and the frame it is clearest in. + startMs Int @map("start_ms") + endMs Int @map("end_ms") + atMs Int @map("at_ms") + /// Box in that frame, in fractions (0 to 1, y down). + x0 Float + y0 Float + x1 Float + y1 Float + score Float + sharpness Float? + /// Mean of the appearance's sharp embeddings (unit length), from `model`. + embedding Float[] @default([]) + model String + /// Frames it was found in. + frames Int + /// That frame as a JPEG in storage (shown when the face is reviewed). + frameKey String @map("frame_key") + createdAt DateTime @default(now()) @map("created_at") + + video CloudVideo @relation(fields: [videoId], references: [id], onDelete: Cascade) + group FaceGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull) + + @@index([videoId]) + @@index([groupId]) + @@map("video_faces") +} + /// What one viewer may see, written when they sign in. Later pages read this row; they do not call the cloud again. /// Shares stay as they were at sign-in until the session ends. model ArchiveGrant { diff --git a/apps/api/src/archive/people.ts b/apps/api/src/archive/people.ts index 05a0a5c..ac57a89 100644 --- a/apps/api/src/archive/people.ts +++ b/apps/api/src/archive/people.ts @@ -10,6 +10,7 @@ import type { UrlSigner } from "../storage/storage.js"; import { publishedPhotos } from "./gallery.js"; import { isNationalSide } from "./match.js"; import type { Viewer } from "./viewer.js"; +import { videoFaceCrop, videoScope } from "./video-faces.js"; /** * People in the archive, for its viewers: who appears in the galleries they may see (named from faces), all the @@ -260,7 +261,42 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De } const chosen = onePerPhoto(hits).slice(0, query.limit); const photos = scope ? await photoCards(chosen, scope) : []; + // The videos they appear in (named or probable), each with its clearest frame and every moment. + const visible = await visibleFolders(v); + const seen = + visible === "all" || visible.length + ? await db.$queryRaw<{ id: string; video_id: string; folder_id: string; name: string; confirmed: boolean; score: number | null; start_ms: number; end_ms: number; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null; duration_ms: number | null; sharpness: number | null }[]>` + SELECT vf.id, vf.video_id, cv.folder_id, cv.path AS name, (g.person_id IS NOT NULL) AS confirmed, g.suggestion_score AS score, + vf.start_ms, vf.end_ms, vf.x0, vf.y0, vf.x1, vf.y1, cv.width, cv.height, cv.duration_ms, vf.sharpness + FROM video_faces vf + JOIN face_groups g ON g.id = vf.group_id AND g.ignored_at IS NULL + JOIN cloud_videos cv ON cv.id = vf.video_id AND ${videoScope(sourceId, visible)} + WHERE g.person_id = ${personId}::uuid OR (${query.level === "all"} AND g.person_id IS NULL AND g.suggested_person_id = ${personId}::uuid) + ORDER BY vf.start_ms` + : []; + const byVideo = new Map(); + for (const r of seen) byVideo.set(r.video_id, [...(byVideo.get(r.video_id) ?? []), r]); + const galleries = await galleryInfo(seen.map((r) => r.folder_id)); + const videos = [...byVideo.entries()].map(([videoId, list]) => { + const clearest = list.reduce((a, b) => ((b.sharpness ?? 0) > (a.sharpness ?? 0) ? b : a)); + return { + id: videoId, + name: clearest.name.split("/").pop(), + level: list.some((r) => r.confirmed) ? ("confirmed" as const) : ("probable" as const), + durationMs: clearest.duration_ms, + width: clearest.width, + height: clearest.height, + face: videoFaceCrop(signer, clearest), + moments: list.map((r) => ({ startMs: r.start_ms, endMs: r.end_ms })), + thumb: signer.videoUrl(videoId, "thumb"), + poster: signer.videoUrl(videoId, "poster"), + src: signer.videoUrl(videoId, "web"), + download: signer.videoUrl(videoId, "download"), + gallery: galleries.get(clearest.folder_id) ?? null, + }; + }); return { + videos, person: { id: person.id, name: person.name, club: person.club, number: person.number, reference: person.referenceKey ? signer.personUrl(person.id) : null }, counts: { confirmed: photos.filter((p) => p.level === "confirmed").length, probable: photos.filter((p) => p.level === "probable").length, similar: photos.filter((p) => p.level === "similar").length }, photos, diff --git a/apps/api/src/archive/review.ts b/apps/api/src/archive/review.ts index 6a5d5ff..cfd15eb 100644 --- a/apps/api/src/archive/review.ts +++ b/apps/api/src/archive/review.ts @@ -9,6 +9,7 @@ import type { UrlSigner } from "../storage/storage.js"; import { galleryMemberIds } from "./gallery.js"; import { clubKey, faceBox } from "./people.js"; import type { Viewer } from "./viewer.js"; +import { videoFaceCrop, videoScope } from "./video-faces.js"; /** * Face review for archive viewers who may edit on the cloud. Rights come from the cloud, never from here: @@ -51,14 +52,28 @@ const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean( export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: Deps) { const { db, signer, faces, viewerOf, editableFolders } = deps; - /** Indexed files of the source the viewer may edit, as a condition on `cf`; null when none. */ - const editScope = async (v: Viewer): Promise<{ sql: Prisma.Sql; all: boolean } | null> => { + /** + * Indexed files of the source the viewer may edit, as a condition on `cf` (photos) and on `cv` (videos); null when + * none. + */ + const editScope = async (v: Viewer): Promise<{ sql: Prisma.Sql; vsql: Prisma.Sql; vedit: Prisma.Sql; all: boolean } | null> => { const editable = await editableFolders(v); if (editable !== "all" && !editable.length) return null; const base = Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`; - return editable === "all" ? { sql: base, all: true } : { sql: Prisma.sql`${base} AND cf.folder_id = ANY(${editable}::uuid[])`, all: false }; + return editable === "all" + ? { sql: base, vsql: videoScope(v.s, "all"), vedit: videoScope(v.s, "all", { edit: true }), all: true } + : { sql: Prisma.sql`${base} AND cf.folder_id = ANY(${editable}::uuid[])`, vsql: videoScope(v.s, editable), vedit: videoScope(v.s, editable, { edit: true }), all: false }; }; + /** + * What a face group holds within a scope: its photos' faces and its videos' appearances, one row each (`item` is + * the photo or the video), so a group of a video only is reviewed like any other. + */ + const members = (scope: { sql: Prisma.Sql; vsql: Prisma.Sql }) => Prisma.sql` + SELECT f.group_id, f.photo_id AS item, false AS video FROM faces f JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + UNION ALL + SELECT vf.group_id, vf.video_id AS item, true AS video FROM video_faces vf JOIN cloud_videos cv ON cv.id = vf.video_id AND ${scope.vsql}`; + const log = (v: Viewer, action: string, data: { personId?: string | null; groupId?: string | null; faces?: number }) => db.archiveFaceAction.create({ data: { sourceId: v.s, viewer: v.n, action, personId: data.personId ?? null, groupId: data.groupId ?? null, faces: data.faces ?? 0 } }); @@ -73,9 +88,10 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De const scope = await editScope(v); if (!scope) return 0; const [row] = await db.$queryRaw<{ n: number }[]>` + WITH m AS (${members(scope)}) SELECT count(DISTINCT g.id)::int AS n - FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id - WHERE g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL AND ${scope.sql}`; + FROM face_groups g JOIN m ON m.group_id = g.id + WHERE g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL`; return row?.n ?? 0; })() : 0; @@ -135,7 +151,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De const folder = await db.cloudFolder.findFirst({ where: { id: query.gallery, sourceId: v.s }, include: { event: true } }); if (!folder) throw notFound("gallery_not_found"); const ids = await galleryMemberIds(db, v.s, folder); - scope = { sql: Prisma.sql`${editable.sql} AND cf.folder_id = ANY(${ids}::uuid[])`, all: false }; + scope = { sql: Prisma.sql`${editable.sql} AND cf.folder_id = ANY(${ids}::uuid[])`, vsql: Prisma.sql`${editable.vsql} AND cv.folder_id = ANY(${ids}::uuid[])`, vedit: Prisma.sql`${editable.vedit} AND cv.folder_id = ANY(${ids}::uuid[])`, all: false }; gallery = { id: folder.id, title: folder.event ? eventName(folder.event) : (folder.path.split("/").filter(Boolean).pop() ?? folder.path) }; } const condition: Record, Prisma.Sql> = { @@ -147,11 +163,12 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De }; const person = query.person ? Prisma.sql`AND (g.person_id = ${query.person}::uuid OR g.suggested_person_id = ${query.person}::uuid OR EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id AND r.person_id = ${query.person}::uuid))` : Prisma.empty; const [groups, counts, queue] = await Promise.all([ - db.$queryRaw<{ id: string; event_id: string; person_id: string | null; suggested_person_id: string | null; suggestion_score: number | null; ignored_at: Date | null; size: number; photos: number }[]>` - SELECT g.id, g.event_id, g.person_id, g.suggested_person_id, g.suggestion_score, g.ignored_at, g.size, count(DISTINCT f.photo_id)::int AS photos + db.$queryRaw<{ id: string; event_id: string; person_id: string | null; suggested_person_id: string | null; suggestion_score: number | null; ignored_at: Date | null; size: number; photos: number; videos: number }[]>` + WITH m AS (${members(scope)}) + SELECT g.id, g.event_id, g.person_id, g.suggested_person_id, g.suggestion_score, g.ignored_at, g.size, + count(DISTINCT m.item) FILTER (WHERE NOT m.video)::int AS photos, count(DISTINCT m.item) FILTER (WHERE m.video)::int AS videos FROM face_groups g - JOIN faces f ON f.group_id = g.id - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + JOIN m ON m.group_id = g.id WHERE ${condition[query.status]} ${person} GROUP BY g.id ORDER BY g.suggestion_score DESC NULLS LAST, g.size DESC, g.id @@ -164,14 +181,13 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De WHEN g.suggested_person_id IS NOT NULL THEN 'suggested' WHEN EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id) THEN 'rejected' WHEN g.size >= 2 THEN 'unnamed' END AS status - FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + FROM face_groups g JOIN (${members(scope)}) m ON m.group_id = g.id WHERE TRUE ${person} ) s WHERE s.status IS NOT NULL GROUP BY s.status`, db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; groups: number }[]>` SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, count(DISTINCT g.id)::int AS groups FROM face_groups g - JOIN faces f ON f.group_id = g.id - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + JOIN (${members(scope)}) m ON m.group_id = g.id JOIN people p ON p.id = g.suggested_person_id WHERE g.person_id IS NULL AND g.ignored_at IS NULL GROUP BY p.id ORDER BY count(DISTINCT g.id) DESC, p.name LIMIT 200`, @@ -192,6 +208,16 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De where: { id: { in: [...new Set(samples.map((s) => s.photo_id))] } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true }, }); + // And the clearest appearances in its videos (the frame each is clearest in). + const videoSamples = ids.length + ? await db.$queryRaw<{ group_id: string; id: string; video_id: string; at_ms: number; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null }[]>` + SELECT group_id, id, video_id, at_ms, x0, y0, x1, y1, width, height FROM ( + SELECT vf.group_id, vf.id, vf.video_id, vf.at_ms, vf.x0, vf.y0, vf.x1, vf.y1, cv.width, cv.height, + row_number() OVER (PARTITION BY vf.group_id ORDER BY vf.sharpness DESC NULLS LAST, vf.score DESC) AS rank + FROM video_faces vf JOIN cloud_videos cv ON cv.id = vf.video_id AND ${scope.vsql} + WHERE vf.group_id = ANY(${ids}::uuid[]) + ) s WHERE rank <= 8` + : []; const photoById = new Map(photos.map((p) => [p.id, p])); const peopleIds = [...new Set(groups.flatMap((g) => [g.person_id, g.suggested_person_id]).filter((x): x is string => !!x))]; const [people, events, rejections] = await Promise.all([ @@ -216,19 +242,25 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De id: g.id, size: g.size, photos: g.photos, + videos: g.videos, score: g.suggestion_score, person: personOut(g.person_id), suggested: personOut(g.suggested_person_id), ignored: !!g.ignored_at, notThem: rejections.filter((r) => r.groupId === g.id).map((r) => ({ id: r.person.id, name: r.person.name, by: r.by })), event: e ? { title: eventName(e), startsAt: e.startsAt } : null, - faces: samples - .filter((s) => s.group_id === g.id) - .flatMap((s) => { - const p = photoById.get(s.photo_id); - if (!p) return []; - return [{ id: s.id, photoId: s.photo_id, src: signer.url(s.photo_id, "preview", p.renderedSeq), box: faceBox(s, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }]; - }), + faces: (() => { + const fromPhotos = samples + .filter((s) => s.group_id === g.id) + .flatMap((s) => { + const p = photoById.get(s.photo_id); + if (!p) return []; + return [{ id: s.id, photoId: s.photo_id as string | null, src: signer.url(s.photo_id, "preview", p.renderedSeq), box: faceBox(s, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }]; + }); + const fromVideos = videoSamples.filter((s) => s.group_id === g.id).map((s) => ({ id: s.id, photoId: null, video: { id: s.video_id, atMs: s.at_ms }, ...videoFaceCrop(signer, s) })); + // Both kinds on the card when the group has both. + return [...fromPhotos.slice(0, fromVideos.length ? 6 : 8), ...fromVideos].slice(0, 8); + })(), }; }), }; @@ -243,11 +275,15 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De if (!scope) throw forbidden("archive_edit_required"); const group = await db.faceGroup.findFirst({ where: { id: groupId, organization: { cloudSources: { some: { id: sourceId } } } } }); if (!group) throw notFound("group_not_found"); - // Every photo of the group must be one the viewer may edit (in this source). + // Every photo and video of the group must be one the viewer may edit (in this source). const [rights] = await db.$queryRaw<{ total: number; editable: number }[]>` - SELECT count(DISTINCT f.photo_id)::int AS total, - count(DISTINCT f.photo_id) FILTER (WHERE EXISTS (SELECT 1 FROM cloud_files cf WHERE cf.photo_id = f.photo_id AND ${scope.sql}))::int AS editable - FROM faces f WHERE f.group_id = ${groupId}::uuid`; + SELECT count(*)::int AS total, count(*) FILTER (WHERE ok)::int AS editable FROM ( + SELECT DISTINCT f.photo_id AS item, EXISTS (SELECT 1 FROM cloud_files cf WHERE cf.photo_id = f.photo_id AND ${scope.sql}) AS ok + FROM faces f WHERE f.group_id = ${groupId}::uuid + UNION + SELECT DISTINCT vf.video_id AS item, EXISTS (SELECT 1 FROM cloud_videos cv WHERE cv.id = vf.video_id AND ${scope.vedit}) AS ok + FROM video_faces vf WHERE vf.group_id = ${groupId}::uuid + ) items`; if (!rights || rights.total === 0 || rights.editable < rights.total) throw forbidden("archive_edit_required"); try { if (body.action === "confirm") { diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index b400913..5e9e802 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -15,7 +15,7 @@ import { ingestWindow } from "../library/events.js"; import { waitUntil } from "../lib/idle.js"; import type { LocalStorage } from "../storage/storage.js"; import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js"; -import { makeWebCopy, VIDEO, VideoToolMissing, type VideoTools } from "./video.js"; +import { makeWebCopy, VIDEO, VIDEO_FILES, VideoToolMissing, type VideoTools } from "./video.js"; import { teamSideRows } from "./directory.js"; import { galleryAssignments } from "./gallery.js"; import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, knownVersus, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf, slashSides, teamMatcher } from "./match.js"; @@ -880,9 +880,19 @@ export class ArchiveService { // Their faces belonged to the other event's groups: taken out of them, and found again in the new event. await db.face.deleteMany({ where: { photoId: { in: moving } } }); await db.photo.updateMany({ where: { id: { in: moving }, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, data: { facesStatus: "PENDING" } }); - if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} } } }); + if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} }, videoFaces: { none: {} } } }); } } + // Its videos' faces were in the other event's groups too: looked for again in the new event. + // Also from no event at all: their faces could not be put in any group until now. + const moved = previous !== eventId ? await db.cloudVideo.findMany({ where: { folderId, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, select: { id: true } }) : []; + if (moved.length) { + const frames = await db.videoFace.findMany({ where: { videoId: { in: moved.map((v) => v.id) } }, select: { frameKey: true } }); + await db.videoFace.deleteMany({ where: { videoId: { in: moved.map((v) => v.id) } } }); + await db.cloudVideo.updateMany({ where: { id: { in: moved.map((v) => v.id) } }, data: { facesStatus: "PENDING" } }); + for (const f of frames) if (this.deps.storage) await this.deps.storage.remove(f.frameKey).catch(() => undefined); + if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} }, videoFaces: { none: {} } } }); + } // An event the archive made and that nothing uses any more goes. if (previous && previous !== eventId) await this.dropIfEmpty(previous); if (previous !== eventId || folder.matchedBy !== matchedBy) await this.markDirectoryDirty(folder.sourceId); @@ -1136,12 +1146,24 @@ export class ArchiveService { await mkdir(out); const made = await this.cpu.run(() => makeWebCopy(videoTools, original, out)); const key = storage.videoKey(video.source.organizationId, video.id); - // The new files take the place of an older copy (a changed video). - await rm(storage.resolve(key), { recursive: true, force: true }); + // The new files take the place of an older copy (a changed video); the faces' frames are left to the face worker. + for (const name of Object.values(VIDEO_FILES)) await storage.remove(`${key}/${name}`); for (const name of await readdir(out)) if (name !== "frame.jpg") await storage.adopt(path.join(out, name), `${key}/${name}`); + // Its faces next, like a photo's: only where the organization has face recognition on. + const org = await db.organization.findUnique({ where: { id: video.source.organizationId }, select: { biometricsEnabled: true } }); await db.cloudVideo.update({ where: { id: videoId }, - data: { status: "DONE", error: null, storageKey: key, durationMs: made.durationMs, width: made.width, height: made.height, capturedAt: made.capturedAt, webBytes: BigInt(made.webBytes) }, + data: { + status: "DONE", + error: null, + storageKey: key, + durationMs: made.durationMs, + width: made.width, + height: made.height, + capturedAt: made.capturedAt, + webBytes: BigInt(made.webBytes), + facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", + }, }); } catch (err) { const message = (err as Error).message; diff --git a/apps/api/src/archive/video-faces.ts b/apps/api/src/archive/video-faces.ts new file mode 100644 index 0000000..51195d8 --- /dev/null +++ b/apps/api/src/archive/video-faces.ts @@ -0,0 +1,63 @@ +import { Prisma } from "../generated/prisma/client.js"; +import type { Db } from "../db.js"; +import type { UrlSigner } from "../storage/storage.js"; + +/** + * Faces in archive videos as the viewers see them: each appearance (a face followed through frames) is in an event's + * face group like a photo's face, so it is named (the group is confirmed), probable (the group has a suggestion) or + * nobody yet. Only videos of published folders count. + */ +export interface VideoPerson { + id: string; + name: string; + level: "confirmed" | "probable"; + /** First time on screen, and every appearance (to jump to each). */ + startMs: number; + moments: { startMs: number; endMs: number }[]; +} + +/** Who appears in each of these videos, named or probable, with when. */ +export async function peopleInVideos(db: Db, videoIds: string[]): Promise> { + const out = new Map(); + if (!videoIds.length) return out; + const rows = await db.$queryRaw<{ video_id: string; person_id: string; name: string; confirmed: boolean; start_ms: number; end_ms: number }[]>` + SELECT vf.video_id, p.id AS person_id, p.name, (g.person_id IS NOT NULL) AS confirmed, vf.start_ms, vf.end_ms + FROM video_faces vf + JOIN face_groups g ON g.id = vf.group_id AND g.ignored_at IS NULL + JOIN people p ON p.id = COALESCE(g.person_id, g.suggested_person_id) + WHERE vf.video_id = ANY(${videoIds}::uuid[]) + ORDER BY vf.start_ms`; + for (const r of rows) { + const list = out.get(r.video_id) ?? []; + let person = list.find((p) => p.id === r.person_id); + if (!person) { + person = { id: r.person_id, name: r.name, level: r.confirmed ? "confirmed" : "probable", startMs: r.start_ms, moments: [] }; + list.push(person); + } + person.moments.push({ startMs: r.start_ms, endMs: r.end_ms }); + out.set(r.video_id, list); + } + for (const list of out.values()) list.sort((a, b) => (a.level === b.level ? a.startMs - b.startMs : a.level === "confirmed" ? -1 : 1)); + return out; +} + +/** + * A video scope on `cv` like the photos' on `cf`: the source and (unless all) these folders. What viewers see is + * only made videos of published folders; what an editor may change (`edit`) is every video of their folders, as for + * the photos, so a video being made again or a folder taken off the site never locks a face group. + */ +export function videoScope(sourceId: string, folders: string[] | "all", opts: { edit?: boolean } = {}): Prisma.Sql { + const base = opts.edit + ? Prisma.sql`cv.source_id = ${sourceId}::uuid` + : Prisma.sql`cv.source_id = ${sourceId}::uuid AND cv.status = 'DONE' AND EXISTS (SELECT 1 FROM cloud_folders pub WHERE pub.id = cv.folder_id AND pub.published)`; + return folders === "all" ? base : Prisma.sql`${base} AND cv.folder_id = ANY(${folders}::uuid[])`; +} + +/** An appearance as a face crop: its frame (signed), the box in it and the frame's shape. */ +export function videoFaceCrop(signer: UrlSigner, f: { id: string; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null }) { + return { + src: signer.videoFaceUrl(f.id), + box: { x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1 }, + aspect: f.width && f.height ? f.width / f.height : 16 / 9, + }; +} diff --git a/apps/api/src/archive/video.ts b/apps/api/src/archive/video.ts index f64459b..8798d78 100644 --- a/apps/api/src/archive/video.ts +++ b/apps/api/src/archive/video.ts @@ -1,6 +1,6 @@ import { spawn } from "node:child_process"; import { createReadStream, existsSync } from "node:fs"; -import { stat } from "node:fs/promises"; +import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import type { FastifyReply } from "fastify"; import sharp from "sharp"; @@ -157,6 +157,17 @@ export async function makeWebCopy(tools: VideoTools, input: string, dir: string) return { ...copy, capturedAt: original.capturedAt, webBytes: (await stat(web)).size }; } +/** + * Frames of a video at `fps` a second (JPEG, the video's own size), for face analysis: the files in time order; + * frame i is at i / fps seconds from the start of the part read (`part`: from, and how long; the whole video + * without it). + */ +export async function extractFrames(tools: VideoTools, input: string, dir: string, fps: number, part?: { fromMs: number; lengthMs: number }): Promise { + const window = part ? ["-ss", (part.fromMs / 1000).toFixed(3), "-t", (part.lengthMs / 1000).toFixed(3)] : []; + await run(tools.ffmpeg, ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", ...window, "-i", input, "-vf", `fps=${fps}`, "-q:v", "3", path.join(dir, "frame_%06d.jpg")], "ffmpeg"); + return (await readdir(dir)).filter((f) => /^frame_\d+\.jpg$/.test(f)).sort().map((f) => path.join(dir, f)); +} + /** A `Range: bytes=…` header against a file's size: the part to send, `null` for the whole file, `"bad"` when it cannot be met. */ export function parseRange(header: string | undefined, size: number): { start: number; end: number } | null | "bad" { if (!header) return null; diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 351221a..7d8e115 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -17,6 +17,7 @@ import { registerArchiveDownloadRoutes } from "./downloads.js"; import { registerArchiveReviewRoutes } from "./review.js"; import type { ArchiveService } from "./service.js"; import { sendFile, VIDEO_FILES, VIDEO_VARIANTS } from "./video.js"; +import { peopleInVideos } from "./video-faces.js"; /** * The archive for people outside the organization (the federation, the clubs, the press): they sign in with @@ -581,6 +582,8 @@ export async function registerArchiveViewerRoutes( ? await db.cloudVideo.findMany({ where: { folderId: { in: ids }, status: "DONE", storageKey: { not: null } }, orderBy: { path: "asc" }, take: 200 }) : []; const videoTotal = await db.cloudVideo.count({ where: { folderId: { in: ids }, status: "DONE", storageKey: { not: null } } }); + // Who appears in each video (named, or probable), and when: the player jumps to them. + const inVideos = await peopleInVideos(db, videos.map((x) => x.id)); const facePhotos = await db.photo.findMany({ where: { id: { in: sharpest.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true }, @@ -606,7 +609,14 @@ export async function registerArchiveViewerRoutes( GROUP BY ROLLUP (f.photo_id)` : []; const pendingOf = new Map(waiting.filter((w) => w.photo_id).map((w) => [w.photo_id!, Number(w.n)])); - const pending = reviews ? Number(waiting.find((w) => !w.photo_id)?.n ?? 0) : undefined; + // And the appearances in the gallery's videos waiting for one. + const [videoWaiting] = reviews + ? await db.$queryRaw<{ n: number }[]>` + SELECT count(*)::int AS n FROM video_faces vf + JOIN face_groups g ON g.id = vf.group_id AND g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL + JOIN cloud_videos cv ON cv.id = vf.video_id AND cv.folder_id = ANY(${ids}::uuid[]) AND cv.status = 'DONE'` + : []; + const pending = reviews ? Number(waiting.find((w) => !w.photo_id)?.n ?? 0) + Number(videoWaiting?.n ?? 0) : undefined; return { id: shown.id, ...(pending !== undefined && { pending }), @@ -640,6 +650,7 @@ export async function registerArchiveViewerRoutes( poster: signer.videoUrl(x.id, "poster"), src: signer.videoUrl(x.id, "web"), download: signer.videoUrl(x.id, "download"), + people: inVideos.get(x.id) ?? [], ...(onCloud && { cloudUrl: `${base}/f/${x.fileId}` }), })), photos: files.map((f) => ({ @@ -701,6 +712,16 @@ export async function registerArchiveViewerRoutes( }); }); + /** The frame an appearance in a video is clearest in (its face, when reviewed), by signed URL. */ + app.get("/v1/files/video-faces/:faceId", async (req, reply) => { + const { faceId } = z.object({ faceId: z.uuid() }).parse(req.params); + const { exp, sig } = VideoFileQuery.parse(req.query); + if (!signer.verifyVideoFace(faceId, exp, sig)) throw notFound("file_not_found"); + const face = await db.videoFace.findUnique({ where: { id: faceId }, select: { frameKey: true, video: { select: { folder: { select: { published: true } } } } } }); + if (!face || !face.video.folder.published || !(await deps.storage.exists(face.frameKey))) throw notFound("file_not_found"); + return sendFile(reply, deps.storage.resolve(face.frameKey), undefined, { "content-type": "image/jpeg", "cache-control": "private, max-age=3600" }); + }); + await registerArchivePeopleRoutes(app, { db, signer, viewerOf, visibleFolders }); await registerArchiveReviewRoutes(app, { db, diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 962f016..360b2d3 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -60,6 +60,8 @@ const Env = z.object({ ARCHIVE_VIDEO_CONCURRENCY: z.coerce.number().int().nonnegative().default(1), /** ffmpeg and ffprobe (archive videos). On PATH by default (apt install ffmpeg). */ FFMPEG_BIN: z.string().default("ffmpeg"), + /** Frames a second looked at for faces in archive videos (each one analysed like a photo). */ + ARCHIVE_VIDEO_FACE_FPS: z.coerce.number().positive().max(30).default(5), FFPROBE_BIN: z.string().default("ffprobe"), /** Read competitions, squads and fixtures from Liga Portugal, FPF and FPA (worker). "off" to disable. */ SPORTS_SYNC: z.enum(["on", "off"]).default("on"), diff --git a/apps/api/src/faces/routes.ts b/apps/api/src/faces/routes.ts index 3468c60..583500c 100644 --- a/apps/api/src/faces/routes.ts +++ b/apps/api/src/faces/routes.ts @@ -307,6 +307,11 @@ export async function registerFaceRoutes( faces_boosted_at = (SELECT e.face_boosted_at FROM events e WHERE e.id = p.event_id), updated_at = now() WHERE p.organization_id = ${orgId}::uuid AND p.status = 'READY' AND p.faces_status = 'NONE'`; + // And the archive's videos already made. + await db.$executeRaw` + UPDATE cloud_videos AS v SET faces_status = 'PENDING', updated_at = now() + FROM cloud_sources s + WHERE v.source_id = s.id AND s.organization_id = ${orgId}::uuid AND v.status = 'DONE' AND v.faces_status = 'NONE'`; } return { enabled: org.biometricsEnabled, legalBasis: org.biometricsLegalBasis }; }); diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 0a50513..80b5fb7 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -1,3 +1,4 @@ +import sharp from "sharp"; import { expandCodes, parseCodeList } from "@photoreport/metadata"; import type { Db } from "../db.js"; import { Prisma } from "../generated/prisma/client.js"; @@ -20,11 +21,32 @@ import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.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"; +import { FaceFollower } from "./track.js"; +import { randomUUID } from "node:crypto"; +import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { extractFrames, type VideoTools } from "../archive/video.js"; /** 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). */ export const STALE_RUNNING_MS = 10 * 60_000; +/** Video appearances put in groups per transaction. */ +const VIDEO_GROUP_BATCH = 400; +/** A video is read for faces this much at a time. */ +const VIDEO_PART_MS = 60_000; +/** A video being read is touched after every part (a minute of video); untouched this long, its run is gone. */ +const STALE_VIDEO_MS = 30 * 60_000; +/** A video whose faces failed is tried again after this long. */ +const RETRY_FAILED_VIDEO_MS = 6 * 3600_000; +/** Long side of the frame kept for each appearance (shown when its face is reviewed). */ +const VIDEO_FRAME_SIZE = 960; + +/** A video's run was taken over by a newer request (moved to another event, its web copy made again). */ +class VideoRunSuperseded extends Error {} +/** The worker is stopping: the video goes back in the queue. */ +class VideoRunStopped extends Error {} /** 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'`; @@ -49,6 +71,10 @@ export class FaceService { engine?: FaceEngine | undefined; /** The shirt-number model (workers/ml/jersey), when one has been trained. */ jersey?: { read(original: string, box: Box): Promise } | undefined; + /** ffmpeg, to take frames out of archive videos (their faces go through the same engine as the photos). */ + videoTools?: VideoTools | undefined; + /** Frames per second looked at in a video. */ + videoFps?: number | undefined; }, ) {} @@ -96,6 +122,7 @@ export class FaceService { where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } }, data: { facesStatus: "PENDING" }, }); + await this.requeueVideos(now); return r.count; } @@ -125,6 +152,11 @@ export class FaceService { * while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute. */ async queueMissed(): Promise { + // Archive videos made while face recognition was off, or before their faces were looked for. + await this.deps.db.$executeRaw` + UPDATE cloud_videos AS v SET faces_status = 'PENDING', updated_at = now() + FROM cloud_sources s JOIN organizations o ON o.id = s.organization_id + WHERE v.source_id = s.id AND o.biometrics_enabled AND v.status = 'DONE' AND v.faces_status = 'NONE'`; // A boosted event keeps that place in the queue for photos that were missed, not only the ones already pending. return Number( await this.deps.db.$executeRaw` @@ -216,6 +248,143 @@ export class FaceService { } } + /** Archive videos whose faces are to be found, oldest request first (the photos go before them). */ + async claimVideos(limit: number): Promise { + if (limit <= 0 || !this.deps.engine || !this.deps.videoTools) return []; + const rows = await this.deps.db.$queryRaw<{ id: string }[]>` + UPDATE cloud_videos SET faces_status = 'RUNNING', updated_at = now() + WHERE id IN ( + SELECT v.id FROM cloud_videos v + WHERE v.faces_status = 'PENDING' AND v.status = 'DONE' AND v.storage_key IS NOT NULL + ORDER BY v.updated_at + LIMIT ${limit} + FOR UPDATE OF v SKIP LOCKED + ) + RETURNING id`; + return rows.map((r) => r.id); + } + + /** + * The faces of one archive video, the photos' way: frames taken from its web copy (`videoFps` a second, a minute at + * a time), each analysed by the same engine with the same filters (size, focus, sharpness), the same face followed + * through consecutive frames as one appearance, and each appearance put in the event's face groups like a photo's + * face. The run is the video's while it stays RUNNING: a newer request (its folder moved to another event, its web + * copy made again) takes it over and this run's result is dropped. Never throws. + */ + async processVideo(videoId: string): Promise { + const { db, storage, log, engine, videoTools } = this.deps; + const dir = await mkdtemp(path.join(tmpdir(), "pr-video-faces-")); + const written: string[] = []; + try { + if (!engine || !videoTools) throw new Error("face engine or ffmpeg not configured"); + const video = await db.cloudVideo.findUniqueOrThrow({ where: { id: videoId } }); + if (!video.storageKey) throw new Error("video has no web copy"); + const fps = this.deps.videoFps ?? 5; + const web = storage.resolve(`${video.storageKey}/web.mp4`); + // A glimpse of under half a second is a face in the crowd or a false detection, not someone on screen. + const follower = new FaceFollower({ same: this.thresholds(engine.model).group, minSharpness: MIN_SHARPNESS, minFrames: Math.max(1, Math.ceil(fps / 2)) }); + // A minute at a time: a whole game is tens of thousands of frames, and only each appearance's clearest frame + // is kept on disk between parts. + const length = video.durationMs ?? 0; + let frames = 0; + for (let fromMs = 0, part = 0; fromMs === 0 || fromMs < length; fromMs += VIDEO_PART_MS, part++) { + if (this.stoppingVideos) throw new VideoRunStopped(); + const partDir = path.join(dir, `part_${part}`); + await mkdir(partDir); + const files = await extractFrames(videoTools, web, partDir, fps, length ? { fromMs, lengthMs: VIDEO_PART_MS } : undefined); + for (const [i, file] of files.entries()) { + if (this.stoppingVideos) throw new VideoRunStopped(); + const analysis = await engine.analyse(file); + const faces = inFocus(analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE)); + follower.add({ + at: fromMs + Math.round((i * 1000) / fps), + file, + faces: faces.map((f) => ({ x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1, score: f.score, sharpness: f.sharpness ?? null, embedding: f.embedding ?? [] })), + }); + } + frames += files.length; + const keep = follower.keep(); + for (const file of files) if (!keep.has(file)) await rm(file, { force: true }); + // Still at it (a run that stops being touched is taken back by the stale check); and still ours. + const still = await db.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "RUNNING" } }); + if (!still.count) throw new VideoRunSuperseded(); + if (!length) break; + } + const appearances = follower.finish(); + // The frame of each appearance is kept (what a reviewer sees), small, beside the video's web copy. + const kept: { id: string; key: string; a: (typeof appearances)[number] }[] = []; + for (const a of appearances) { + const id = randomUUID(); + const key = `${video.storageKey}/faces/${id}.jpg`; + await storage.write(key, await sharp(await readFile(a.best.file)).resize(VIDEO_FRAME_SIZE, VIDEO_FRAME_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 80 }).toBuffer()); + written.push(key); + kept.push({ id, key, a }); + } + const old = await db.videoFace.findMany({ where: { videoId }, select: { frameKey: true } }); + await db.$transaction(async (tx) => { + // Only if the video is still this run's (a newer request set it PENDING meanwhile: that one wins). + const ours = await tx.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "DONE" } }); + if (!ours.count) throw new VideoRunSuperseded(); + await tx.videoFace.deleteMany({ where: { videoId } }); + for (const { id, key, a } of kept) { + await tx.videoFace.create({ + data: { + id, + videoId, + startMs: a.startMs, + endMs: a.endMs, + atMs: a.best.at, + x0: a.best.x0, + y0: a.best.y0, + x1: a.best.x1, + y1: a.best.y1, + score: a.best.score, + sharpness: a.best.sharpness, + embedding: a.embedding, + model: engine.model, + frames: a.frames, + frameKey: key, + }, + }); + } + }); + written.length = 0; + for (const o of old) await storage.remove(o.frameKey).catch(() => undefined); + // The folder's event as it is now (it may have changed during a long run). + const eventId = (await db.cloudVideo.findUnique({ where: { id: videoId }, select: { folder: { select: { eventId: true } } } }))?.folder.eventId; + if (eventId) await this.groupEvent(eventId); + log.info({ videoId, frames, appearances: kept.length }, "faces: video analysed"); + } catch (err) { + for (const key of written) await storage.remove(key).catch(() => undefined); + if (err instanceof VideoRunSuperseded) { + log.info({ videoId }, "faces: video asked again meanwhile, this run dropped"); + } else if (err instanceof VideoRunStopped) { + // The worker is stopping (a deploy): the video goes back in the queue, to be read again from the start. + await db.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "PENDING" } }).catch(() => {}); + } else { + log.warn({ videoId, err: (err as Error).message }, "faces: video analysis failed"); + await db.cloudVideo.updateMany({ where: { id: videoId, facesStatus: "RUNNING" }, data: { facesStatus: "FAILED" } }).catch(() => {}); + } + } finally { + await rm(dir, { recursive: true, force: true }); + } + } + + private stoppingVideos = false; + + /** Videos being read stop at the next frame and go back in the queue (the worker is stopping). */ + stopVideos(): void { + this.stoppingVideos = true; + } + + /** Videos left RUNNING by a worker that is gone, and failed ones after a while, back in the queue. */ + async requeueVideos(now = new Date()): Promise { + const { db } = this.deps; + const stale = await db.cloudVideo.updateMany({ where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_VIDEO_MS) } }, data: { facesStatus: "PENDING" } }); + const failed = await db.cloudVideo.updateMany({ where: { facesStatus: "FAILED", status: "DONE", updatedAt: { lt: new Date(now.getTime() - RETRY_FAILED_VIDEO_MS) } }, data: { facesStatus: "PENDING" } }); + return stale.count + failed.count; + } + /** * Puts every ungrouped face of the event into the closest group (or a new one), then names photos of * confirmed groups and refreshes suggestions. Serialised per event. @@ -232,7 +401,8 @@ export class FaceService { where: { groupId: null, photo: { eventId }, NOT: { embedding: { isEmpty: true } }, OR: [{ sharpness: null }, { sharpness: { gte: MIN_SHARPNESS } }] }, orderBy: { createdAt: "asc" }, }); - for (const face of loose) { + // The closest group of the event, or a new one: a photo's face and a video's appearance alike. + const place = async (face: { embedding: number[]; model: string }): Promise => { const { group: match } = this.thresholds(face.model); let best: FaceGroup | undefined; let bestScore = -1; @@ -252,6 +422,10 @@ export class FaceService { group = await tx.faceGroup.create({ data: { organizationId: event.organizationId, eventId, centroid: face.embedding, size: 1, model: face.model } }); groups.push(group); } + return group; + }; + for (const face of loose) { + const group = await place(face); await tx.face.update({ where: { id: face.id }, data: { groupId: group.id } }); if (group.personId) touchedPhotos.add(face.photoId); } @@ -259,11 +433,65 @@ export class FaceService { }, { timeout: 30_000 }, ); + await this.groupVideoFaces(eventId, organizationId); await this.nameConfirmedPhotos([...touchedPhotos]); await this.refreshSuggestions(eventId); this.deps.broadcaster.library(organizationId, { type: "faces.updated", eventId }); } + /** + * The appearances in the event's archive videos (their folder's event) that have no group yet, into the closest + * group or a new one: the photos' rule (`groupEvent`), but a few hundred at a time, each batch in its own short + * transaction (a whole game can bring thousands), the groups written once per batch. + */ + private async groupVideoFaces(eventId: string, organizationId: string): Promise { + const { db } = this.deps; + for (;;) { + const placed = await db.$transaction( + async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`faces:${eventId}`}))`; + const loose = await tx.videoFace.findMany({ + where: { groupId: null, video: { folder: { eventId } }, NOT: { embedding: { isEmpty: true } } }, + select: { id: true, embedding: true, model: true }, + orderBy: { createdAt: "asc" }, + take: VIDEO_GROUP_BATCH, + }); + if (!loose.length) return 0; + const groups = (await tx.faceGroup.findMany({ where: { eventId }, select: { id: true, centroid: true, size: true, model: true } })).map((g) => ({ ...g, fresh: false, members: [] as string[] })); + for (const face of loose) { + const { group: match } = this.thresholds(face.model); + let best: (typeof groups)[number] | undefined; + let bestScore = -1; + for (const g of groups) { + if (g.model !== face.model) continue; + const s = cosine(g.centroid, face.embedding); + if (s > bestScore) { + bestScore = s; + best = g; + } + } + if (best && bestScore >= match) { + best.centroid = addToMean(best.centroid, best.size, face.embedding); + best.size++; + best.members.push(face.id); + } else { + groups.push({ id: randomUUID(), centroid: face.embedding, size: 1, model: face.model, fresh: true, members: [face.id] }); + } + } + for (const g of groups) { + if (!g.members.length) continue; + if (g.fresh) await tx.faceGroup.create({ data: { id: g.id, organizationId, eventId, centroid: g.centroid, size: g.size, model: g.model } }); + else await tx.faceGroup.update({ where: { id: g.id }, data: { centroid: g.centroid, size: g.size } }); + await tx.videoFace.updateMany({ where: { id: { in: g.members } }, data: { groupId: g.id } }); + } + return loose.length; + }, + { timeout: 60_000 }, + ); + if (placed < VIDEO_GROUP_BATCH) return; + } + } + /** Suggests a person for each open group: best match among confirmed people, if clearly ahead. */ /** * Groups of the event named as the same person become one card (the largest takes the others' faces): one place @@ -282,6 +510,7 @@ export class FaceService { const [target, ...rest] = list as [(typeof named)[number], ...typeof named]; await db.$transaction([ db.face.updateMany({ where: { groupId: { in: rest.map((g) => g.id) } }, data: { groupId: target.id } }), + db.videoFace.updateMany({ where: { groupId: { in: rest.map((g) => g.id) } }, data: { groupId: target.id } }), db.faceGroup.update({ where: { id: target.id }, data: { centroid: mergeMeans(list.map((g) => ({ mean: g.centroid, count: g.size }))), size: list.reduce((n, g) => n + g.size, 0) }, @@ -623,6 +852,7 @@ export class FaceService { const personId = target.personId ?? source.personId; await db.$transaction([ db.face.updateMany({ where: { groupId: sourceId }, data: { groupId: targetId } }), + db.videoFace.updateMany({ where: { groupId: sourceId }, data: { groupId: targetId } }), db.faceGroup.update({ where: { id: targetId }, data: { centroid: mergeMeans([{ mean: source.centroid, count: source.size }, { mean: target.centroid, count: target.size }]), size: source.size + target.size, personId }, @@ -817,6 +1047,7 @@ export async function dropCrossSportSuggestions(db: Db): Promise { export class FaceWorker { private inFlight = 0; + private videosInFlight = 0; private timer: NodeJS.Timeout | undefined; private stopped = false; private ticking = false; @@ -845,6 +1076,7 @@ export class FaceWorker { void this.service.requeueStale(); let missedAt = 0; let failedAt = 0; + let videosCheckedAt = Date.now(); const tick = async () => { this.ticking = true; try { @@ -859,6 +1091,11 @@ export class FaceWorker { const n = await this.service.requeueFailed(); if (n) this.opts.log.info({ photos: n }, "faces: failed photos queued again"); } + if (Date.now() - videosCheckedAt > 10 * 60_000) { + videosCheckedAt = Date.now(); + const n = await this.service.requeueVideos(); + if (n) this.opts.log.info({ videos: n }, "faces: videos 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) { @@ -867,6 +1104,15 @@ export class FaceWorker { this.inFlight--; }); } + // Archive videos one at a time, when the photos leave room (a video is many frames). + if (!ids.length && this.videosInFlight === 0) { + for (const id of await this.service.claimVideos(1)) { + this.videosInFlight++; + void this.service.processVideo(id).finally(() => { + this.videosInFlight--; + }); + } + } } catch (err) { this.opts.log.warn({ err }, "faces: poll failed"); } finally { @@ -880,7 +1126,9 @@ export class FaceWorker { async stop(timeoutMs = 25_000): Promise { this.stopped = true; if (this.timer) clearTimeout(this.timer); - const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs }); + // A video being read can take long: it stops at the next frame and goes back in the queue. + this.service.stopVideos(); + const drained = await waitUntil(() => !this.ticking && this.inFlight === 0 && this.videosInFlight === 0, { timeoutMs }); if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "faces: stop timed out with work still running"); } } diff --git a/apps/api/src/faces/track.test.ts b/apps/api/src/faces/track.test.ts new file mode 100644 index 0000000..5cdf054 --- /dev/null +++ b/apps/api/src/faces/track.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; +import { followFaces, iou, type Frame, type FrameFace } from "./track.js"; + +const vec = (i: number, wobble = 0) => { + const v = new Array(8).fill(0); + v[i] = 1; + v[(i + 1) % 8] = wobble; + const n = Math.sqrt(1 + wobble * wobble); + return v.map((x) => x / n); +}; +const face = (x: number, emb: number[], sharpness: number | null = 100, score = 0.9): FrameFace => ({ x0: x, y0: 0.2, x1: x + 0.1, y1: 0.35, score, sharpness, embedding: emb }); +const frames = (list: FrameFace[][], fps = 5): Frame[] => list.map((faces, i) => ({ at: (i * 1000) / fps, file: `f${i}.jpg`, faces })); +const opts = { same: 0.55, minSharpness: 45 }; + +describe("following faces through a video", () => { + it("makes one appearance of a face seen frame after frame, with when and its clearest frame", () => { + const a = followFaces( + frames([[face(0.1, vec(0))], [face(0.11, vec(0, 0.1), 80)], [face(0.12, vec(0, 0.2), 300, 0.95)], [face(0.13, vec(0))]]), + opts, + ); + expect(a).toHaveLength(1); + expect(a[0]).toMatchObject({ startMs: 0, endMs: 600, frames: 4, best: { at: 400, file: "f2.jpg", sharpness: 300 } }); + expect(Math.hypot(...a[0]!.embedding)).toBeCloseTo(1, 5); + }); + + it("keeps two people apart in the same frames, even when they swap places", () => { + const a = followFaces( + frames([ + [face(0.1, vec(0)), face(0.6, vec(3))], + [face(0.35, vec(0)), face(0.35, vec(3))], + [face(0.6, vec(0)), face(0.1, vec(3))], + ]), + opts, + ); + expect(a).toHaveLength(2); + expect(a.map((x) => x.frames)).toEqual([3, 3]); + expect(a.map((x) => x.embedding.indexOf(Math.max(...x.embedding))).sort()).toEqual([0, 3]); + }); + + it("joins a face missed for a moment, and starts again after a long absence", () => { + const empty: FrameFace[] = []; + const short = followFaces(frames([[face(0.1, vec(0))], empty, empty, [face(0.1, vec(0))]]), opts); + expect(short).toHaveLength(1); + const long = followFaces(frames([[face(0.1, vec(0))], ...Array.from({ length: 10 }, () => empty), [face(0.1, vec(0))]]), opts); + expect(long.map((x) => [x.startMs, x.endMs])).toEqual([ + [0, 0], + [2200, 2200], + ]); + }); + + it("drops what was never seen sharply, like a blurred face in a photo", () => { + expect(followFaces(frames([[face(0.1, vec(0), 10)], [face(0.1, vec(0), 20)]]), opts)).toEqual([]); + // Followed through its blurred frames, but the embedding and the frame are the sharp one's. + const a = followFaces(frames([[face(0.1, vec(0, 0.3), 10)], [face(0.1, vec(0), 200)]]), opts); + expect(a[0]).toMatchObject({ frames: 2, best: { file: "f1.jpg" } }); + }); + + it("leaves out a glimpse shorter than asked (a face in the crowd, a false detection)", () => { + const list = frames([[face(0.1, vec(0)), face(0.6, vec(3))], [face(0.1, vec(0))], [face(0.1, vec(0))]]); + expect(followFaces(list, { ...opts, minFrames: 2 }).map((a) => a.frames)).toEqual([3]); + expect(followFaces(list, opts)).toHaveLength(2); + }); + + it("measures how much two boxes overlap", () => { + expect(iou(face(0.1, []), face(0.1, []))).toBeCloseTo(1); + expect(iou(face(0.1, []), face(0.5, []))).toBe(0); + }); +}); diff --git a/apps/api/src/faces/track.ts b/apps/api/src/faces/track.ts new file mode 100644 index 0000000..11291ed --- /dev/null +++ b/apps/api/src/faces/track.ts @@ -0,0 +1,158 @@ +import { cosine } from "./math.js"; + +/** + * Following faces through a video's frames. Each sampled frame is analysed like a photo (same engine, same + * filters); a face is the same appearance as one seen just before when it looks like it (embedding) and is about + * where it was (box). One appearance is then one face to review, not one per frame. + */ +export interface FrameFace { + x0: number; + y0: number; + x1: number; + y1: number; + score: number; + sharpness: number | null; + embedding: number[]; +} + +export interface Frame { + /** When in the video (ms). */ + at: number; + /** The frame's file (its clearest face's frame is kept). */ + file: string; + faces: FrameFace[]; +} + +export interface Appearance { + startMs: number; + endMs: number; + /** The clearest sighting: its frame, time and box. */ + best: FrameFace & { at: number; file: string }; + /** Mean of the sharp sightings' embeddings, unit length (what is compared with the face groups). */ + embedding: number[]; + frames: number; +} + +export interface TrackOptions { + /** How alike two sightings must be to be one appearance (the face groups' threshold). */ + same: number; + /** A face may be missed this long (turned away, behind someone) and still be the same appearance. */ + maxGapMs?: number; + /** Below this a sighting is followed but does not count for the embedding (as photos: not grouped). */ + minSharpness: number; + /** Fewer sightings than this is a passing glimpse (a face in the crowd, a false detection): not an appearance. */ + minFrames?: number; +} + +interface Track { + /** How many frames it was seen in, and when last (the sightings themselves are not kept: a long video has many). */ + count: number; + lastAt: number; + last: FrameFace & { at: number }; + first: number; + /** The clearest sharp sighting, and the sum of the sharp sightings' embeddings. */ + best: (FrameFace & { at: number; file: string }) | null; + sum: number[] | null; + sharp: number; +} + +/** Overlap of two boxes (intersection over union). */ +export function iou(a: FrameFace, b: FrameFace): number { + const w = Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)); + const h = Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0)); + const inter = w * h; + const union = (a.x1 - a.x0) * (a.y1 - a.y0) + (b.x1 - b.x0) * (b.y1 - b.y0) - inter; + return union > 0 ? inter / union : 0; +} + +const unit = (v: number[]): number[] => { + const n = Math.sqrt(v.reduce((s, x) => s + x * x, 0)); + return n > 0 ? v.map((x) => x / n) : v; +}; + +const sharpEnough = (f: FrameFace, min: number) => f.sharpness == null || f.sharpness >= min; + +/** + * Follows faces frame after frame (in time order), so a long video can be read a part at a time: `add` each frame, + * `keep` says which frame files are still needed (the clearest sighting of each appearance), `finish` gives the + * appearances. Each frame's faces are matched to the open appearances, most alike first, one face per appearance + * per frame; a face still near where the appearance was counts as more alike (a turned head changes the embedding + * more than the place). Appearances never seen sharply are dropped: like a blurred face in a photo, they cannot be + * compared with anyone. + */ +export class FaceFollower { + private readonly open: Track[] = []; + private readonly closed: Track[] = []; + private readonly maxGap: number; + + constructor(private readonly opts: TrackOptions) { + this.maxGap = opts.maxGapMs ?? 1500; + } + + add(frame: Frame): void { + const { open, closed } = this; + // Appearances not seen for too long are over. + for (let i = open.length - 1; i >= 0; i--) if (frame.at - open[i]!.last.at > this.maxGap) closed.push(...open.splice(i, 1)); + const pairs: { t: number; f: number; s: number }[] = []; + frame.faces.forEach((face, f) => { + if (!face.embedding.length) return; + open.forEach((track, t) => { + const look = cosine(track.last.embedding, face.embedding); + const near = iou(track.last, face); + // Where it was helps; it never makes a stranger the same person. + const s = look + 0.15 * near; + if (look >= this.opts.same - (near > 0.3 ? 0.1 : 0)) pairs.push({ t, f, s }); + }); + }); + pairs.sort((a, b) => b.s - a.s); + const usedT = new Set(); + const usedF = new Set(); + for (const p of pairs) { + if (usedT.has(p.t) || usedF.has(p.f)) continue; + usedT.add(p.t); + usedF.add(p.f); + const face = frame.faces[p.f]!; + this.sight(open[p.t]!, face, frame); + } + frame.faces.forEach((face, f) => { + if (usedF.has(f) || !face.embedding.length) return; + const track: Track = { count: 0, lastAt: frame.at, last: { ...face, at: frame.at }, best: null, sum: null, sharp: 0, first: frame.at }; + this.sight(track, face, frame); + open.push(track); + }); + } + + private sight(track: Track, face: FrameFace, frame: Frame): void { + const at = { ...face, at: frame.at, file: frame.file }; + track.count++; + track.lastAt = frame.at; + track.last = { ...face, at: frame.at }; + if (!sharpEnough(face, this.opts.minSharpness)) return; + track.sharp++; + if (!track.sum) track.sum = new Array(face.embedding.length).fill(0); + for (let i = 0; i < track.sum.length; i++) track.sum[i]! += face.embedding[i] ?? 0; + // The clearest: sharpness times confidence (confidence alone when the engine gives no sharpness). + const clear = (f: FrameFace) => (f.sharpness ?? 1) * f.score; + if (!track.best || clear(face) > clear(track.best)) track.best = at; + } + + /** The frame files still needed: the clearest sighting of every appearance so far. */ + keep(): Set { + return new Set([...this.open, ...this.closed].flatMap((t) => (t.best ? [t.best.file] : []))); + } + + finish(): Appearance[] { + return [...this.closed, ...this.open] + .flatMap((t): Appearance[] => + t.best && t.sum && t.count >= (this.opts.minFrames ?? 1) ? [{ startMs: t.first, endMs: t.lastAt, best: t.best, embedding: unit(t.sum), frames: t.count }] : [], + ) + .sort((a, b) => a.startMs - b.startMs); + } +} + +/** The appearances in a video's frames, all at once (see `FaceFollower`). */ +export function followFaces(frames: Frame[], opts: TrackOptions): Appearance[] { + const follower = new FaceFollower(opts); + for (const frame of [...frames].sort((a, b) => a.at - b.at)) follower.add(frame); + return follower.finish(); +} diff --git a/apps/api/src/storage/storage.ts b/apps/api/src/storage/storage.ts index d29bf67..1cad2df 100644 --- a/apps/api/src/storage/storage.ts +++ b/apps/api/src/storage/storage.ts @@ -119,6 +119,16 @@ export class UrlSigner { return `/v1/files/videos/${videoId}/${variant}?exp=${exp}&sig=${this.mac(videoId, `video-${variant}`, exp)}`; } + /** Signed URL of the frame an appearance in a video is clearest in (shown when its face is reviewed). */ + videoFaceUrl(videoFaceId: string): string { + const exp = this.expiry(); + return `/v1/files/video-faces/${videoFaceId}?exp=${exp}&sig=${this.mac(videoFaceId, "video-face", exp)}`; + } + + verifyVideoFace(videoFaceId: string, exp: number, sig: string): boolean { + return this.verifyVideo(videoFaceId, "face", exp, sig); + } + verifyVideo(videoId: string, variant: string, exp: number, sig: string): boolean { if (!Number.isFinite(exp) || exp < Math.floor(this.now() / 1000)) return false; const expected = Buffer.from(this.mac(videoId, `video-${variant}`, exp)); diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 7c5930c..d499124 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -105,7 +105,8 @@ const renders = renderEngine ? new RenderWorker(develop, { concurrency: capacity const sportsService = new SportsService({ db, storage, log, fetch }); // Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud. // A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share. -const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS), storage, videoTools: findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir()) }); +const videoTools = findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir()); +const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS), storage, videoTools }); const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveDownloads, intervalMs: 2000, log, pressure: new Pressure(), videos: config.ARCHIVE_VIDEO_CONCURRENCY }); const deliveryService = new DeliveryService({ db, storage, secrets, broadcaster, log, develop, originals: archiveService, notifications: new Notifications(db, (err) => log.warn({ err }, "notifications: not written")) }); // Every arrival goes on to the destinations that take all of them (one's own backup of the originals). @@ -132,7 +133,7 @@ const faceEngine = 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 }), { + ? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), { concurrency: capacity.faces, intervalMs: 1000, log, diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index 2a8eb1c..05185a0 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -9,6 +9,8 @@ import { galleryAssignments } from "../src/archive/gallery.js"; import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryRoot, isExhibition, isInitials, isTeam, knownVersus, lisbonDay, parseFolder, pickFixture, teamLabel, teamMatcher, type FixtureCandidate } from "../src/archive/match.js"; import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js"; import { ArchiveService, localDirs } from "../src/archive/service.js"; +import { FaceService } from "../src/faces/service.js"; +import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js"; import { execFileSync } from "node:child_process"; import { SecretBox } from "../src/delivery/secrets.js"; import { IngestService } from "../src/ingest/service.js"; @@ -1540,6 +1542,191 @@ describe("archive from a Nextcloud", () => { await ctx.app.inject({ method: "POST", url: `/v1/cloud-sources/${source.id}/scan`, headers: bearer(token) }); expect((await ctx.db.cloudVideo.findFirstOrThrow({ where: { path: { endsWith: "Treino.mp4" } } })).status).toBe("PENDING"); }, 60_000); + + it.skipIf(!hasFfmpeg)("finds faces in videos the photos' way: same groups, same suggestions, reviewed and named, and shown with when", async () => { + const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; + cloud.add(`${game}/Golo 1.mp4`, mp4(640, 360)); + await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } }); + const source = await connect(); + cloud.authorised = true; + await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); + const storage = new LocalStorage(storageRoot); + const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } }); + await videoWorker.scan(source.id); + for (const id of await worker.claim(10)) await worker.index(id); + for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id); + const video = await ctx.db.cloudVideo.findFirstOrThrow(); + expect(video).toMatchObject({ status: "DONE", facesStatus: "PENDING" }); + + // Rita in the photos and the first second of the video; someone else from 0.8 s on, in the video only. + const rita = unitVec(1); + const other = unitVec(2); + const at = (x: number, emb: number[]) => ({ x0: x, y0: 0.2, x1: x + 0.12, y1: 0.4, score: 0.95, sharpness: 120, landmarks: [] as [number, number][], embedding: emb }); + const engine: FaceEngine = { + model: "auraface-v1", + async analyse(file: string): Promise { + const frame = /frame_(\d+)\.jpg$/.exec(file); + if (!frame) return { width: 2048, height: 1365, faces: [at(0.4, rita)] }; + const i = Number(frame[1]); + return { width: 640, height: 360, faces: [...(i <= 6 ? [at(0.1, rita)] : []), ...(i >= 5 ? [at(0.6, other)] : [])] }; + }, + async close() {}, + }; + const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 5 }); + await ctx.db.person.create({ data: { organizationId: orgId, name: "Rita Sousa", centroid: rita, model: "auraface-v1", faceCount: 5 } }); + await ctx.db.photo.updateMany({ data: { facesStatus: "PENDING" } }); + for (let ids = await faces.claim(10); ids.length; ids = await faces.claim(10)) for (const id of ids) await faces.process(id); + expect(await faces.claimVideos(1)).toEqual([video.id]); + await faces.processVideo(video.id); + + // Two appearances, each with when it is on screen and its frame; Rita's joins the group of her photos' faces. + const appearances = await ctx.db.videoFace.findMany({ where: { videoId: video.id }, orderBy: { startMs: "asc" } }); + expect(appearances.map((a) => [a.startMs, a.endMs, a.frames])).toEqual([ + [0, 1000, 6], + [800, 1800, 6], + ]); + expect(await storage.exists(appearances[0]!.frameKey)).toBe(true); + const photoFace = await ctx.db.face.findFirstOrThrow({ where: { photo: { originalName: "PS_0001.jpg" } } }); + expect(appearances[0]!.groupId).toBe(photoFace.groupId); + expect(appearances[1]!.groupId).not.toBe(photoFace.groupId); + const ritaGroup = await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: photoFace.groupId! }, include: { suggested: true } }); + expect(ritaGroup.suggested?.name).toBe("Rita Sousa"); + expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("DONE"); + + // An editor of the game's folder reviews it: the card carries the video's frame, and confirming names both. + const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01"); + cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] }); + cloud.authorised = false; + cloud.loginAs = "abc"; + const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; + cloud.authorised = true; + const club = ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; + const as = { authorization: `Archive ${club}` }; + let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review?status=suggested`, headers: as }); + const card = (res.json().groups as { id: string; photos: number; videos: number; faces: { src: string; video?: { id: string; atMs: number } }[] }[]).find((g) => g.id === ritaGroup.id)!; + expect(card).toMatchObject({ photos: 2, videos: 1 }); + const frame = card.faces.find((f) => f.video)!; + expect(frame.video).toMatchObject({ id: video.id }); + res = await ctx.app.inject({ method: "GET", url: frame.src }); + expect([res.statusCode, res.headers["content-type"]]).toEqual([200, "image/jpeg"]); + expect((await ctx.app.inject({ method: "GET", url: frame.src.replace(/sig=[^&]+/, "sig=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") })).statusCode).toBe(404); + + // Before: probable in the gallery's video. After confirming: named, with when. + const gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } }); + const peopleOfVideo = async () => ((await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gameFolder.id}`, headers: as })).json().videos[0].people as { name: string; level: string; startMs: number; moments: unknown[] }[]); + expect(await peopleOfVideo()).toEqual([expect.objectContaining({ name: "Rita Sousa", level: "probable", startMs: 0 })]); + res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${ritaGroup.id}`, headers: as, payload: { action: "confirm" } }); + expect(res.statusCode).toBe(200); + expect(await peopleOfVideo()).toEqual([{ id: ritaGroup.suggestedPersonId, name: "Rita Sousa", level: "confirmed", startMs: 0, moments: [{ startMs: 0, endMs: 1000 }] }]); + + // Her page lists the video, with its frame and the moments to jump to. + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/${ritaGroup.suggestedPersonId}`, headers: as }); + expect(res.json().videos).toEqual([expect.objectContaining({ id: video.id, name: "Golo 1.mp4", level: "confirmed", moments: [{ startMs: 0, endMs: 1000 }], gallery: expect.objectContaining({ id: gameFolder.id }) })]); + + // A viewer without edit rights cannot act on a group that has the video. + cloud.viewers.set("ler", { password: "ler-pass", shared: [po01] }); + cloud.authorised = false; + cloud.loginAs = "ler"; + const s2 = ((await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }).state; + cloud.authorised = true; + const reader = ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state: s2 } })).json() as { token: string }).token; + const otherGroup = appearances[1]!.groupId!; + res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${otherGroup}`, headers: { authorization: `Archive ${reader}` }, payload: { action: "ignore" } }); + expect(res.statusCode).toBe(403); + + // The folder moved to another event: its video's faces are looked for again there, never left in the old groups. + const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g2" } }); + await videoWorker.setFolderEvent(gameFolder.id, { fixtureId: fixture.id }); + expect(await ctx.db.videoFace.count({ where: { videoId: video.id } })).toBe(0); + expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); + expect(await storage.exists(appearances[0]!.frameKey)).toBe(false); + }, 90_000); + + it.skipIf(!hasFfmpeg)("reads a long video a minute at a time: one face on screen throughout is one appearance", async () => { + const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; + cloud.add(`${game}/Jogo.mp4`, execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=5:duration=65", "-c:v", "mpeg4", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1"], { maxBuffer: 64 * 1024 * 1024 })); + await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } }); + const source = await connect(); + cloud.authorised = true; + await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); + const storage = new LocalStorage(storageRoot); + const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } }); + await videoWorker.scan(source.id); + for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id); + const video = await ctx.db.cloudVideo.findFirstOrThrow(); + const someone = unitVec(7); + let analysed = 0; + const engine: FaceEngine = { + model: "auraface-v1", + async analyse(): Promise { + analysed++; + return { width: 160, height: 90, faces: [{ x0: 0.4, y0: 0.2, x1: 0.55, y1: 0.5, score: 0.9, sharpness: 100, landmarks: [], embedding: someone }] }; + }, + async close() {}, + }; + const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 2 }); + expect(await faces.claimVideos(1)).toEqual([video.id]); + await faces.processVideo(video.id); + expect(analysed).toBeGreaterThanOrEqual(128); + const appearances = await ctx.db.videoFace.findMany({ where: { videoId: video.id } }); + expect(appearances).toHaveLength(1); + expect(appearances[0]!.startMs).toBe(0); + expect(appearances[0]!.endMs).toBeGreaterThan(64_000); + expect(appearances[0]!.frames).toBe(analysed); + }, 120_000); + + it.skipIf(!hasFfmpeg)("never keeps a stale video result: asked again meanwhile, it is dropped; a stopping worker puts it back", async () => { + const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; + cloud.add(`${game}/Golo 1.mp4`, mp4(640, 360)); + await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } }); + const source = await connect(); + cloud.authorised = true; + await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); + const storage = new LocalStorage(storageRoot); + const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } }); + await videoWorker.scan(source.id); + for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id); + const video = await ctx.db.cloudVideo.findFirstOrThrow(); + const someone = unitVec(9); + let onFirst: (() => Promise) | null = null; + const engine: FaceEngine = { + model: "auraface-v1", + async analyse(): Promise { + const hook = onFirst; + onFirst = null; + if (hook) await hook(); + return { width: 640, height: 360, faces: [{ x0: 0.4, y0: 0.2, x1: 0.55, y1: 0.5, score: 0.9, sharpness: 100, landmarks: [], embedding: someone }] }; + }, + async close() {}, + }; + const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 5 }); + + // Asked again while being read (its folder moved, its copy made again): this run writes nothing. + expect(await faces.claimVideos(1)).toEqual([video.id]); + onFirst = async () => void (await ctx.db.cloudVideo.update({ where: { id: video.id }, data: { facesStatus: "PENDING" } })); + await faces.processVideo(video.id); + expect(await ctx.db.videoFace.count()).toBe(0); + expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); + + // The next run is the one that counts. + expect(await faces.claimVideos(1)).toEqual([video.id]); + await faces.processVideo(video.id); + expect(await ctx.db.videoFace.count()).toBe(1); + expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("DONE"); + + // A worker stopping mid-video (a deploy) puts it back in the queue, its earlier faces untouched. + await ctx.db.cloudVideo.update({ where: { id: video.id }, data: { facesStatus: "PENDING" } }); + expect(await faces.claimVideos(1)).toEqual([video.id]); + onFirst = async () => faces.stopVideos(); + await faces.processVideo(video.id); + expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); + expect(await ctx.db.videoFace.count()).toBe(1); + + // Left RUNNING by a worker that is gone, and failed ones after a while: back in the queue. + await ctx.db.$executeRaw`UPDATE cloud_videos SET faces_status = 'RUNNING', updated_at = now() - interval '2 hours'`; + expect(await faces.requeueVideos()).toBe(1); + expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); + }, 90_000); }); const hasFfmpeg = (() => { @@ -1561,3 +1748,10 @@ function mp4(width: number, height: number): Buffer { "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1", ], { maxBuffer: 64 * 1024 * 1024 }); } + +/** A unit vector of the embedder's length, different for each seed. */ +function unitVec(seed: number): number[] { + const v = Array.from({ length: 512 }, (_, i) => Math.sin(seed * 977 + i * 13.37)); + const n = Math.hypot(...v); + return v.map((x) => x / n); +} diff --git a/apps/site/src/app/arquivo/[id]/Gallery.tsx b/apps/site/src/app/arquivo/[id]/Gallery.tsx index b774c6a..d83bfc1 100644 --- a/apps/site/src/app/arquivo/[id]/Gallery.tsx +++ b/apps/site/src/app/arquivo/[id]/Gallery.tsx @@ -380,7 +380,7 @@ export function Gallery({ )} - {playing !== null && videos[playing] && } + {playing !== null && videos[playing] && } {index !== null && photos[index] && ( (null); const [only, setOnly] = useState(null); const [index, setIndex] = useState(null); + /** A video open in the player, at one of the person's moments. */ + const [playing, setPlaying] = useState<{ index: number; at: number } | null>(null); const [error, setError] = useState(false); const [attempt, setAttempt] = useState(0); @@ -52,6 +55,24 @@ export function PhotosOf({ }, [sourceId, view.kind, view.id, token, onExpired, attempt]); const photos = useMemo(() => (data ? (only ? data.photos.filter((p) => p.level === only) : data.photos) : []), [data, only]); + // Their videos, as the player takes them (who else appears is in each gallery; here, when they do). + const videos: ArchiveVideo[] = useMemo( + () => + (data?.videos ?? []).map((v) => ({ + id: v.id, + name: v.name, + durationMs: v.durationMs, + width: v.width, + height: v.height, + capturedAt: null, + thumb: v.thumb, + poster: v.poster, + src: v.src, + download: v.download, + people: data?.person ? [{ id: data.person.id, name: data.person.name, level: v.level, startMs: v.moments[0]?.startMs ?? 0, moments: v.moments }] : [], + })), + [data], + ); const counts = useMemo(() => { const c: Record = { confirmed: 0, probable: 0, similar: 0 }; for (const p of data?.photos ?? []) if (p.level) c[p.level]++; @@ -159,7 +180,43 @@ export function PhotosOf({ ))} {counts.similar > 0 &&

“Parecido” são caras semelhantes que ainda ninguém identificou: confirma antes de publicar.

} - {photos.length === 0 &&

Sem fotos.

} + {videos.length > 0 && ( +
+

Vídeos

+
+ {data!.videos!.map((v, i) => ( +
+ +
+ + + {v.gallery?.title ?? v.name} + + {LEVEL[v.level]}{" "} + {[v.gallery?.startsAt ? day.format(new Date(v.gallery.startsAt)) : null, v.name].filter(Boolean).join(" · ")} + + +
+ + {v.moments.map((m, j) => ( + + ))} + +
+ ))} +
+ {photos.length > 0 &&

Fotos

} +
+ )} + {photos.length === 0 && videos.length === 0 &&

Sem fotos.

}
{photos.map((p, i) => (
+ {playing !== null && videos[playing.index] && ( + setPlaying(i === null ? null : { index: i, at: 0 })} onPerson={onPerson} /> + )} {index !== null && photos[index] && ( item.faces); const photos = groups.reduce((n, item) => n + item.photos, 0); + const videos = groups.reduce((n, item) => n + (item.videos ?? 0), 0); const [open, setOpen] = useState(null); const [first, ...rest] = faces; const onKey = (e: React.KeyboardEvent) => { @@ -407,7 +408,7 @@ function Card({
{who ? who.name : "Sem nome"} - {[who?.number && `nº ${who.number}`, who?.club, `${photos} ${photos === 1 ? "foto" : "fotos"}`, groups.length > 1 ? `${groups.length} jogos` : null].filter(Boolean).join(" · ")} + {[who?.number && `nº ${who.number}`, who?.club, photos || !videos ? `${photos} ${photos === 1 ? "foto" : "fotos"}` : null, videos ? `${videos} ${videos === 1 ? "vídeo" : "vídeos"}` : null, groups.length > 1 ? `${groups.length} jogos` : null].filter(Boolean).join(" · ")} {groups.length === 1 && g.event && {[g.event.title, g.event.startsAt ? shortDay.format(new Date(g.event.startsAt)) : null].filter(Boolean).join(" · ")}} {groups.length > 1 && ( diff --git a/apps/site/src/app/arquivo/[id]/VideoPlayer.tsx b/apps/site/src/app/arquivo/[id]/VideoPlayer.tsx index 059284d..d65d2c7 100644 --- a/apps/site/src/app/arquivo/[id]/VideoPlayer.tsx +++ b/apps/site/src/app/arquivo/[id]/VideoPlayer.tsx @@ -1,7 +1,7 @@ "use client"; import { useEffect, useRef } from "react"; -import { duration, shortDay, type ArchiveVideo } from "./api"; +import { duration, LEVEL, shortDay, type ArchiveVideo } from "./api"; import { Icon } from "./parts"; import "./video.css"; @@ -10,9 +10,29 @@ import "./video.css"; * arrived, and jumps anywhere), the arrows go to the gallery's other videos. Every viewer saves it at web size; * those who edit the folder on the cloud also get the link to the original there. */ -export function VideoPlayer({ videos, index, onIndex }: { videos: ArchiveVideo[]; index: number; onIndex: (i: number | null) => void }) { +export function VideoPlayer({ + videos, + index, + onIndex, + startAt, + onPerson, +}: { + videos: ArchiveVideo[]; + index: number; + onIndex: (i: number | null) => void; + /** Where to start the first video (ms): a person's moment in it. */ + startAt?: number | undefined; + onPerson?: ((personId: string) => void) | undefined; +}) { const current = videos[index]!; const player = useRef(null); + const opened = useRef(index); + const jump = (ms: number) => { + const v = player.current; + if (!v) return; + v.currentTime = ms / 1000; + void v.play().catch(() => undefined); + }; useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -61,7 +81,21 @@ export function VideoPlayer({ videos, index, onIndex }: { videos: ArchiveVideo[]
{/* key: a new element per video, so the next one starts from its beginning with its own poster. */} -
{index > 0 && (