diff --git a/apps/api/src/archive/find.ts b/apps/api/src/archive/find.ts index e1b68e4..5d138ea 100644 --- a/apps/api/src/archive/find.ts +++ b/apps/api/src/archive/find.ts @@ -4,7 +4,8 @@ import { z } from "zod"; import { Prisma } from "../generated/prisma/client.js"; import type { Db } from "../db.js"; import { facesOut, lookupFailed, lookupImage, LookupQuery } from "../faces/lookupRoutes.js"; -import type { FaceLookup, MatchLevel } from "../faces/lookup.js"; +import type { FaceLookup } from "../faces/lookup.js"; +import { cosine, POSSIBLE_BELOW, THRESHOLDS } from "../faces/math.js"; import { conflict, forbidden, notFound } from "../lib/errors.js"; import type { UrlSigner } from "../storage/storage.js"; import { faceBox } from "./people.js"; @@ -15,6 +16,9 @@ import type { Viewer } from "./viewer.js"; * Search the archive by a photo: for editors on the cloud (same rights as "Rever rostos"), when the archive has * the option on and the organization has biometrics on. The search photo is read in memory and never kept. * Results stay inside the folders the viewer may see. + * + * Speed: face groups are ranked with pgvector HNSW (`centroid_vec`), the same path as "more of this face". + * Event ids of the viewer's scope are cached a few minutes so a second search does not re-scan cloud_files. */ interface Deps { db: Db; @@ -26,28 +30,35 @@ interface Deps { } const SourceParams = z.object({ sourceId: z.uuid() }); +const EVENTS_TTL_MS = 5 * 60_000; +const NEAREST = 400; +const MAX_PHOTOS = 500; type CardLevel = "confirmed" | "probable" | "similar"; -const toCardLevel = (level: MatchLevel, named: boolean): CardLevel => { - if (named && level === "strong") return "confirmed"; - if (level === "strong") return "probable"; - return "similar"; -}; +const levelOf = (score: number, match: number): CardLevel => (score >= match ? "probable" : "similar"); export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps) { const { db, signer, lookup, viewerOf, visibleFolders, editableFolders } = deps; - const scopeOf = async (v: Viewer): Promise => { + /** Event ids of a viewer's archive scope: the heavy DISTINCT over cloud_files, reused while they search. */ + const eventsCache = new Map(); + + const scopeOf = async (v: Viewer): Promise<{ sql: Prisma.Sql; key: string } | null> => { const visible = await visibleFolders(v); if (visible !== "all" && !visible.length) return null; - if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`; - return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`; + const key = visible === "all" ? "all" : [...visible].sort().join(","); + const sql = + visible === "all" + ? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}` + : Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`; + return { sql, key }; }; const requireFind = async (v: Viewer) => { const editable = await editableFolders(v); if (editable !== "all" && !editable.length) throw forbidden("archive_edit_required"); + // Always read the option from the DB so turning it off takes effect at once (not cached). const source = await db.cloudSource.findUnique({ where: { id: v.s }, select: { id: true, organizationId: true, photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } }, @@ -57,6 +68,64 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps return source; }; + const eventsInScope = async (sourceId: string, scope: Prisma.Sql, cacheKey: string): Promise => { + const key = `${sourceId}:${cacheKey}`; + const hit = eventsCache.get(key); + if (hit && Date.now() - hit.at < EVENTS_TTL_MS) return hit.ids; + const rows = await db.$queryRaw<{ event_id: string }[]>` + SELECT DISTINCT ph.event_id AS event_id + FROM photos ph + JOIN cloud_files cf ON cf.photo_id = ph.id AND ${scope} + WHERE ph.event_id IS NOT NULL`; + const ids = rows.map((r) => r.event_id); + eventsCache.set(key, { at: Date.now(), ids }); + return ids; + }; + + /** + * Face groups in the viewer's events like the probe. Production (512-d) uses the HNSW index; shorter test + * vectors fall back to a cosine over the float array. + */ + const nearGroups = async (eventIds: string[], embedding: number[], model: string) => { + if (!eventIds.length) return [] as { id: string; personId: string | null; score: number }[]; + const match = (THRESHOLDS[model] ?? { match: 0.5 }).match; + const floor = match - POSSIBLE_BELOW; + if (embedding.length === 512) { + const literal = `[${embedding.map((n) => (Number.isFinite(n) ? n : 0)).join(",")}]`; + const rows = await db.$queryRaw<{ id: string; person_id: string | null; score: number }[]>` + SELECT id, person_id, score FROM ( + SELECT g.id, g.person_id, (1 - (g.centroid_vec <=> ${literal}::vector))::float AS score + FROM face_groups g + WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.centroid_vec IS NOT NULL AND g.size > 0 + AND g.event_id = ANY(${eventIds}::uuid[]) + ORDER BY g.centroid_vec <=> ${literal}::vector + LIMIT ${NEAREST} + ) ranked + WHERE score >= ${floor}`; + return rows.map((r) => ({ id: r.id, personId: r.person_id, score: Number(r.score) })); + } + const groups = await db.$queryRaw<{ id: string; centroid: unknown; person_id: string | null }[]>` + SELECT g.id, g.centroid, g.person_id + FROM face_groups g + WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.size > 0 AND cardinality(g.centroid) > 0 + AND g.event_id = ANY(${eventIds}::uuid[])`; + const asVector = (v: unknown): number[] => + Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : []; + return groups + .map((g) => ({ id: g.id, personId: g.person_id, score: cosine(embedding, asVector(g.centroid)) })) + .filter((x) => x.score >= floor) + .sort((a, b) => b.score - a.score) + .slice(0, NEAREST); + }; + + /** Starts the face engine so the first real search does not wait on model load. */ + app.get("/v1/archive/:sourceId/find/ready", async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + await requireFind(v); + return { ready: lookup.available }; + }); + /** * A photo of the person (headshot, press cutout) against faces already indexed in the folders this editor may * see. Best matches first. The uploaded file is not stored. @@ -66,25 +135,22 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps const q = LookupQuery.parse(req.query); const v = viewerOf(req, sourceId); const source = await requireFind(v); - const scope = await scopeOf(v); - if (!scope) return { faces: [], used: 0, people: [], total: 0, photos: [] }; + const scoped = await scopeOf(v); + if (!scoped) return { faces: [], used: 0, people: [], total: 0, photos: [] }; + const { sql: scope, key: scopeKey } = scoped; const image = await lookupImage(req); const read = await lookup.facesIn(image).catch(lookupFailed); const used = Math.min(q.face, read.faces.length - 1); const probe = read.faces[used]!; + const match = (THRESHOLDS[read.model] ?? { match: 0.5 }).match; - const events = await db.$queryRaw<{ event_id: string }[]>` - SELECT DISTINCT ph.event_id AS event_id - FROM photos ph - JOIN cloud_files cf ON cf.photo_id = ph.id AND ${scope} - WHERE ph.event_id IS NOT NULL`; - const eventIds = events.map((e) => e.event_id); + const eventIds = await eventsInScope(sourceId, scope, scopeKey); if (!eventIds.length) return { faces: facesOut(read.faces), used, people: [], total: 0, photos: [] }; const [people, groups] = await Promise.all([ lookup.people(source.organizationId, probe.embedding, read.model), - lookup.groups(source.organizationId, probe.embedding, read.model, { eventIds, limit: 400 }), + nearGroups(eventIds, probe.embedding, read.model), ]); const best = new Map(); @@ -93,58 +159,66 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps if (!was || score > was.score) best.set(photoId, { faceId, score, level, sharpness }); }; - if (groups.length) { - const faces = await db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>` - SELECT f.id, f.photo_id, f.group_id, f.sharpness - FROM faces f - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} - WHERE f.group_id = ANY(${groups.map((g) => g.groupId)}::uuid[])`; - const byGroup = new Map(groups.map((g) => [g.groupId, g])); - for (const f of faces) { - const g = byGroup.get(f.group_id)!; - keep(f.photo_id, f.id, g.score, toCardLevel(g.level, !!g.personId), f.sharpness); - } - } - const sure = people.filter((p) => p.level === "strong"); - if (sure.length) { - const named = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null }[]>` - SELECT f.id, f.photo_id, f.sharpness, g.person_id - FROM faces f - JOIN face_groups g ON g.id = f.group_id - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} - WHERE g.ignored_at IS NULL AND g.person_id = ANY(${sure.map((p) => p.id)}::uuid[])`; - const scoreOf = new Map(sure.map((p) => [p.id, p.score])); - for (const f of named) { - const score = (f.person_id && scoreOf.get(f.person_id)) || sure[0]!.score; - keep(f.photo_id, f.id, score, "confirmed", f.sharpness); - } + const groupIds = groups.map((g) => g.id); + + const [groupFaces, namedFaces] = await Promise.all([ + groupIds.length + ? db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>` + SELECT f.id, f.photo_id, f.group_id, f.sharpness + FROM faces f + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} + WHERE f.group_id = ANY(${groupIds}::uuid[])` + : Promise.resolve([] as { id: string; photo_id: string; group_id: string; sharpness: number | null }[]), + sure.length + ? db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null }[]>` + SELECT f.id, f.photo_id, f.sharpness, g.person_id + FROM faces f + JOIN face_groups g ON g.id = f.group_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} + WHERE g.ignored_at IS NULL AND g.person_id = ANY(${sure.map((p) => p.id)}::uuid[])` + : Promise.resolve([] as { id: string; photo_id: string; sharpness: number | null; person_id: string | null }[]), + ]); + + const byGroup = new Map(groups.map((g) => [g.id, g])); + for (const f of groupFaces) { + const g = byGroup.get(f.group_id)!; + const level: CardLevel = g.personId && g.score >= match ? "confirmed" : levelOf(g.score, match); + keep(f.photo_id, f.id, g.score, level, f.sharpness); + } + const scoreOf = new Map(sure.map((p) => [p.id, p.score])); + for (const f of namedFaces) { + const score = (f.person_id && scoreOf.get(f.person_id)) || sure[0]!.score; + keep(f.photo_id, f.id, score, "confirmed", f.sharpness); } const hits = [...best.entries()] .map(([photoId, h]) => ({ photoId, ...h })) .sort((a, b) => b.score - a.score || (b.sharpness ?? 0) - (a.sharpness ?? 0)); - const shown = hits.slice(0, 500); + const shown = hits.slice(0, MAX_PHOTOS); if (!shown.length) return { faces: facesOut(read.faces), used, people, total: 0, photos: [] }; const ids = shown.map((h) => h.photoId); - const links = await db.$queryRaw<{ photo_id: string; folder_id: string }[]>` - SELECT DISTINCT ON (cf.photo_id) cf.photo_id, cf.folder_id - FROM cloud_files cf - WHERE cf.photo_id = ANY(${ids}::uuid[]) AND ${scope} - ORDER BY cf.photo_id, cf.path`; + const faceIds = shown.map((h) => h.faceId); + const [links, photos, faceRows] = await Promise.all([ + db.$queryRaw<{ photo_id: string; folder_id: string }[]>` + SELECT DISTINCT ON (cf.photo_id) cf.photo_id, cf.folder_id + FROM cloud_files cf + WHERE cf.photo_id = ANY(${ids}::uuid[]) AND ${scope} + ORDER BY cf.photo_id, cf.path`, + db.photo.findMany({ + where: { id: { in: ids } }, + select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true }, + }), + db.face.findMany({ where: { id: { in: faceIds } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } }), + ]); const folderOf = new Map(links.map((r) => [r.photo_id, r.folder_id])); - const photos = await db.photo.findMany({ - where: { id: { in: ids } }, - select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true }, - }); - const byId = new Map(photos.map((p) => [p.id, p])); - const faceRows = await db.face.findMany({ where: { id: { in: shown.map((h) => h.faceId) } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } }); - const faceById = new Map(faceRows.map((f) => [f.id, f])); const folders = await db.cloudFolder.findMany({ where: { id: { in: [...new Set(folderOf.values())] } }, include: { event: true } }); const galleries = new Map( folders.map((f) => [f.id, { id: f.id, title: f.event ? eventName(f.event) : (f.path.split("/").pop() ?? ""), startsAt: f.event?.startsAt ?? null, competition: f.event?.competition ?? null }]), ); + const byId = new Map(photos.map((p) => [p.id, p])); + const faceById = new Map(faceRows.map((f) => [f.id, f])); const cards = shown .filter((h) => byId.has(h.photoId) && folderOf.has(h.photoId)) diff --git a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx index 8899954..149669f 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -58,6 +58,12 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } cached(`/v1/archive/${info.id}/me`, token, setMe).catch(() => setMe(null)); }, [token, info.id, meTick]); + // Editors who can search by photo: start the face engine as soon as they are in, so the first search is quicker. + useEffect(() => { + if (!token || !me?.canFind) return; + void fetch(`/v1/archive/${info.id}/find/ready`, { headers: { authorization: `Archive ${token}` } }).catch(() => undefined); + }, [token, me?.canFind, info.id]); + /** Ends the session here and on the server (which revokes the app password kept on the cloud). */ const signOut = useCallback(() => { const t = readStored(storageKey(info.id)); diff --git a/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx b/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx index 8505f4e..afb4e0c 100644 --- a/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx +++ b/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx @@ -1,6 +1,6 @@ "use client"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { day, download, Forbidden, LEVEL, Unauthorised, type FindByPhotoResult, type Level, type Me, type PhotoFace } from "./api"; import { Lightbox } from "./Lightbox"; import { Icon } from "./parts"; @@ -35,6 +35,11 @@ export function FindByPhoto({ const [only, setOnly] = useState(null); const [index, setIndex] = useState(null); + // Start the face engine while the editor is on this page, so the first upload does not wait on model load. + useEffect(() => { + void fetch(`/v1/archive/${sourceId}/find/ready`, { headers: { authorization: `Archive ${token}` } }).catch(() => undefined); + }, [sourceId, token]); + const search = async (next: File, face = 0) => { setBusy(true); setError(null); diff --git a/docs/archive.md b/docs/archive.md index 817cdf8..93797ce 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -238,6 +238,8 @@ When `cloud_sources.photo_find_enabled` is on (default off; on for FPA) and the viewers with edit rights on at least one folder see "Procurar por foto": they upload a portrait (read in memory, never kept) and the archive returns matching photos in the folders they may see (`POST /v1/archive/:source/find`). Same gate as face review — Federação, Ana Teixeira, etc., not read-only viewers and not the public "Encontra-te". +Groups are ranked with pgvector HNSW (`centroid_vec`); event ids of the viewer's scope are cached a few minutes. +`GET …/find/ready` starts the face engine before the first upload. ### Face review (viewers who edit on the cloud)