From 10004452b445fd25037f86efc08d047c46ab2c46 Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 17 Oct 2026 19:45:44 +0100 Subject: [PATCH] Folder search: read faces on this computer and remember them. The desktop app reads the folder locally and only asks the server for a name. A photo already read is not read again. While a folder is still read on the server, face processes keep being added until the CPU is full. --- apps/api/src/app.ts | 16 +- apps/api/src/faces/lookupRoutes.ts | 49 +- apps/api/src/faces/process.ts | 92 ++++ apps/api/src/lib/engines.ts | 5 +- apps/api/test/lookup.test.ts | 12 + apps/app/src/i18n.ts | 2 + apps/app/src/library/CardScan.test.tsx | 22 + apps/app/src/library/CardScan.tsx | 193 ++++++- apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.toml | 4 +- apps/desktop/src-tauri/build.rs | 5 + .../src-tauri/capabilities/default.json | 5 + .../autogenerated/card_ingest.toml | 11 + .../autogenerated/card_save_settings.toml | 11 + .../permissions/autogenerated/card_scan.toml | 11 + .../autogenerated/card_settings.toml | 11 + .../autogenerated/faces_cancel.toml | 11 + .../autogenerated/faces_local.toml | 11 + .../permissions/autogenerated/faces_read.toml | 11 + .../autogenerated/faces_remember.toml | 11 + .../permissions/autogenerated/faces_scan.toml | 11 + apps/desktop/src-tauri/src/faces.rs | 503 ++++++++++++++++++ apps/desktop/src-tauri/src/lib.rs | 7 + apps/desktop/src-tauri/src/ui.rs | 8 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- packages/sdk/src/client.ts | 7 +- packages/sdk/src/types.ts | 9 +- workers/faces/Cargo.toml | 4 + workers/faces/src/lib.rs | 152 ++++++ workers/faces/src/main.rs | 199 +------ 30 files changed, 1171 insertions(+), 226 deletions(-) create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/card_ingest.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/card_save_settings.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/card_scan.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/card_settings.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/faces_cancel.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/faces_local.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/faces_read.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/faces_remember.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/faces_scan.toml create mode 100644 apps/desktop/src-tauri/src/faces.rs create mode 100644 workers/faces/src/lib.rs diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 98f1930..3cedfee 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -31,9 +31,10 @@ import { DevelopService } from "./develop/service.js"; import { registerFaceRoutes } from "./faces/routes.js"; import { FaceLookup, IdleEngine } from "./faces/lookup.js"; import { registerLookupRoutes } from "./faces/lookupRoutes.js"; -import { type FaceEngine, FacePool, FaceProcess } from "./faces/process.js"; +import { type FaceEngine, FaceProcess, GrowingFacePool } from "./faces/process.js"; import { faceWorkerLive } from "./faces/heartbeat.js"; import { faceEnginePaths, jerseyModelDir, scanSlots } from "./lib/engines.js"; +import { modelsDir } from "./lib/models.js"; import { JerseyModel, JerseyPool } from "./jersey/model.js"; import type { JerseyReader } from "./faces/lookup.js"; import { registerJerseyRoutes } from "./jersey/routes.js"; @@ -160,11 +161,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give faceEngine ? () => faceEngine : facePaths && config.NODE_ENV !== "test" - ? () => { - // One process per core: the face engine handles a single photo at a time. - const engines = Array.from({ length: slots }, () => new FaceProcess({ bin: facePaths.bin, modelsDir: facePaths.modelsDir, embedder: config.FACES_EMBEDDER })); - return engines.length === 1 ? engines[0]! : new FacePool(engines); - } + ? () => new GrowingFacePool(() => new FaceProcess({ bin: facePaths.bin, modelsDir: facePaths.modelsDir, embedder: config.FACES_EMBEDDER }), slots) : null, ); app.addHook("onClose", async () => (faceEngine ? undefined : lookupEngine.close())); @@ -181,14 +178,15 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give return null; }); if (!first) return null; - if (slots === 1) return first; - const rest = await Promise.all(Array.from({ length: slots - 1 }, () => JerseyModel.load(dir).catch(() => null))); + const copies = Math.min(slots, 8); + if (copies === 1) return first; + const rest = await Promise.all(Array.from({ length: copies - 1 }, () => JerseyModel.load(dir).catch(() => null))); const models = [first, ...rest.filter((model): model is JerseyModel => !!model)]; return models.length === 1 ? models[0]! : new JerseyPool(models); })(); return jerseyOnce; }; - await registerLookupRoutes(app, { db, sessions, lookup, signer, jersey: jerseyOf }); + await registerLookupRoutes(app, { db, sessions, lookup, signer, jersey: jerseyOf, models: modelsDir(config.STORAGE_ROOT) }); await registerDeliveryRoutes(app, { db, sessions, secrets, delivery }); // Edits are stored and fanned out here; the worker replays and renders them. // Corrections to the autopilot's edits teach it (autopilot/learning.ts). diff --git a/apps/api/src/faces/lookupRoutes.ts b/apps/api/src/faces/lookupRoutes.ts index b2113ee..7587002 100644 --- a/apps/api/src/faces/lookupRoutes.ts +++ b/apps/api/src/faces/lookupRoutes.ts @@ -1,3 +1,6 @@ +import { createReadStream } from "node:fs"; +import { stat } from "node:fs/promises"; +import { join } from "node:path"; import type { FastifyInstance, FastifyRequest } from "fastify"; import { z } from "zod"; import { ROLE_RANK, requireAuth, requireMembership } from "../auth/guard.js"; @@ -41,9 +44,11 @@ export const facesOut = (faces: QueryFace[]) => faces.map((f) => ({ box: f.box, * Search the library by a photo: who is it (named people like that face) and every photo with that face, across * all events or one. Only with biometrics on for the organization; the photo is not kept. */ +const MODEL_FILES = ["face_detection_yunet_2023mar.onnx", "glintr100.onnx"] as const; + export async function registerLookupRoutes( app: FastifyInstance, - deps: { db: Db; sessions: SessionService; lookup: FaceLookup; signer: UrlSigner; jersey?: () => Promise }, + deps: { db: Db; sessions: SessionService; lookup: FaceLookup; signer: UrlSigner; jersey?: () => Promise; models?: string | null }, ) { const { db, lookup, signer } = deps; const authenticate = requireAuth(deps.sessions); @@ -150,4 +155,46 @@ export async function registerLookupRoutes( }), }; }); + + /** + * Names for faces already read on the photographer's computer. The photo stays there; only the embeddings + * (and nothing else) are compared, first with the game and then with everyone else. + */ + app.post("/v1/orgs/:orgId/faces/identify", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => { + const { orgId } = OrgParams.parse(req.params); + const body = z + .object({ + eventId: z.uuid().optional(), + model: z.string().min(1).max(64).default("auraface-v1"), + faces: z.array(z.object({ embedding: z.array(z.number().finite()).min(8).max(1024) })).max(32), + }) + .parse(req.body); + await requireMembership(db, req, orgId, "PHOTOGRAPHER"); + const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { biometricsEnabled: true } }); + if (!org.biometricsEnabled) throw conflict("biometrics_disabled"); + const ctx = body.eventId ? await numberContext(db, body.eventId) : null; + const ids = body.eventId ? await roster(body.eventId) : null; + const prefer = ids && ids.length ? ids : null; + const hits = await Promise.all(body.faces.map(async (f) => (await lookup.people(orgId, f.embedding, body.model, 1, prefer))[0] ?? null)); + const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map(); + return { + roster: ids ? ids.length : ids, + people: hits.map((hit) => (hit ? { id: hit.id, name: hit.name, club: hit.club, number: worn.get(hit.id) ?? hit.number, level: hit.level } : null)), + }; + }); + + /** The face models, so the desktop app can read a folder itself. Checked by hash when they are loaded. */ + app.get("/v1/orgs/:orgId/faces/models/:file", { preHandler: authenticate }, async (req, reply) => { + const { orgId } = OrgParams.parse(req.params); + const { file } = z.object({ file: z.enum(MODEL_FILES) }).parse(req.params); + await requireMembership(db, req, orgId, "PHOTOGRAPHER"); + const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { biometricsEnabled: true } }); + if (!org.biometricsEnabled) throw conflict("biometrics_disabled"); + const dir = deps.models; + if (!dir) throw new AppError(404, "models_missing"); + const path = join(dir, file); + const info = await stat(path).catch(() => null); + if (!info?.isFile()) throw new AppError(404, "models_missing"); + return reply.header("content-type", "application/octet-stream").header("content-length", String(info.size)).header("cache-control", "private, max-age=86400").send(createReadStream(path)); + }); } diff --git a/apps/api/src/faces/process.ts b/apps/api/src/faces/process.ts index c23c640..d1280f5 100644 --- a/apps/api/src/faces/process.ts +++ b/apps/api/src/faces/process.ts @@ -1,5 +1,25 @@ +import { cpus } from "node:os"; import { LeastBusy, LineProcess } from "../lib/line-process.js"; +/** Stop adding face processes once the machine is this full. */ +const CPU_TARGET = 0.97; + +interface CpuTimes { + idle: number; + total: number; +} + +function cpuTimes(): CpuTimes { + let idle = 0; + let total = 0; + for (const cpu of cpus()) { + const t = cpu.times; + idle += t.idle; + total += t.user + t.nice + t.sys + t.idle + t.irq; + } + return { idle, total }; +} + export interface DetectedFace { x0: number; y0: number; @@ -73,3 +93,75 @@ export class FacePool implements FaceEngine { await Promise.all(this.engines.map((e) => e.close())); } } + +/** + * Face processes that start a few at a time and keep being added while the CPU is under {@link CPU_TARGET}. + * Each process is one core. `cap` is the most this machine should run. + */ +export class GrowingFacePool implements FaceEngine { + readonly model: string; + private readonly engines: FaceEngine[] = []; + private readonly busy: number[] = []; + private last: CpuTimes = cpuTimes(); + private lastGrow = 0; + + constructor( + private readonly make: () => FaceEngine, + private readonly cap: number, + ) { + const first = make(); + this.model = first.model; + this.engines.push(first); + this.busy.push(0); + this.add(Math.min(3, Math.max(0, cap - 1))); + } + + get size(): number { + return this.engines.length; + } + + private add(count: number): void { + const room = Math.max(0, this.cap - this.engines.length); + const n = Math.min(count, room); + for (let i = 0; i < n; i++) { + this.engines.push(this.make()); + this.busy.push(0); + } + } + + /** Add more processes when every current one is busy and the CPU is not full yet. */ + private grow(): void { + if (this.engines.length >= this.cap) return; + const now = Date.now(); + if (now - this.lastGrow < 1500) return; + const allBusy = this.busy.every((n) => n > 0); + if (!allBusy && this.engines.length >= 4) return; + const sample = cpuTimes(); + const idle = sample.idle - this.last.idle; + const total = sample.total - this.last.total; + this.last = sample; + const used = total > 0 ? 1 - idle / total : 0; + if (used >= CPU_TARGET) return; + const step = Math.max(2, Math.floor(this.engines.length / 2)); + this.add(step); + this.lastGrow = now; + } + + async analyse(path: string): Promise { + this.grow(); + let index = 0; + for (let i = 1; i < this.busy.length; i++) { + if (this.busy[i]! < this.busy[index]!) index = i; + } + this.busy[index]!++; + try { + return await this.engines[index]!.analyse(path); + } finally { + this.busy[index]!--; + } + } + + async close(): Promise { + await Promise.all(this.engines.map((e) => e.close())); + } +} diff --git a/apps/api/src/lib/engines.ts b/apps/api/src/lib/engines.ts index 3202fd7..5d42779 100644 --- a/apps/api/src/lib/engines.ts +++ b/apps/api/src/lib/engines.ts @@ -12,9 +12,8 @@ export function scanSlots(machine: { cpus: number; memoryBytes: number } = { cpu const cpus = Math.max(1, machine.cpus); const spareGb = Math.max(1, machine.memoryBytes / 1e9 - 6); const byMemory = Math.max(1, Math.floor(spareGb / 0.6)); - let leave = 0; - if (cpus >= 16) leave = 8; - else if (cpus >= 8) leave = 2; + // One core stays for the window and the API. The pool grows up to this until the machine is full. + const leave = cpus > 2 ? 1 : 0; return Math.max(1, Math.min(cpus - leave, byMemory)); } diff --git a/apps/api/test/lookup.test.ts b/apps/api/test/lookup.test.ts index 746f41e..a2bc71d 100644 --- a/apps/api/test/lookup.test.ts +++ b/apps/api/test/lookup.test.ts @@ -209,6 +209,18 @@ describe("search by photo", () => { expect(res.json()).toMatchObject({ faces: [{ person: { id: outsider.id, name: "Só lá fora" } }] }); }); + it("names an embedding read on the photographer's computer, without the photo", async () => { + const { orgId, token, rui } = await setup(); + const res = await app.inject({ + method: "POST", + url: `/v1/orgs/${orgId}/faces/identify`, + headers: { ...bearer(token), "content-type": "application/json" }, + payload: { faces: [{ embedding: face(1) }, { embedding: face(9) }] }, + }); + expect(res.statusCode).toBe(200); + expect(res.json()).toMatchObject({ roster: null, people: [{ id: rui.id, name: "Rui Silva" }, null] }); + }); + it("finds a visitor's face in a public gallery's photos only", async () => { const { orgId, token, photos } = await setup(); expect((await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/sites`, headers: bearer(token), payload: { domain: "fotos.test", skin: "photoreport", name: "PhotoReport" } })).statusCode).toBe(201); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 71bbd0f..2346339 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -620,6 +620,8 @@ export const t = { button: "Procurar numa pasta", title: "Procurar numa pasta", help: "Escolhe uma pasta. As fotos ficam onde estão. Só entram no jogo as que selecionares.", + local: "A ler neste computador. As fotos não são enviadas. O que já foi lido fica guardado.", + preparing: "A preparar o reconhecimento neste computador. Da primeira vez demora um pouco.", game: "Jogo", roster: (n: number) => n === 1 diff --git a/apps/app/src/library/CardScan.test.tsx b/apps/app/src/library/CardScan.test.tsx index 83d614f..7b0b103 100644 --- a/apps/app/src/library/CardScan.test.tsx +++ b/apps/app/src/library/CardScan.test.tsx @@ -85,4 +85,26 @@ describe("card folder dialog", () => { expect(onImport.mock.calls[0]![1]).toBe("game"); expect(screen.getByText("1 foto a entrar no jogo.")).toBeTruthy(); }); + + it("does not send a photo again when the same file was already read", async () => { + vi.stubGlobal("createImageBitmap", async () => ({ width: 800, height: 600, close() {} })); + vi.spyOn(URL, "createObjectURL").mockImplementation(() => "blob:again"); + vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}); + HTMLCanvasElement.prototype.getContext = (() => ({ drawImage() {} })) as unknown as typeof HTMLCanvasElement.prototype.getContext; + HTMLCanvasElement.prototype.toBlob = function (cb) { + cb(new Blob([new Uint8Array([1])], { type: "image/jpeg" })); + }; + const scanCard = vi.fn().mockResolvedValue({ slots: 4, roster: null, faces: [face({ name: "Rui" })] }); + const file = new File(["same"], "again.jpg", { type: "image/jpeg" }); + const { container } = render( + {}} onClose={() => {}} />, + ); + const picker = container.querySelector("input[type=file]") as HTMLInputElement; + fireEvent.change(picker, { target: { files: [file] } }); + expect(await screen.findByRole("button", { name: /Rui/ })).toBeTruthy(); + expect(scanCard).toHaveBeenCalledTimes(1); + fireEvent.change(picker, { target: { files: [file] } }); + expect(await screen.findByRole("button", { name: /Rui/ })).toBeTruthy(); + expect(scanCard).toHaveBeenCalledTimes(1); + }); }); diff --git a/apps/app/src/library/CardScan.tsx b/apps/app/src/library/CardScan.tsx index e5dd0fa..5fbe157 100644 --- a/apps/app/src/library/CardScan.tsx +++ b/apps/app/src/library/CardScan.tsx @@ -2,19 +2,51 @@ import type { ApiClient, CardScan as CardReading, EventSummary } from "@photorep import { ApiError } from "@photoreport/sdk"; import { useEffect, useMemo, useRef, useState } from "react"; import { t } from "../i18n.js"; +import { kv } from "../offline/kv.js"; +import { asArrayBuffer, desktopInvoke, isDesktop } from "../platform.js"; type Face = CardReading["faces"][number]; interface Item { - file: File; + file: File | null; + /** Set when the desktop app read the photo itself. */ + path: string; + name: string; thumb: string; faces: Face[] | null; error: boolean; } +interface CachedScan { + roster: number | null; + faces: Face[]; +} + +interface LocalFace extends Face { + embedding?: number[]; +} + +interface LocalPhoto { + done: number; + total: number; + path: string; + name: string; + cached: boolean; + needsName: boolean; + error: boolean; + roster: number | null; + thumb: string; + faces: LocalFace[]; +} + const JPEG = /\.jpe?g$/i; const fold = (s: string) => s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase(); +function cacheKey(orgId: string, eventId: string, file: File): string { + const rel = "webkitRelativePath" in file && typeof file.webkitRelativePath === "string" && file.webkitRelativePath ? file.webkitRelativePath : file.name; + return `card-scan:${orgId}:${eventId}:${rel}:${file.size}:${file.lastModified}`; +} + /** A photo matches when every word is in a face: a number must be that shirt or that player's number. */ export function cardMatches(faces: Face[], query: string): boolean { if (!faces.length) return false; @@ -95,6 +127,8 @@ export function CardScan({ const [sent, setSent] = useState(null); const [gameId, setGameId] = useState(eventId); const [roster, setRoster] = useState(undefined); + const [localMode, setLocalMode] = useState(false); + const folderRef = useRef(""); const gameRef = useRef(gameId); gameRef.current = gameId; const choices = useMemo(() => [...games].sort((a, b) => b.startsAt.localeCompare(a.startsAt)), [games]); @@ -112,7 +146,7 @@ export function CardScan({ useEffect(() => { return () => { stop.current = true; - for (const item of live.current) if (item.thumb) URL.revokeObjectURL(item.thumb); + for (const item of live.current) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb); }; }, []); @@ -130,16 +164,16 @@ export function CardScan({ if (!files.length) { setRunning(false); setItems((prev) => { - for (const item of prev) if (item.thumb) URL.revokeObjectURL(item.thumb); + for (const item of prev) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb); return []; }); setNote(t.cardScan.jpeg); return; } setRunning(true); - const next: Item[] = files.map((file) => ({ file, thumb: "", faces: null, error: false })); + const next: Item[] = files.map((file) => ({ file, path: "", name: file.name, thumb: "", faces: null, error: false })); setItems((prev) => { - for (const item of prev) if (item.thumb) URL.revokeObjectURL(item.thumb); + for (const item of prev) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb); return next; }); // A handful at first; the server says how many it can read at once, and the rest start then. @@ -150,15 +184,25 @@ export function CardScan({ const launch = () => { while (!stop.current && running < width && cursor < next.length) { const item = next[cursor++]!; + const file = item.file; + if (!file) continue; running++; void (async () => { try { - const small = await previewOf(item.file); - const read = await api.scanCard(orgId, small, gameRef.current); - item.faces = read.faces; - setRoster(read.roster); - if (read.slots > width) width = read.slots; - if (read.faces.length) item.thumb = URL.createObjectURL(small); + const saved = await kv.get(cacheKey(orgId, gameRef.current, file)); + if (saved) { + item.faces = saved.faces; + setRoster(saved.roster); + if (saved.faces.length) item.thumb = URL.createObjectURL(await previewOf(file)); + } else { + const small = await previewOf(file); + const read = await api.scanCard(orgId, small, gameRef.current); + item.faces = read.faces; + setRoster(read.roster); + if (read.slots > width) width = read.slots; + if (read.faces.length) item.thumb = URL.createObjectURL(small); + await kv.set(cacheKey(orgId, gameRef.current, file), { roster: read.roster, faces: read.faces }); + } } catch (err) { item.error = true; item.faces = []; @@ -183,6 +227,102 @@ export function CardScan({ if (next.some((item) => item.error) && !stop.current) setNote(t.cardScan.failed); }; + const runLocal = async (folder: string) => { + stop.current = false; + folderRef.current = folder; + setLocalMode(true); + setNote(t.cardScan.preparing); + setSent(null); + setSelected(new Set()); + setDone(0); + setTotal(0); + setRunning(true); + const next: Item[] = []; + const byPath = new Map(); + setItems((prev) => { + for (const item of prev) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb); + return []; + }); + const pending: { item: Item; embeddings: number[][] }[] = []; + let naming = Promise.resolve(); + const nameBatch = async (batch: { item: Item; embeddings: number[][] }[]) => { + if (!batch.length) return; + const named = await api.identifyFaces(orgId, { eventId: gameRef.current, faces: batch.flatMap((row) => row.embeddings.map((embedding) => ({ embedding }))) }); + setRoster(named.roster); + let at = 0; + for (const row of batch) { + const people = named.people.slice(at, at + row.embeddings.length); + at += row.embeddings.length; + row.item.faces = (row.item.faces ?? []).map((face, i) => ({ ...face, person: people[i] ?? null })); + void desktopInvoke("faces_remember", { + folder, + path: row.item.path, + orgId, + eventId: gameRef.current, + roster: named.roster, + faces: row.item.faces, + }).catch(() => {}); + } + setItems(next.slice()); + }; + const schedule = () => { + if (pending.length < 16) return; + const batch = pending.splice(0, 24); + naming = naming.then(() => nameBatch(batch)).catch(() => {}); + }; + let unlisten = () => {}; + try { + const { listen } = await import("@tauri-apps/api/event"); + unlisten = await listen("faces-photo", (e) => { + const ev = e.payload; + if (stop.current) return; + setTotal(ev.total); + setDone(ev.done); + setNote(null); + let item = byPath.get(ev.path); + if (!item) { + item = { file: null, path: ev.path, name: ev.name, thumb: "", faces: null, error: false }; + byPath.set(ev.path, item); + next.push(item); + } + item.error = ev.error; + if (ev.thumb) item.thumb = `data:image/jpeg;base64,${ev.thumb}`; + if (ev.roster != null) setRoster(ev.roster); + item.faces = ev.faces.map((face) => ({ box: face.box, number: face.number, person: face.person })); + if (ev.needsName && !ev.error) { + const embeddings = ev.faces.flatMap((face) => (face.embedding && face.embedding.length ? [face.embedding] : [])); + if (embeddings.length && item.faces) pending.push({ item, embeddings }); + schedule(); + } + setItems(next.slice()); + }); + const token = await api.realtimeToken(); + await desktopInvoke("faces_scan", { folder, orgId, eventId: gameRef.current, api: api.baseUrl, token }); + if (pending.length) { + const batch = pending.splice(0, pending.length); + naming = naming.then(() => nameBatch(batch)).catch(() => {}); + } + await naming; + } catch (err) { + setNote(err instanceof ApiError ? (t.lookup.errors[err.code] ?? t.unexpectedError) : t.cardScan.failed); + } finally { + unlisten(); + setRunning(false); + } + }; + + const pick = async () => { + if (isDesktop()) { + const local = await desktopInvoke("faces_local").then((ok) => ok).catch(() => false); + if (local) { + const folder = await desktopInvoke("delivery_folder_pick").catch(() => null); + if (folder) await runLocal(folder); + return; + } + } + input.current?.click(); + }; + const toggle = (index: number) => { setSelected((cur) => { const n = new Set(cur); @@ -219,7 +359,7 @@ export function CardScan({ aria-label={t.cardScan.search} className="h-7 min-w-[220px] flex-1 border border-black bg-cell px-2 text-[13px] text-ink" /> - { stop.current = true; + if (localMode) void desktopInvoke("faces_cancel").catch(() => {}); }} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on" > @@ -253,7 +394,7 @@ export function CardScan({

- {t.cardScan.help} {t.cardScan.jpeg} + {localMode ? t.cardScan.local : t.cardScan.help} {t.cardScan.jpeg} {roster === null && {t.cardScan.rosterOpen}} {roster === 0 && {t.cardScan.rosterNone}} {typeof roster === "number" && roster > 0 && {t.cardScan.roster(roster)}} @@ -266,14 +407,14 @@ export function CardScan({

{shown.map(({ item, index }) => ( ))}
@@ -294,10 +435,24 @@ export function CardScan({ type="button" disabled={selected.size === 0} onClick={() => { - const files = [...selected].flatMap((index) => (items[index] ? [items[index].file] : [])); - onImport(files, gameId); - setSent(t.cardScan.sent(files.length)); - setSelected(new Set()); + void (async () => { + const files: File[] = []; + for (const index of selected) { + const item = items[index]; + if (!item) continue; + if (item.file) { + files.push(item.file); + continue; + } + if (!item.path) continue; + const data = asArrayBuffer(await desktopInvoke("faces_read", { path: item.path })); + files.push(new File([data], item.name, { type: "image/jpeg" })); + } + if (!files.length) return; + onImport(files, gameId); + setSent(t.cardScan.sent(files.length)); + setSelected(new Set()); + })(); }} className="h-8 bg-accent px-3 text-[13px] text-white disabled:opacity-40" > diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 204758c..4efd03d 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@photoreport/desktop", - "version": "0.3.12", + "version": "0.3.13", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 2b8386a..fa95255 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photoreport-desktop" -version = "0.3.12" +version = "0.3.13" edition = "2024" publish = false description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine." @@ -28,7 +28,9 @@ tokio = { version = "1", features = ["sync", "time", "fs", "net", "io-util"] } unftp-core = "0.1.0" serde_json = "1" sha2 = "0.10" +libc = "0.2" image = { version = "0.25", default-features = false, features = ["jpeg"] } +photoreport-faces = { path = "../../../workers/faces" } tauri-plugin-dialog = "2" tauri-plugin-updater = "2" # New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates. diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs index 46eeb13..9788b5b 100644 --- a/apps/desktop/src-tauri/build.rs +++ b/apps/desktop/src-tauri/build.rs @@ -30,6 +30,11 @@ fn main() { "card_ingest", "card_settings", "card_save_settings", + "faces_local", + "faces_scan", + "faces_cancel", + "faces_remember", + "faces_read", "update_check", "update_install", "ui_status", diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index 90f5d3e..e97f04a 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -45,6 +45,11 @@ "allow-card-ingest", "allow-card-settings", "allow-card-save-settings", + "allow-faces-local", + "allow-faces-scan", + "allow-faces-cancel", + "allow-faces-remember", + "allow-faces-read", "allow-update-check", "allow-update-install", "allow-ui-status", diff --git a/apps/desktop/src-tauri/permissions/autogenerated/card_ingest.toml b/apps/desktop/src-tauri/permissions/autogenerated/card_ingest.toml new file mode 100644 index 0000000..9969bfb --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/card_ingest.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-card-ingest" +description = "Enables the card_ingest command without any pre-configured scope." +commands.allow = ["card_ingest"] + +[[permission]] +identifier = "deny-card-ingest" +description = "Denies the card_ingest command without any pre-configured scope." +commands.deny = ["card_ingest"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/card_save_settings.toml b/apps/desktop/src-tauri/permissions/autogenerated/card_save_settings.toml new file mode 100644 index 0000000..1e36022 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/card_save_settings.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-card-save-settings" +description = "Enables the card_save_settings command without any pre-configured scope." +commands.allow = ["card_save_settings"] + +[[permission]] +identifier = "deny-card-save-settings" +description = "Denies the card_save_settings command without any pre-configured scope." +commands.deny = ["card_save_settings"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/card_scan.toml b/apps/desktop/src-tauri/permissions/autogenerated/card_scan.toml new file mode 100644 index 0000000..59d780c --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/card_scan.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-card-scan" +description = "Enables the card_scan command without any pre-configured scope." +commands.allow = ["card_scan"] + +[[permission]] +identifier = "deny-card-scan" +description = "Denies the card_scan command without any pre-configured scope." +commands.deny = ["card_scan"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/card_settings.toml b/apps/desktop/src-tauri/permissions/autogenerated/card_settings.toml new file mode 100644 index 0000000..e328251 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/card_settings.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-card-settings" +description = "Enables the card_settings command without any pre-configured scope." +commands.allow = ["card_settings"] + +[[permission]] +identifier = "deny-card-settings" +description = "Denies the card_settings command without any pre-configured scope." +commands.deny = ["card_settings"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/faces_cancel.toml b/apps/desktop/src-tauri/permissions/autogenerated/faces_cancel.toml new file mode 100644 index 0000000..caad750 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/faces_cancel.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-faces-cancel" +description = "Enables the faces_cancel command without any pre-configured scope." +commands.allow = ["faces_cancel"] + +[[permission]] +identifier = "deny-faces-cancel" +description = "Denies the faces_cancel command without any pre-configured scope." +commands.deny = ["faces_cancel"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/faces_local.toml b/apps/desktop/src-tauri/permissions/autogenerated/faces_local.toml new file mode 100644 index 0000000..d00f762 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/faces_local.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-faces-local" +description = "Enables the faces_local command without any pre-configured scope." +commands.allow = ["faces_local"] + +[[permission]] +identifier = "deny-faces-local" +description = "Denies the faces_local command without any pre-configured scope." +commands.deny = ["faces_local"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/faces_read.toml b/apps/desktop/src-tauri/permissions/autogenerated/faces_read.toml new file mode 100644 index 0000000..5179bf2 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/faces_read.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-faces-read" +description = "Enables the faces_read command without any pre-configured scope." +commands.allow = ["faces_read"] + +[[permission]] +identifier = "deny-faces-read" +description = "Denies the faces_read command without any pre-configured scope." +commands.deny = ["faces_read"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/faces_remember.toml b/apps/desktop/src-tauri/permissions/autogenerated/faces_remember.toml new file mode 100644 index 0000000..b984194 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/faces_remember.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-faces-remember" +description = "Enables the faces_remember command without any pre-configured scope." +commands.allow = ["faces_remember"] + +[[permission]] +identifier = "deny-faces-remember" +description = "Denies the faces_remember command without any pre-configured scope." +commands.deny = ["faces_remember"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/faces_scan.toml b/apps/desktop/src-tauri/permissions/autogenerated/faces_scan.toml new file mode 100644 index 0000000..f604ffd --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/faces_scan.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-faces-scan" +description = "Enables the faces_scan command without any pre-configured scope." +commands.allow = ["faces_scan"] + +[[permission]] +identifier = "deny-faces-scan" +description = "Denies the faces_scan command without any pre-configured scope." +commands.deny = ["faces_scan"] diff --git a/apps/desktop/src-tauri/src/faces.rs b/apps/desktop/src-tauri/src/faces.rs new file mode 100644 index 0000000..8d8bd64 --- /dev/null +++ b/apps/desktop/src-tauri/src/faces.rs @@ -0,0 +1,503 @@ +//! Read a folder for faces on this computer. Photos are not uploaded: the engine runs here, one copy per +//! core, and only a face that is not already named is sent to the server as its embedding. +//! +//! Results stay on disk (the face, and the name for this game) so opening the same folder again does not +//! read the photos a second time. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tauri::{AppHandle, Emitter}; + +use photoreport_faces::{Engine, FoundFace}; + +const CPU_TARGET: f64 = 0.97; +const MODEL_FILES: [&str; 2] = ["face_detection_yunet_2023mar.onnx", "glintr100.onnx"]; + +pub struct FaceScan { + cancel: Arc, +} + +impl Default for FaceScan { + fn default() -> Self { + Self { cancel: Arc::new(AtomicBool::new(false)) } + } +} + +#[derive(Clone, Serialize, Deserialize)] +pub struct Rect { + x0: f32, + y0: f32, + x1: f32, + y1: f32, +} + +#[derive(Clone, Serialize, Deserialize)] +pub struct Person { + id: String, + name: String, + club: Option, + number: Option, + level: String, +} + +/// One face as the folder search shows it. `embedding` is present only until the server has named it. +#[derive(Clone, Serialize, Deserialize)] +pub struct ScanFace { + #[serde(rename = "box")] + rect: Rect, + number: Option, + person: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + embedding: Option>, +} + +#[derive(Serialize, Deserialize)] +struct EngineCache { + faces: Vec, +} + +#[derive(Serialize, Deserialize)] +struct NamedCache { + roster: Option, + faces: Vec, +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct Progress { + done: usize, + total: usize, + path: String, + name: String, + cached: bool, + needs_name: bool, + error: bool, + roster: Option, + /// Small JPEG, base64, so the grid can show the photo without reading it again in the page. + thumb: String, + faces: Vec, +} + +struct Job { + path: PathBuf, + key: String, +} + +fn cache_root() -> PathBuf { + dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join("pt.photoreport.desktop").join("face-scan") +} + +fn models_dir() -> PathBuf { + cache_root().join("models") +} + +fn file_key(root: &Path, path: &Path) -> String { + let rel = path.strip_prefix(root).unwrap_or(path); + let meta = std::fs::metadata(path).ok(); + let len = meta.as_ref().map(|m| m.len()).unwrap_or(0); + let modified = meta.and_then(|m| m.modified().ok()).unwrap_or(UNIX_EPOCH); + let secs = modified.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let raw = format!("{}\0{len}\0{secs}", rel.to_string_lossy()); + Sha256::digest(raw.as_bytes()).iter().map(|b| format!("{b:02x}")).collect() +} + +fn engine_file(key: &str) -> PathBuf { + cache_root().join("engine").join(format!("{key}.json")) +} + +fn thumb_file(key: &str) -> PathBuf { + cache_root().join("engine").join(format!("{key}.jpg")) +} + +fn named_file(org_id: &str, event_id: &str, key: &str) -> PathBuf { + cache_root().join("names").join(org_id).join(event_id).join(format!("{key}.json")) +} + +fn read_json Deserialize<'a>>(path: &Path) -> Option { + serde_json::from_slice(&std::fs::read(path).ok()?).ok() +} + +fn write_json(path: &Path, value: &impl Serialize) -> Result<(), String> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let bytes = serde_json::to_vec(value).map_err(|e| e.to_string())?; + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, &bytes).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, path).map_err(|e| e.to_string()) +} + +/// Faces worth naming: large enough, in focus, with an embedding. Same rule as the server. +fn worth_naming(faces: &[FoundFace]) -> Vec<&FoundFace> { + const MIN_SIDE: f32 = 0.012; + const MIN_SHARP: f32 = 45.0; + const RELATIVE: f32 = 0.25; + let big: Vec<&FoundFace> = faces.iter().filter(|f| (f.x1 - f.x0).max(f.y1 - f.y0) >= MIN_SIDE).collect(); + let sharpest = big.iter().filter_map(|f| f.sharpness).fold(0.0_f32, f32::max); + big.into_iter() + .filter(|f| match f.sharpness { + None => true, + Some(s) => s >= MIN_SHARP && s >= RELATIVE * sharpest, + }) + .filter(|f| f.embedding.as_ref().is_some_and(|e| !e.is_empty())) + .collect() +} + +fn to_scan(face: &FoundFace, with_embedding: bool) -> ScanFace { + ScanFace { + rect: Rect { x0: face.x0, y0: face.y0, x1: face.x1, y1: face.y1 }, + number: None, + person: None, + embedding: if with_embedding { face.embedding.clone() } else { None }, + } +} + +fn b64(data: &[u8]) -> String { + const TABLE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + let mut i = 0; + while i < data.len() { + let b0 = u32::from(data[i]); + let b1 = data.get(i + 1).copied().map(u32::from); + let b2 = data.get(i + 2).copied().map(u32::from); + let n = (b0 << 16) | (b1.unwrap_or(0) << 8) | b2.unwrap_or(0); + out.push(TABLE[((n >> 18) & 63) as usize] as char); + out.push(TABLE[((n >> 12) & 63) as usize] as char); + out.push(if b1.is_some() { TABLE[((n >> 6) & 63) as usize] as char } else { '=' }); + out.push(if b2.is_some() { TABLE[(n & 63) as usize] as char } else { '=' }); + i += 3; + } + out +} + +fn thumb_jpeg(path: &Path) -> Vec { + let Ok(reader) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) else { return Vec::new() }; + let Ok(img) = reader.decode() else { return Vec::new() }; + let small = img.thumbnail(480, 480); + let mut bytes = Vec::new(); + if small.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Jpeg).is_err() { + return Vec::new(); + } + bytes +} + +fn jpeg_paths(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name.starts_with('.') { + continue; + } + if path.is_dir() { + jpeg_paths(&path, out); + } else if name.to_ascii_lowercase().ends_with(".jpg") || name.to_ascii_lowercase().ends_with(".jpeg") { + out.push(path); + } + } +} + +fn memory_gb() -> f64 { + let pages = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) }; + let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + if pages <= 0 || size <= 0 { + return 8.0; + } + (pages as f64) * (size as f64) / 1e9 +} + +/// One engine per core, and only as many as memory can hold (each copy of the model is large). +fn engine_cap() -> usize { + let cpus = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2); + let by_mem = ((memory_gb() - 2.0) / 0.7).floor().max(1.0) as usize; + cpus.max(1).min(by_mem.max(1)) +} + +#[cfg(target_os = "macos")] +fn cpu_ticks() -> Option<(u64, u64)> { + #[repr(C)] + struct Load { + ticks: [u32; 4], + } + unsafe extern "C" { + fn mach_host_self() -> u32; + fn host_statistics(host: u32, flavor: i32, info: *mut u32, count: *mut u32) -> i32; + } + let mut info = Load { ticks: [0; 4] }; + let mut count = 4u32; + let rc = unsafe { host_statistics(mach_host_self(), 3, (&mut info as *mut Load).cast(), &mut count) }; + if rc != 0 { + return None; + } + let idle = u64::from(info.ticks[2]); + let total = info.ticks.iter().map(|t| u64::from(*t)).sum(); + Some((idle, total)) +} + +#[cfg(target_os = "linux")] +fn cpu_ticks() -> Option<(u64, u64)> { + let text = std::fs::read_to_string("/proc/stat").ok()?; + let line = text.lines().next()?; + let mut idle = 0u64; + let mut total = 0u64; + for (i, part) in line.split_whitespace().skip(1).enumerate() { + let n = part.parse::().unwrap_or(0); + total += n; + if i == 3 { + idle = n; + } + } + if total == 0 { None } else { Some((idle, total)) } +} + +#[cfg(not(any(target_os = "macos", target_os = "linux")))] +fn cpu_ticks() -> Option<(u64, u64)> { + None +} + +fn cpu_used(prev: &mut Option<(u64, u64)>) -> Option { + let now = cpu_ticks()?; + let used = prev.and_then(|(idle, total)| { + let idle_d = now.0.saturating_sub(idle); + let total_d = now.1.saturating_sub(total); + if total_d == 0 { None } else { Some(1.0 - (idle_d as f64) / (total_d as f64)) } + }); + *prev = Some(now); + used +} + +fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cached: bool, needs_name: bool, error: bool, roster: Option, thumb: &[u8], faces: Vec) { + let n = done.fetch_add(1, Ordering::Relaxed) + 1; + let name = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + let _ = app.emit( + "faces-photo", + Progress { + done: n, + total, + path: path.to_string_lossy().to_string(), + name, + cached, + needs_name, + error, + roster, + thumb: if thumb.is_empty() { String::new() } else { b64(thumb) }, + faces, + }, + ); +} + +async fn ensure_models(api: &str, token: &str, org_id: &str) -> Result { + let dir = models_dir(); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + if MODEL_FILES.iter().all(|name| dir.join(name).is_file()) { + return Ok(dir); + } + let http = crate::ui::http_client(600)?; + for name in MODEL_FILES { + let dest = dir.join(name); + if dest.is_file() { + continue; + } + let url = format!("{}/v1/orgs/{org_id}/faces/models/{name}", api.trim_end_matches('/')); + let res = http.get(url).bearer_auth(token).send().await.map_err(|e| e.to_string())?; + if !res.status().is_success() { + return Err(format!("models_{}", res.status().as_u16())); + } + let bytes = res.bytes().await.map_err(|e| e.to_string())?; + let tmp = dest.with_extension("part"); + std::fs::write(&tmp, &bytes).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &dest).map_err(|e| e.to_string())?; + } + Ok(dir) +} + +fn run_jobs(dir: PathBuf, jobs: Arc>>, cancel: Arc, app: AppHandle, done: Arc, total: usize) { + let engine = match Engine::load(&dir, "auraface", 0.6) { + Ok(engine) => engine, + Err(err) => { + eprintln!("faces: {err}"); + return; + } + }; + loop { + if cancel.load(Ordering::Relaxed) { + return; + } + let job = jobs.lock().ok().and_then(|mut q| q.pop()); + let Some(job) = job else { return }; + if let Some(cached) = read_json::(&engine_file(&job.key)) { + let faces = worth_naming(&cached.faces).into_iter().map(|f| to_scan(f, true)).collect(); + let thumb = std::fs::read(thumb_file(&job.key)).unwrap_or_default(); + emit_one(&app, &done, total, &job.path, true, true, false, None, &thumb, faces); + continue; + } + match engine.analyse(&job.path) { + Ok(read) => { + let _ = write_json(&engine_file(&job.key), &EngineCache { faces: read.faces.clone() }); + let thumb = thumb_jpeg(&job.path); + if !thumb.is_empty() { + let _ = std::fs::write(thumb_file(&job.key), &thumb); + } + let faces = worth_naming(&read.faces).into_iter().map(|f| to_scan(f, true)).collect(); + emit_one(&app, &done, total, &job.path, false, true, false, None, &thumb, faces); + } + Err(_) => emit_one(&app, &done, total, &job.path, false, false, true, None, &[], Vec::new()), + } + } +} + +fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String, models: PathBuf, cancel: Arc) -> Result<(), String> { + let root = PathBuf::from(&folder); + if !root.is_dir() { + return Err("not_a_folder".into()); + } + let mut files = Vec::new(); + jpeg_paths(&root, &mut files); + let total = files.len(); + let done = Arc::new(AtomicUsize::new(0)); + let mut pending = Vec::new(); + for path in files { + let key = file_key(&root, &path); + if let Some(named) = read_json::(&named_file(&org_id, &event_id, &key)) { + let thumb = std::fs::read(thumb_file(&key)).unwrap_or_default(); + emit_one(&app, &done, total, &path, true, false, false, named.roster, &thumb, named.faces); + continue; + } + pending.push(Job { path, key }); + } + if pending.is_empty() || cancel.load(Ordering::Relaxed) { + return Ok(()); + } + let jobs = Arc::new(Mutex::new(pending)); + let cap = engine_cap(); + let mut handles: Vec> = Vec::new(); + let mut sample = None; + let _ = cpu_used(&mut sample); + while !cancel.load(Ordering::Relaxed) { + let left = jobs.lock().map(|q| q.len()).unwrap_or(0); + let alive = handles.iter().filter(|h| !h.is_finished()).count(); + if left == 0 && alive == 0 { + break; + } + if alive == 0 && !handles.is_empty() && left > 0 { + let rest = jobs.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default(); + for job in rest { + emit_one(&app, &done, total, &job.path, false, false, true, None, &[], Vec::new()); + } + break; + } + if left > 0 && handles.len() < cap { + let used = cpu_used(&mut sample).unwrap_or(0.0); + let busy = handles.is_empty() || used < CPU_TARGET; + if busy { + let batch = if handles.is_empty() { 2.min(cap) } else { 2.min(cap - handles.len()) }; + for _ in 0..batch { + let jobs = jobs.clone(); + let cancel = cancel.clone(); + let app = app.clone(); + let done = done.clone(); + let dir = models.clone(); + handles.push(std::thread::spawn(move || run_jobs(dir, jobs, cancel, app, done, total))); + } + } + } + std::thread::sleep(Duration::from_millis(700)); + } + for handle in handles { + let _ = handle.join(); + } + Ok(()) +} + +/// True when this desktop build can read a folder itself. Older builds do not have the command. +#[tauri::command] +pub fn faces_local() -> bool { + true +} + +#[tauri::command] +pub fn faces_cancel(state: tauri::State<'_, FaceScan>) { + state.cancel.store(true, Ordering::Relaxed); +} + +/// Reads every JPEG under `folder` on this computer. Emits `faces-photo` as each one finishes. +/// A photo already named for this game is not read again. The models are downloaded once. +#[tauri::command] +pub async fn faces_scan(app: AppHandle, state: tauri::State<'_, FaceScan>, folder: String, org_id: String, event_id: String, api: String, token: String) -> Result<(), String> { + state.cancel.store(false, Ordering::Relaxed); + let cancel = state.cancel.clone(); + let models = ensure_models(&api, &token, &org_id).await?; + let cancel2 = cancel.clone(); + tauri::async_runtime::spawn_blocking(move || scan_folder(app, folder, org_id, event_id, models, cancel2)) + .await + .map_err(|e| e.to_string())? +} + +/// Remembers the names for one photo of this game, so the next search of the same file skips the server too. +#[tauri::command] +pub fn faces_remember(folder: String, path: String, org_id: String, event_id: String, roster: Option, faces: Vec) -> Result<(), String> { + let root = PathBuf::from(&folder); + let file = PathBuf::from(&path); + let key = file_key(&root, &file); + let faces = faces + .into_iter() + .map(|mut face| { + face.embedding = None; + face + }) + .collect(); + write_json(&named_file(&org_id, &event_id, &key), &NamedCache { roster, faces }) +} + +/// The original JPEG, for importing the photos the photographer picked. Only a JPEG, and only after a scan. +#[tauri::command] +pub fn faces_read(path: String) -> Result { + let file = PathBuf::from(&path); + let name = file.file_name().map(|s| s.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + if !name.ends_with(".jpg") && !name.ends_with(".jpeg") { + return Err("not_a_jpeg".into()); + } + let meta = std::fs::metadata(&file).map_err(|e| e.to_string())?; + if meta.len() > 80 * 1024 * 1024 { + return Err("file_too_large".into()); + } + let bytes = std::fs::read(&file).map_err(|e| e.to_string())?; + Ok(tauri::ipc::Response::new(bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base64_round_trip_of_a_short_buffer() { + let raw = b"faces"; + let encoded = b64(raw); + assert_eq!(encoded, "ZmFjZXM="); + } + + #[test] + fn a_soft_face_behind_a_sharp_one_is_not_named() { + let sharp = FoundFace { + x0: 0.4, + y0: 0.05, + x1: 0.5, + y1: 0.2, + score: 0.9, + landmarks: [[0.0; 2]; 5], + sharpness: Some(300.0), + embedding: Some(vec![1.0]), + }; + let soft = FoundFace { sharpness: Some(10.0), embedding: Some(vec![1.0]), ..sharp.clone() }; + let faces = [sharp.clone(), soft]; + let named = worth_naming(&faces); + assert_eq!(named.len(), 1); + assert_eq!(named[0].sharpness, Some(300.0)); + } +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index b5aeac8..a0681d0 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -7,6 +7,7 @@ mod card; mod catalog; +mod faces; mod deliver; mod ftp; mod local; @@ -85,6 +86,7 @@ pub fn run() { .manage(local::LocalIndex::default()) .manage(catalog::Catalog::default()) .manage(card::CardState::default()) + .manage(faces::FaceScan::default()) .manage(deliver::Deliveries::default()) .manage(shared) .setup(|app| { @@ -134,6 +136,11 @@ pub fn run() { card::card_ingest, card::card_settings, card::card_save_settings, + faces::faces_local, + faces::faces_scan, + faces::faces_cancel, + faces::faces_remember, + faces::faces_read, updater::update_check, updater::update_install, ui::ui_status, diff --git a/apps/desktop/src-tauri/src/ui.rs b/apps/desktop/src-tauri/src/ui.rs index d0fcf50..39bb551 100644 --- a/apps/desktop/src-tauri/src/ui.rs +++ b/apps/desktop/src-tauri/src/ui.rs @@ -216,17 +216,21 @@ pub fn watch(app: tauri::AppHandle) { }); } -fn client() -> Result { +pub(crate) fn http_client(timeout_secs: u64) -> Result { if rustls::crypto::CryptoProvider::get_default().is_none() { let _ = rustls::crypto::ring::default_provider().install_default(); } reqwest::Client::builder() .user_agent(concat!("PhotoReport-desktop/", env!("CARGO_PKG_VERSION"))) - .timeout(std::time::Duration::from_secs(120)) + .timeout(std::time::Duration::from_secs(timeout_secs)) .build() .map_err(|e| e.to_string()) } +fn client() -> Result { + http_client(120) +} + /// One check: the published manifest (a few KB), and only if it is newer than what is in use, the files that changed. async fn check(app: &tauri::AppHandle) -> Result { let ui = app.state::().inner().clone(); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index d00baa8..96c746f 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PhotoReport", - "version": "0.3.12", + "version": "0.3.13", "identifier": "pt.photoreport.desktop", "build": { "devUrl": "http://localhost:5173", diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 1ea0a33..8c27f9a 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -1,5 +1,5 @@ import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts"; -import type { AgendaEntry, ArchiveStorage, CardScan, CloudFolderSummary, CloudSource, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js"; +import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, CloudFolderSummary, CloudSource, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js"; /** * Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it @@ -723,6 +723,11 @@ export class ApiClient { return this.request("POST", `/v1/orgs/${orgId}/faces/scan${eventId ? `?eventId=${eventId}` : ""}`, form); } + /** Names for faces already read on this computer. The photo is not uploaded. */ + identifyFaces(orgId: string, input: { eventId?: string; model?: string; faces: { embedding: number[] }[] }) { + return this.request("POST", `/v1/orgs/${orgId}/faces/identify`, input); + } + /** * Search the library by a photo: who that face is and every photo with it (all events, or one). `face` picks * another face of the photo (0: the largest). The photo is not kept on the server. diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 125828e..01dcd19 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -456,7 +456,6 @@ export interface LookupFace { clear: boolean; } -/** One photo from a folder, read and not kept: clear faces, the shirt number, and the known person. */ export interface CardScan { /** How many photos the server can read at once. The client keeps that many in flight. */ slots: number; @@ -469,6 +468,14 @@ export interface CardScan { }[]; } +/** Names for embeddings already computed on the photographer's computer. The photo is not uploaded. */ +export interface FaceIdentify { + /** People of the chosen game asked first. Null: that game has no squad, so everyone is asked together. */ + roster: number | null; + /** One name per embedding, in the same order. Null when nobody matches. */ + people: CardScan["faces"][number]["person"][]; +} + /** The result of searching by a photo. */ export interface PhotoLookup { faces: LookupFace[]; diff --git a/workers/faces/Cargo.toml b/workers/faces/Cargo.toml index 90eabe1..4e4a6a5 100644 --- a/workers/faces/Cargo.toml +++ b/workers/faces/Cargo.toml @@ -5,6 +5,10 @@ edition.workspace = true publish.workspace = true description = "Face detection and embeddings for PhotoReport ingest, built on lightcraft-faces (YuNet + AuraFace/SFace)" +[lib] +name = "photoreport_faces" +path = "src/lib.rs" + [[bin]] name = "photoreport-faces" path = "src/main.rs" diff --git a/workers/faces/src/lib.rs b/workers/faces/src/lib.rs new file mode 100644 index 0000000..3ce4e79 --- /dev/null +++ b/workers/faces/src/lib.rs @@ -0,0 +1,152 @@ +//! Face detection and embeddings shared by the worker process and the desktop app. +//! +//! The interpreter is single-threaded (`Rc` inside the network), so each thread loads its own copy. + +use std::path::{Path, PathBuf}; + +use lightcraft_faces::align::{Rgb, align_to_template}; +use lightcraft_faces::known; +use lightcraft_faces::runtime::Embedder; +use lightcraft_faces::yunet::{Detector, Options}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +#[derive(Clone, Serialize, Deserialize)] +pub struct FoundFace { + pub x0: f32, + pub y0: f32, + pub x1: f32, + pub y1: f32, + pub score: f32, + pub landmarks: [[f32; 2]; 5], + /// Variance of the Laplacian of the aligned face (grey levels): low means blurred or out of focus. + pub sharpness: Option, + pub embedding: Option>, +} + +pub struct Analysed { + pub width: usize, + pub height: usize, + pub faces: Vec, +} + +struct Models { + detector: Detector, + embedder: Embedder, +} + +/// One loaded copy of YuNet + AuraFace. Not shareable across threads: build one per worker. +pub struct Engine { + models: Models, + min_score: f32, +} + +fn sha256(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + digest.iter().map(|b| format!("{b:02x}")).collect() +} + +fn load(dir: &Path, embedder: &str) -> Result { + let yunet = known::yunet(); + let det_path = dir.join("face_detection_yunet_2023mar.onnx"); + let det_bytes = std::fs::read(&det_path).map_err(|e| format!("{}: {e}", det_path.display()))?; + if Some(sha256(&det_bytes).as_str()) != yunet.sha256.as_deref() { + return Err(format!("{} does not match the published YuNet file", det_path.display())); + } + let detector = Detector::new(&det_bytes).map_err(|e| e.to_string())?; + + let (manifest, file) = match embedder { + "sface" => (known::sface(), "face_recognition_sface_2021dec.onnx"), + _ => (known::auraface(), "glintr100.onnx"), + }; + let emb_path: PathBuf = dir.join(file); + let emb_bytes = std::fs::read(&emb_path).map_err(|e| format!("{}: {e}", emb_path.display()))?; + if Some(sha256(&emb_bytes).as_str()) != manifest.sha256.as_deref() { + return Err(format!("{} does not match the published {} file", emb_path.display(), manifest.name)); + } + drop(emb_bytes); + let embedder = Embedder::load(&emb_path, &manifest).map_err(|e| e.to_string())?; + Ok(Models { detector, embedder }) +} + +/// Variance of the 4-neighbour Laplacian over the inner half of the face (eyes, nose, mouth), so hair and +/// background edges count less. Grey levels 0-255. +fn sharpness(rgb: &[u8], w: usize, h: usize) -> f32 { + let grey = |x: usize, y: usize| -> f32 { + let i = (y * w + x) * 3; + match rgb.get(i..i + 3) { + Some(p) => 0.299 * f32::from(p[0]) + 0.587 * f32::from(p[1]) + 0.114 * f32::from(p[2]), + None => 0.0, + } + }; + let (mut n, mut sum, mut sq) = (0f64, 0f64, 0f64); + for y in (h / 4).max(1)..(h * 3 / 4).min(h - 1) { + for x in (w / 4).max(1)..(w * 3 / 4).min(w - 1) { + let l = 4.0 * grey(x, y) - grey(x - 1, y) - grey(x + 1, y) - grey(x, y - 1) - grey(x, y + 1); + n += 1.0; + sum += f64::from(l); + sq += f64::from(l) * f64::from(l); + } + } + if n == 0.0 { + return 0.0; + } + let mean = sum / n; + (sq / n - mean * mean) as f32 +} + +impl Engine { + /// Loads YuNet and the recognition model (`auraface` or `sface`). Checks each file against its published SHA-256. + pub fn load(dir: &Path, embedder: &str, min_score: f32) -> Result { + Ok(Engine { models: load(dir, embedder)?, min_score }) + } + + pub fn dim(&self) -> u64 { + match self.models.embedder.manifest().output { + lightcraft_faces::OutputSpec::Embedding { dim } => u64::from(dim), + _ => 0, + } + } + + /// Faces in one upright JPEG (EXIF orientation applied), with an embedding when the face can be aligned. + pub fn analyse(&self, path: &Path) -> Result { + let mut decoder = image::ImageReader::open(path) + .and_then(|r| r.with_guessed_format()) + .map_err(|e| e.to_string())? + .into_decoder() + .map_err(|e| e.to_string())?; + let orientation = image::ImageDecoder::orientation(&mut decoder).unwrap_or(image::metadata::Orientation::NoTransforms); + let mut dynamic = image::DynamicImage::from_decoder(decoder).map_err(|e| e.to_string())?; + dynamic.apply_orientation(orientation); + let img = dynamic.into_rgb8(); + let (w, h) = (img.width() as usize, img.height() as usize); + let rgb = img.into_raw(); + let faces = self + .models + .detector + .detect(&rgb, w, h, &Options { score: self.min_score, ..Options::default() }) + .map_err(|e| e.to_string())?; + let pic = Rgb { data: &rgb, width: w, height: h }; + let (iw, ih) = self.models.embedder.input_size(); + let out = faces + .iter() + .map(|f| { + let px = f.landmarks.map(|(x, y)| (x * w as f32, y * h as f32)); + let crop = align_to_template(&pic, &px, iw, ih); + let sharpness = crop.as_deref().map(|c| sharpness(c, iw, ih)); + let embedding = crop.and_then(|c| self.models.embedder.embed(&c).ok()); + FoundFace { + x0: f.x0.clamp(0.0, 1.0), + y0: f.y0.clamp(0.0, 1.0), + x1: f.x1.clamp(0.0, 1.0), + y1: f.y1.clamp(0.0, 1.0), + score: f.score, + landmarks: f.landmarks.map(|(x, y)| [x, y]), + sharpness, + embedding, + } + }) + .collect(); + Ok(Analysed { width: w, height: h, faces: out }) + } +} diff --git a/workers/faces/src/main.rs b/workers/faces/src/main.rs index 377d772..96165f6 100644 --- a/workers/faces/src/main.rs +++ b/workers/faces/src/main.rs @@ -5,18 +5,13 @@ //! out: {"id": "...", "width": W, "height": H, "faces": [{"x0":..,"y0":..,"x1":..,"y1":..,"score":.., //! "landmarks": [[x,y] x5], "embedding": [..]}]} (box and landmarks in fractions of the photo) //! or: {"id": "...", "error": "..."} -//! Detection is YuNet; recognition is AuraFace v1 (Apache-2.0, default) or SFace, both run by LightCraft's -//! pure-Rust interpreter. Model files are checked against their SHA-256 before use. +//! Detection is YuNet; recognition is AuraFace v1 (Apache-2.0). Model files are checked against their SHA-256. use std::io::{BufRead, Write}; -use std::path::{Path, PathBuf}; +use std::path::Path; -use lightcraft_faces::align::{Rgb, align_to_template}; -use lightcraft_faces::known; -use lightcraft_faces::runtime::Embedder; -use lightcraft_faces::yunet::{Detector, Options}; +use photoreport_faces::{Engine, FoundFace}; use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; #[derive(Deserialize)] struct Request { @@ -24,160 +19,11 @@ struct Request { path: String, } -#[derive(Serialize)] -struct FaceOut { - x0: f32, - y0: f32, - x1: f32, - y1: f32, - score: f32, - landmarks: [[f32; 2]; 5], - /// Variance of the Laplacian of the aligned face (grey levels): low means blurred or out of focus. - sharpness: Option, - embedding: Option>, -} - #[derive(Serialize)] #[serde(untagged)] enum Response { - Ok { - id: String, - width: usize, - height: usize, - faces: Vec, - }, - Err { - id: String, - error: String, - }, -} - -struct Models { - detector: Detector, - embedder: Embedder, -} - -fn sha256(bytes: &[u8]) -> String { - let digest = Sha256::digest(bytes); - digest.iter().map(|b| format!("{b:02x}")).collect() -} - -fn load(dir: &Path, embedder: &str) -> Result { - let yunet = known::yunet(); - let det_path = dir.join("face_detection_yunet_2023mar.onnx"); - let det_bytes = std::fs::read(&det_path).map_err(|e| format!("{}: {e}", det_path.display()))?; - if Some(sha256(&det_bytes).as_str()) != yunet.sha256.as_deref() { - return Err(format!( - "{} does not match the published YuNet file", - det_path.display() - )); - } - let detector = Detector::new(&det_bytes).map_err(|e| e.to_string())?; - - let (manifest, file) = match embedder { - "sface" => (known::sface(), "face_recognition_sface_2021dec.onnx"), - _ => (known::auraface(), "glintr100.onnx"), - }; - let emb_path: PathBuf = dir.join(file); - let emb_bytes = std::fs::read(&emb_path).map_err(|e| format!("{}: {e}", emb_path.display()))?; - if Some(sha256(&emb_bytes).as_str()) != manifest.sha256.as_deref() { - return Err(format!( - "{} does not match the published {} file", - emb_path.display(), - manifest.name - )); - } - drop(emb_bytes); - let embedder = Embedder::load(&emb_path, &manifest).map_err(|e| e.to_string())?; - Ok(Models { detector, embedder }) -} - -/// Variance of the 4-neighbour Laplacian over the inner half of the face (eyes, nose, mouth), so hair and -/// background edges count less. Grey levels 0-255. -fn sharpness(rgb: &[u8], w: usize, h: usize) -> f32 { - let grey = |x: usize, y: usize| -> f32 { - let i = (y * w + x) * 3; - match rgb.get(i..i + 3) { - Some(p) => 0.299 * f32::from(p[0]) + 0.587 * f32::from(p[1]) + 0.114 * f32::from(p[2]), - None => 0.0, - } - }; - let (mut n, mut sum, mut sq) = (0f64, 0f64, 0f64); - for y in (h / 4).max(1)..(h * 3 / 4).min(h - 1) { - for x in (w / 4).max(1)..(w * 3 / 4).min(w - 1) { - let l = 4.0 * grey(x, y) - - grey(x - 1, y) - - grey(x + 1, y) - - grey(x, y - 1) - - grey(x, y + 1); - n += 1.0; - sum += f64::from(l); - sq += f64::from(l) * f64::from(l); - } - } - if n == 0.0 { - return 0.0; - } - let mean = sum / n; - (sq / n - mean * mean) as f32 -} - -fn analyse( - models: &Models, - path: &str, - min_score: f32, -) -> Result<(usize, usize, Vec), String> { - // Upright, as people see it (EXIF orientation): boxes then match the previews, and YuNet sees faces upright. - let mut decoder = image::ImageReader::open(path) - .and_then(|r| r.with_guessed_format()) - .map_err(|e| e.to_string())? - .into_decoder() - .map_err(|e| e.to_string())?; - let orientation = image::ImageDecoder::orientation(&mut decoder) - .unwrap_or(image::metadata::Orientation::NoTransforms); - let mut dynamic = image::DynamicImage::from_decoder(decoder).map_err(|e| e.to_string())?; - dynamic.apply_orientation(orientation); - let img = dynamic.into_rgb8(); - let (w, h) = (img.width() as usize, img.height() as usize); - let rgb = img.into_raw(); - let faces = models - .detector - .detect( - &rgb, - w, - h, - &Options { - score: min_score, - ..Options::default() - }, - ) - .map_err(|e| e.to_string())?; - let pic = Rgb { - data: &rgb, - width: w, - height: h, - }; - let (iw, ih) = models.embedder.input_size(); - let out = faces - .iter() - .map(|f| { - let px = f.landmarks.map(|(x, y)| (x * w as f32, y * h as f32)); - let crop = align_to_template(&pic, &px, iw, ih); - let sharpness = crop.as_deref().map(|c| sharpness(c, iw, ih)); - let embedding = crop.and_then(|c| models.embedder.embed(&c).ok()); - FaceOut { - x0: f.x0.clamp(0.0, 1.0), - y0: f.y0.clamp(0.0, 1.0), - x1: f.x1.clamp(0.0, 1.0), - y1: f.y1.clamp(0.0, 1.0), - score: f.score, - landmarks: f.landmarks.map(|(x, y)| [x, y]), - sharpness, - embedding, - } - }) - .collect(); - Ok((w, h, out)) + Ok { id: String, width: usize, height: usize, faces: Vec }, + Err { id: String, error: String }, } fn main() { @@ -189,16 +35,11 @@ fn main() { match arg.as_str() { "--models" => models_dir = args.next().unwrap_or_default(), "--embedder" => embedder = args.next().unwrap_or_default(), - "--min-score" => { - min_score = args - .next() - .and_then(|v| v.parse().ok()) - .unwrap_or(min_score) - } + "--min-score" => min_score = args.next().and_then(|v| v.parse().ok()).unwrap_or(min_score), _ => {} } } - let models = match load(Path::new(&models_dir), &embedder) { + let models = match Engine::load(Path::new(&models_dir), &embedder, min_score) { Ok(m) => m, Err(e) => { eprintln!("photoreport-faces: {e}"); @@ -207,12 +48,7 @@ fn main() { }; let stdout = std::io::stdout(); let mut out = stdout.lock(); - // Ready signal: the caller waits for this line before sending work. - let _ = writeln!( - out, - "{}", - serde_json::json!({ "ready": true, "embedder": embedder, "dim": match models.embedder.manifest().output { lightcraft_faces::OutputSpec::Embedding { dim } => dim, _ => 0 } }) - ); + let _ = writeln!(out, "{}", serde_json::json!({ "ready": true, "embedder": embedder, "dim": models.dim() })); let _ = out.flush(); for line in std::io::stdin().lock().lines() { let Ok(line) = line else { break }; @@ -220,24 +56,13 @@ fn main() { continue; } let response = match serde_json::from_str::(&line) { - Ok(req) => match analyse(&models, &req.path, min_score) { - Ok((width, height, faces)) => Response::Ok { - id: req.id, - width, - height, - faces, - }, + Ok(req) => match models.analyse(Path::new(&req.path)) { + Ok(read) => Response::Ok { id: req.id, width: read.width, height: read.height, faces: read.faces }, Err(error) => Response::Err { id: req.id, error }, }, - Err(e) => Response::Err { - id: String::new(), - error: format!("bad request: {e}"), - }, + Err(e) => Response::Err { id: String::new(), error: format!("bad request: {e}") }, }; - if serde_json::to_writer(&mut out, &response).is_err() - || writeln!(out).is_err() - || out.flush().is_err() - { + if serde_json::to_writer(&mut out, &response).is_err() || writeln!(out).is_err() || out.flush().is_err() { break; } } -- 2.47.3