diff --git a/apps/api/src/autopilot/learning.ts b/apps/api/src/autopilot/learning.ts index 4353009..c85a367 100644 --- a/apps/api/src/autopilot/learning.ts +++ b/apps/api/src/autopilot/learning.ts @@ -1,6 +1,9 @@ import type { EditCommand } from "@photoreport/contracts"; import type { Db } from "../db.js"; import type { Box } from "../composition/compose.js"; +import { TONE_KEYS, WB_KEYS } from "./look.js"; + +export { TONE_KEYS, WB_KEYS }; /** * Learning from corrections (docs/photo-editing-rules.md §4): when someone changes what the autopilot did to a @@ -12,9 +15,6 @@ import type { Box } from "../composition/compose.js"; * alone. A correction counts only when most recent ones agree on the direction, so one odd photo changes nothing. */ -export const TONE_KEYS = ["light.exposure", "light.contrast", "light.highlights", "light.shadows", "light.whites", "light.blacks", "color.vibrance", "color.saturation"]; -export const WB_KEYS = ["wb.temp", "wb.tint"]; - /** Below this, a difference is noise; above `max`, it is a creative choice, not a correction. */ const LIMITS: Record = { "light.exposure": { min: 0.05, max: 1.5 }, diff --git a/apps/api/src/autopilot/look.ts b/apps/api/src/autopilot/look.ts index 7ee81b3..60ecf95 100644 --- a/apps/api/src/autopilot/look.ts +++ b/apps/api/src/autopilot/look.ts @@ -14,6 +14,10 @@ export type Look = "agency" | "natural" | "none"; +/** Tone and white balance the autopilot sets, and learns from. Shared with the desktop plan. */ +export const TONE_KEYS = ["light.exposure", "light.contrast", "light.highlights", "light.shadows", "light.whites", "light.blacks", "color.vibrance", "color.saturation"]; +export const WB_KEYS = ["wb.temp", "wb.tint"]; + const BASE: Record, Record> = { agency: { "color.vibrance": 18, diff --git a/apps/api/src/autopilot/routes.ts b/apps/api/src/autopilot/routes.ts index 4d7e582..947576c 100644 --- a/apps/api/src/autopilot/routes.ts +++ b/apps/api/src/autopilot/routes.ts @@ -15,8 +15,10 @@ export async function registerAutopilotRoutes(app: FastifyInstance, deps: { db: app.get("/v1/orgs/:orgId/autopilot/style", { preHandler: authenticate }, async (req) => { const { orgId } = z.object({ orgId: z.uuid() }).parse(req.params); const q = Query.parse(req.query); - await requireMembership(db, req, orgId, "INGESTER"); - const photographerId = q.photographerId ?? currentUserId(req); + const me = currentUserId(req); + const photographerId = q.photographerId ?? me; + // Your own style is what the desktop caches to edit offline. Someone else's needs an editor. + await requireMembership(db, req, orgId, photographerId !== me ? "EDITOR" : "PHOTOGRAPHER"); const style = await learntStyle(db, orgId, photographerId, q.venue); return { photographerId, style }; }); diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index 592bece..948bd12 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -4,8 +4,9 @@ import type { Db } from "../db.js"; import type { DeliveryService } from "../delivery/service.js"; import type { RenderEngine } from "../develop/engine.js"; import type { DevelopService } from "../develop/service.js"; -import { type Box, compose, frameScore, isReportage, minCropWidth, peopleIn, planCrop } from "../composition/compose.js"; +import { type Box, frameScore, isReportage, peopleIn } from "../composition/compose.js"; import type { SubjectDetector } from "../composition/detect.js"; +import { planFrame, levelAngle, measuredValues } from "../composition/planFrame.js"; import { constrainRotated, tighter } from "../composition/geometry.js"; import type { IngestLogger } from "../ingest/service.js"; import { waitUntil } from "../lib/idle.js"; @@ -17,18 +18,12 @@ import { CANDIDATE_SELECT, candidatesOf } from "./best.js"; import { sequenceWeights } from "./sequence.js"; import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.js"; import { curate, matchMinutes } from "./curate.js"; -import { type LearntStyle, learntStyle, TONE_KEYS, WB_KEYS } from "./learning.js"; -import { detailForCrop, lookValues, toneApplied } from "./look.js"; +import { type LearntStyle, learntStyle } from "./learning.js"; +import { detailForCrop, lookValues } from "./look.js"; const STALE_RUNNING_MS = 10 * 60_000; /** A burst is decided once no new frame of it has arrived for this long. */ const BURST_SETTLE_MS = 15_000; -/** Straightening beyond this is more likely a creative tilt than a crooked horizon: left alone. */ -const MAX_LEVEL = 5; -const MIN_LEVEL = 0.3; -/** A crop this close to the whole frame (width) is not worth making: the photo stays as shot (agencies send a third uncropped). */ -const KEEP_WHOLE = 0.92; - export interface AutopilotRecord { score: number; reason: string | null; @@ -113,57 +108,39 @@ export class AutopilotService { const preview = storage.resolve(storage.derivedKey(photo.organizationId, photo.sha256, "preview")); const W = photo.width ?? 3; const H = photo.height ?? 2; - const ops: EditCommand[] = []; const reportage = isReportage(photo.event); - // White balance and tone (a measured amount), and the level angle. - let angle = 0; - let values: Record | null = null; // What this photographer's corrections taught it (none until there are enough that agree). const style = await learntStyle(db, photo.organizationId, photo.uploaderId, photo.event?.venue).catch(() => null); + let rawAngle: number | null = null; + let values: Record | null = null; if (engine && (settings.tone || settings.whiteBalance || settings.level)) { const auto = await engine.auto(preview, null); - values = {}; - if (settings.whiteBalance) for (const k of WB_KEYS) if (auto.values[k] !== undefined) values[k] = auto.values[k]! + (style?.offsets[k] ?? 0); - if (settings.tone) - for (const k of TONE_KEYS) { - const v = toneApplied(k, auto.values[k] ?? 0, settings.toneStrength, reportage) + (style?.offsets[k] ?? 0); - if (v) values[k] = Math.round(v * 100) / 100; - } - // The finishing look (colour, local contrast, sharpening, noise by ISO): never over what was measured. - // Structure and sharpening are scaled to the crop below, once the crop exists: they belong to the whole frame. - for (const [k, v] of Object.entries(lookValues(settings.look, photo.iso))) if (values[k] === undefined) values[k] = v; - if (settings.level && auto.angle !== null && Math.abs(auto.angle) >= MIN_LEVEL && Math.abs(auto.angle) <= MAX_LEVEL) angle = auto.angle; + rawAngle = auto.angle; + values = measuredValues(auto.values, settings, reportage, photo.iso, style?.offsets ?? {}); } - - // The crop around who the photo is about. + const angle = levelAngle(rawAngle, settings.level); const load = this.deps.detector(); const detections = load ? await (await load).detect(preview) : null; - const aspect = settings.aspect ? settings.aspect[0] / settings.aspect[1] : null; const focusFile = photo.originalStored ? storage.resolve(photo.storageKey) : preview; const focus = focusFromExifJson(photo.exif) ?? (existsSync(focusFile) ? await readFocusPoint(focusFile) : null); - const minWidth = minCropWidth(W, H, settings.minLongEdge); - const context = reportage ? "reportage" : "sport"; - // Faces tell a whole figure from a bust (a head in a car window, a torso). They may not be ready yet; - // the crop still refuses to slice a person who is only a little less sharp. + // Faces tell a whole figure from a bust. They may not be ready yet; the crop still refuses a slice. const faces = reportage ? (await db.face.findMany({ where: { photoId }, select: { x0: true, y0: true, x1: true, y1: true } })).map((f) => ({ x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1 })) : []; - const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces }) : null; - const wideComposition = detections && !reportage && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full", context: "sport" }) : null; - const plans = reportage && detections ? { half: planCrop(detections, "half", aspect, { minWidth, focus, context, faces }), threeQuarter: planCrop(detections, "threeQuarter", aspect, { minWidth, focus, context, faces }) } : null; - let crop: Box | null = null; - if (settings.crop && composition) { - // Photographers who always tighten the autopilot's crop get it tighter (never cutting into the subject). - const rect = style?.cropFactor ? tighter(composition.rect, composition.subject, style.cropFactor) : composition.rect; - // Almost the whole frame: leave the photo as shot. - if (rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(rect, angle, W, H); - } - const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(wideComposition.rect, angle, W, H) : null; - if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H); - if (values) { - const tuned = detailForCrop(values, crop, W, H); - if (Object.keys(tuned).length) ops.push({ command: "develop.set", params: { values: tuned } } as EditCommand); - } - if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } } as EditCommand); + const planned = planFrame({ + detections, + width: W, + height: H, + reportage, + values, + angle, + focus, + faces, + cropFactor: style?.cropFactor ?? null, + settings, + }); + const ops = planned.ops; + const { crop, wide, composition, plans } = planned; + const context = reportage ? "reportage" : "sport"; // Someone already edited it (on the desktop app without a network, before it was uploaded): their edit // stands; the autopilot still scores the frame for its burst. diff --git a/apps/api/src/composition/compose.ts b/apps/api/src/composition/compose.ts index d5fc583..b921bba 100644 --- a/apps/api/src/composition/compose.ts +++ b/apps/api/src/composition/compose.ts @@ -19,7 +19,12 @@ * When the camera wrote a focus point, the person under it is the subject; sharpness still frames everyone else. */ -import type { FocusHint } from "../ingest/focus.js"; +/** Where the camera focused, as a point on the upright photo. Same shape as `ingest/focus.ts`. */ +export interface FocusHint { + x: number; + y: number; + box?: { x0: number; y0: number; x1: number; y1: number }; +} export interface Box { x0: number; diff --git a/apps/api/src/composition/detect.ts b/apps/api/src/composition/detect.ts index 64e65ad..f75ebdf 100644 --- a/apps/api/src/composition/detect.ts +++ b/apps/api/src/composition/detect.ts @@ -4,14 +4,13 @@ import * as ort from "onnxruntime-node"; import { modelsDir } from "../lib/models.js"; import sharp from "sharp"; import type { Detection, Detections } from "./compose.js"; +import { BALL, PERSON, YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf } from "./yolox.js"; /** * People and balls in a photo, with YOLOX-s (Apache-2.0, COCO classes; infra/faces/download-models.sh fetches it). * Runs on the CPU in a few hundred milliseconds at 640 px, which is plenty to find who a sports photo is about. */ -const SIZE = 640; -const PERSON = 0; -const BALL = 32; // COCO "sports ball" +const SIZE = YOLOX_SIZE; /** Loads the detector on first use from the downloaded models (null while the model isn't there). `sessions` run side by side. */ export function lazyDetector(storageRoot: string, sessions = 1): () => Promise | null { @@ -92,67 +91,13 @@ export class SubjectDetector { } finally { this.pool.release(session); } - const all = decode(raw, scale, width, height); - const people = nms(all.filter((d) => d.cls === PERSON)); + const all = decodeYolox(raw, scale, width, height); + const people = nmsKeep(all.filter((d) => d.cls === PERSON)); await addSharpness(file, people); - return { width, height, people, balls: nms(all.filter((d) => d.cls === BALL)) }; + return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)) }; } } -interface Raw extends Detection { - cls: number; -} - -/** YOLOX head output (8400 anchors x [cx, cy, w, h, obj, 80 classes]) on the 8/16/32 grids, to photo fractions. */ -function decode(raw: Float32Array, scale: number, width: number, height: number): Raw[] { - const out: Raw[] = []; - const stride = 85; - let a = 0; - for (const s of [8, 16, 32]) { - const g = SIZE / s; - for (let y = 0; y < g; y++) { - for (let x = 0; x < g; x++, a++) { - const o = a * stride; - const obj = raw[o + 4]!; - if (obj < 0.1) continue; - for (const cls of [PERSON, BALL]) { - const score = obj * raw[o + 5 + cls]!; - if (score < 0.25) continue; - const bx = (raw[o]! + x) * s; - const by = (raw[o + 1]! + y) * s; - const bw = Math.exp(raw[o + 2]!) * s; - const bh = Math.exp(raw[o + 3]!) * s; - out.push({ - cls, - score, - x0: clamp((bx - bw / 2) / scale / width), - y0: clamp((by - bh / 2) / scale / height), - x1: clamp((bx + bw / 2) / scale / width), - y1: clamp((by + bh / 2) / scale / height), - }); - } - } - } - } - return out; -} - -const clamp = (v: number) => Math.min(1, Math.max(0, v)); - -function iou(a: Detection, b: Detection): number { - const ix = Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)); - const iy = Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0)); - const i = ix * iy; - return i / ((a.x1 - a.x0) * (a.y1 - a.y0) + (b.x1 - b.x0) * (b.y1 - b.y0) - i); -} - -function nms(list: Raw[], threshold = 0.45): Detection[] { - const sorted = [...list].sort((a, b) => b.score - a.score); - const kept: Raw[] = []; - for (const d of sorted) if (kept.every((k) => iou(k, d) < threshold)) kept.push(d); - return kept.map(({ x0, y0, x1, y1, score }) => ({ x0, y0, x1, y1, score })); -} - /** * How sharp each person is: the variance of the Laplacian over the upper part of their box (head and torso, * where focus is judged), relative to the sharpest person in the photo. The photographer focused on someone; @@ -162,29 +107,5 @@ async function addSharpness(file: string | Buffer, people: Detection[]): Promise if (!people.length) return; const W = 1024; const { data, info } = await sharp(file, { failOn: "none" }).rotate().resize({ width: W }).greyscale().raw().toBuffer({ resolveWithObject: true }); - const H = info.height; - const values = people.map((p) => { - const x0 = Math.max(1, Math.floor(p.x0 * W)); - const x1 = Math.min(W - 2, Math.ceil(p.x1 * W)); - const y0 = Math.max(1, Math.floor(p.y0 * H)); - const y1 = Math.min(H - 2, Math.ceil((p.y0 + 0.6 * (p.y1 - p.y0)) * H)); - let n = 0; - let sum = 0; - let sum2 = 0; - for (let y = y0; y <= y1; y++) { - for (let x = x0; x <= x1; x++) { - const i = y * W + x; - const l = 4 * data[i]! - data[i - 1]! - data[i + 1]! - data[i - W]! - data[i + W]!; - n++; - sum += l; - sum2 += l * l; - } - } - return n > 20 ? sum2 / n - (sum / n) ** 2 : 0; - }); - const max = Math.max(...values, 1e-9); - people.forEach((p, i) => { - p.sharpness = values[i]! / max; - p.focus = values[i]!; - }); + sharpnessOf(data, W, info.height, people); } diff --git a/apps/api/src/composition/planFrame.ts b/apps/api/src/composition/planFrame.ts new file mode 100644 index 0000000..3cad880 --- /dev/null +++ b/apps/api/src/composition/planFrame.ts @@ -0,0 +1,101 @@ +import type { EditCommand } from "@photoreport/contracts"; +import { type Box, type Detections, type FocusHint, compose, minCropWidth, planCrop } from "./compose.js"; +import { constrainRotated, tighter } from "./geometry.js"; +import { type Look, WB_KEYS, TONE_KEYS, detailForCrop, lookValues, toneApplied } from "../autopilot/look.js"; + +/** Straightening beyond this is more likely a creative tilt than a crooked horizon. */ +const MAX_LEVEL = 5; +const MIN_LEVEL = 0.3; +/** A crop this close to the whole frame is not worth making. */ +const KEEP_WHOLE = 0.92; + +export interface PlanSettings { + crop: boolean; + tone: boolean; + whiteBalance: boolean; + level: boolean; + toneStrength: number; + look: Look; + framing: "tight" | "full"; + aspect: [number, number] | null; + minLongEdge: number; +} + +/** The level angle the autopilot keeps. Outside the band, the photo stays as shot. */ +export function levelAngle(angle: number | null, enabled: boolean): number { + if (!enabled || angle === null || Math.abs(angle) < MIN_LEVEL || Math.abs(angle) > MAX_LEVEL) return 0; + return angle; +} + +/** + * White balance, tone and the finishing look, before the crop scales detail. Null when none of those are on: + * the same gate the server uses (it measures only when tone, white balance or level is enabled). + */ +export function measuredValues( + auto: Record, + settings: PlanSettings, + reportage: boolean, + iso: number | null, + offsets: Record, +): Record | null { + if (!settings.tone && !settings.whiteBalance && !settings.level) return null; + const values: Record = {}; + if (settings.whiteBalance) for (const k of WB_KEYS) if (auto[k] !== undefined) values[k] = auto[k]! + (offsets[k] ?? 0); + if (settings.tone) { + for (const k of TONE_KEYS) { + const v = toneApplied(k, auto[k] ?? 0, settings.toneStrength, reportage) + (offsets[k] ?? 0); + if (v) values[k] = Math.round(v * 100) / 100; + } + } + for (const [k, v] of Object.entries(lookValues(settings.look, iso))) if (values[k] === undefined) values[k] = v; + return values; +} + +export interface PlannedFrame { + ops: EditCommand[]; + crop: Box | null; + wide: Box | null; + composition: ReturnType; + plans: { half: Box | null; threeQuarter: Box | null } | null; +} + +/** + * The edit the autopilot would make for one photo. The server and the desktop both call this, so a photo edited + * here is the same edit the worker would have queued. + */ +export function planFrame(input: { + detections: Detections | null; + width: number; + height: number; + reportage: boolean; + values: Record | null; + angle: number; + focus?: FocusHint | null; + faces?: Box[]; + cropFactor?: number | null; + settings: PlanSettings; +}): PlannedFrame { + const { detections, settings, width: W, height: H, reportage } = input; + const aspect = settings.aspect ? settings.aspect[0] / settings.aspect[1] : null; + const minWidth = minCropWidth(W, H, settings.minLongEdge); + const context = reportage ? "reportage" : "sport"; + const faces = input.faces ?? []; + const focus = input.focus ?? null; + const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces }) : null; + const wideComposition = detections && !reportage && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full", context: "sport" }) : null; + const plans = reportage && detections ? { half: planCrop(detections, "half", aspect, { minWidth, focus, context, faces }), threeQuarter: planCrop(detections, "threeQuarter", aspect, { minWidth, focus, context, faces }) } : null; + let crop: Box | null = null; + if (settings.crop && composition) { + const rect = input.cropFactor ? tighter(composition.rect, composition.subject, input.cropFactor) : composition.rect; + if (rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(rect, input.angle, W, H); + } + const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(wideComposition.rect, input.angle, W, H) : null; + if (!crop && input.angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, input.angle, W, H); + const ops: EditCommand[] = []; + if (input.values) { + const tuned = detailForCrop(input.values, crop, W, H); + if (Object.keys(tuned).length) ops.push({ command: "develop.set", params: { values: tuned } }); + } + if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle: input.angle, aspect: settings.aspect ?? [W, H] } }); + return { ops, crop, wide, composition, plans }; +} diff --git a/apps/api/src/composition/routes.ts b/apps/api/src/composition/routes.ts index c16fb6e..85a0fd2 100644 --- a/apps/api/src/composition/routes.ts +++ b/apps/api/src/composition/routes.ts @@ -1,10 +1,13 @@ -import { existsSync } from "node:fs"; +import { createReadStream, existsSync } from "node:fs"; +import { stat } from "node:fs/promises"; +import { join } from "node:path"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { requireAuth, requireMembership } from "../auth/guard.js"; import type { SessionService } from "../auth/sessions.js"; import type { Db } from "../db.js"; import { notFound } from "../lib/errors.js"; +import { modelsDir } from "../lib/models.js"; import type { LocalStorage } from "../storage/storage.js"; import { readFocusPoint } from "../ingest/exif.js"; import { focusFromExifJson } from "../ingest/focus.js"; @@ -50,4 +53,15 @@ export async function registerCompositionRoutes(app: FastifyInstance, deps: { db const context = isReportage(photo.event) ? "reportage" : "sport"; return { crop: compose(detections, aspect ? aspect[0] / aspect[1] : null, { focus, context, faces: photo.faces }) }; }); + + /** YOLOX-s, so the desktop can crop with the same detector. Not a face model: no biometrics gate. */ + app.get("/v1/orgs/:orgId/models/yolox_s.onnx", { preHandler: authenticate }, async (req, reply) => { + const { orgId } = z.object({ orgId: z.uuid() }).parse(req.params); + await requireMembership(db, req, orgId, "PHOTOGRAPHER"); + const dir = modelsDir(deps.storageRoot); + const file = dir ? join(dir, "yolox_s.onnx") : ""; + const info = file ? await stat(file).catch(() => null) : null; + if (!info?.isFile()) return reply.code(404).send({ error: "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(file)); + }); } diff --git a/apps/api/src/composition/yolox.ts b/apps/api/src/composition/yolox.ts new file mode 100644 index 0000000..a673e1e --- /dev/null +++ b/apps/api/src/composition/yolox.ts @@ -0,0 +1,92 @@ +import type { Detection } from "./compose.js"; + +/** YOLOX-s input. People are COCO class 0, the sports ball is class 32. */ +export const YOLOX_SIZE = 640; +export const PERSON = 0; +export const BALL = 32; + +export interface RawDet extends Detection { + cls: number; +} + +const clamp = (v: number) => Math.min(1, Math.max(0, v)); + +/** YOLOX head output (8400 anchors x [cx, cy, w, h, obj, 80 classes]) on the 8/16/32 grids, to photo fractions. */ +export function decodeYolox(raw: Float32Array, scale: number, width: number, height: number): RawDet[] { + const out: RawDet[] = []; + const stride = 85; + let a = 0; + for (const s of [8, 16, 32]) { + const g = YOLOX_SIZE / s; + for (let y = 0; y < g; y++) { + for (let x = 0; x < g; x++, a++) { + const o = a * stride; + const obj = raw[o + 4]!; + if (obj < 0.1) continue; + for (const cls of [PERSON, BALL]) { + const score = obj * raw[o + 5 + cls]!; + if (score < 0.25) continue; + const bx = (raw[o]! + x) * s; + const by = (raw[o + 1]! + y) * s; + const bw = Math.exp(raw[o + 2]!) * s; + const bh = Math.exp(raw[o + 3]!) * s; + out.push({ + cls, + score, + x0: clamp((bx - bw / 2) / scale / width), + y0: clamp((by - bh / 2) / scale / height), + x1: clamp((bx + bw / 2) / scale / width), + y1: clamp((by + bh / 2) / scale / height), + }); + } + } + } + } + return out; +} + +function iou(a: Detection, b: Detection): number { + const ix = Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)); + const iy = Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0)); + const i = ix * iy; + return i / ((a.x1 - a.x0) * (a.y1 - a.y0) + (b.x1 - b.x0) * (b.y1 - b.y0) - i); +} + +export function nmsKeep(list: RawDet[], threshold = 0.45): Detection[] { + const sorted = [...list].sort((a, b) => b.score - a.score); + const kept: RawDet[] = []; + for (const d of sorted) if (kept.every((k) => iou(k, d) < threshold)) kept.push(d); + return kept.map(({ x0, y0, x1, y1, score }) => ({ x0, y0, x1, y1, score })); +} + +/** + * How sharp each person is: the variance of the Laplacian over the upper part of their box, on a greyscale + * image of `width` columns. Relative to the sharpest person, and the absolute value for comparing a burst. + */ +export function sharpnessOf(grey: ArrayLike, width: number, height: number, people: Detection[]): void { + if (!people.length) return; + const values = people.map((p) => { + const x0 = Math.max(1, Math.floor(p.x0 * width)); + const x1 = Math.min(width - 2, Math.ceil(p.x1 * width)); + const y0 = Math.max(1, Math.floor(p.y0 * height)); + const y1 = Math.min(height - 2, Math.ceil((p.y0 + 0.6 * (p.y1 - p.y0)) * height)); + let n = 0; + let sum = 0; + let sum2 = 0; + for (let y = y0; y <= y1; y++) { + for (let x = x0; x <= x1; x++) { + const i = y * width + x; + const l = 4 * grey[i]! - grey[i - 1]! - grey[i + 1]! - grey[i - width]! - grey[i + width]!; + n++; + sum += l; + sum2 += l * l; + } + } + return n > 20 ? sum2 / n - (sum / n) ** 2 : 0; + }); + const max = Math.max(...values, 1e-9); + people.forEach((p, i) => { + p.sharpness = values[i]! / max; + p.focus = values[i]!; + }); +} diff --git a/apps/api/src/faces/lookup.ts b/apps/api/src/faces/lookup.ts index 525a1e3..d400c7a 100644 --- a/apps/api/src/faces/lookup.ts +++ b/apps/api/src/faces/lookup.ts @@ -6,7 +6,7 @@ import type { Db } from "../db.js"; import type { JerseyReading } from "../jersey/model.js"; import { numberBoxes } from "../jersey/crop.js"; import { JERSEY_MIN_SCORE } from "./votes.js"; -import { MIN_SHARPNESS, THRESHOLDS, inFocus } from "./math.js"; +import { MIN_SHARPNESS, POSSIBLE_BELOW, THRESHOLDS, inFocus } from "./math.js"; import type { FaceEngine } from "./process.js"; /** A face found in the photo someone searched with (box in fractions of the photo). */ @@ -27,7 +27,6 @@ export class LookupRejected extends Error { } /** How far below the "same person" threshold a face still shows, as "possible". */ -const POSSIBLE_BELOW = 0.06; /** A face smaller than this (fraction of the long side) is not someone to name. */ const MIN_FACE_SIDE = 0.012; diff --git a/apps/api/src/faces/lookupRoutes.ts b/apps/api/src/faces/lookupRoutes.ts index 7587002..028e546 100644 --- a/apps/api/src/faces/lookupRoutes.ts +++ b/apps/api/src/faces/lookupRoutes.ts @@ -183,6 +183,35 @@ export async function registerLookupRoutes( }; }); + /** + * The squad of one game, for the desktop to name faces with no network. Only when the event has an opponent. + * Everyone else stays on the server. + */ + app.get("/v1/orgs/:orgId/events/:eventId/face-roster", { preHandler: authenticate }, async (req) => { + const { orgId, eventId } = z.object({ orgId: z.uuid(), eventId: z.uuid() }).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 event = await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }); + if (!event) throw new AppError(404, "event_not_found"); + const ctx = await numberContext(db, eventId); + if (!ctx) return { game: false as const, model: null, people: [] }; + const ids = await roster(eventId); + if (!ids?.length) return { game: true as const, model: null, people: [] }; + const rows = await db.person.findMany({ + where: { id: { in: ids }, organizationId: orgId, recognitionOffAt: null }, + select: { id: true, name: true, club: true, number: true, centroid: true, model: true }, + }); + const withFace = rows.filter((p) => p.centroid.length > 0); + const worn = await numbersIn(db, ctx, withFace.map((p) => p.id)); + const model = withFace.find((p) => p.model)?.model ?? "auraface-v1"; + return { + game: true as const, + model, + people: withFace.map((p) => ({ id: p.id, name: p.name, club: p.club, number: worn.get(p.id) ?? null, model: p.model, embedding: p.centroid })), + }; + }); + /** 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); diff --git a/apps/api/src/faces/math.ts b/apps/api/src/faces/math.ts index 1964862..576c00a 100644 --- a/apps/api/src/faces/math.ts +++ b/apps/api/src/faces/math.ts @@ -44,6 +44,9 @@ export function mergeMeans(parts: { mean: readonly number[]; count: number }[]): * purpose: a mixed group would name the wrong photos, while splitting one person in two costs a "Juntar" click. * Tuned on a real football match (58 photos, 472 faces): at 0.40 blurred crowd faces merged into groups of 20-35. */ +/** How far under `match` a face can sit and still be a possible, not a sure, name. */ +export const POSSIBLE_BELOW = 0.06; + export const THRESHOLDS: Record = { "auraface-v1": { match: 0.4, group: 0.45, margin: 0.05 }, "sface-2021dec": { match: 0.55, group: 0.6, margin: 0.05 }, diff --git a/apps/app/package.json b/apps/app/package.json index eaa8ff0..c7a7473 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -19,6 +19,7 @@ "@photoreport/sdk": "workspace:*", "@tauri-apps/api": "^2.12.3", "@tauri-apps/plugin-opener": "^2.7.1", + "onnxruntime-web": "1.29.0", "qrcode": "1.5.4", "react": "^19.3.0", "react-dom": "^19.3.0", diff --git a/apps/app/src/develop/SyncSettings.tsx b/apps/app/src/develop/SyncSettings.tsx new file mode 100644 index 0000000..e23f4ff --- /dev/null +++ b/apps/app/src/develop/SyncSettings.tsx @@ -0,0 +1,52 @@ +import { useState } from "react"; +import type { Module } from "@photoreport/contracts"; +import { t } from "../i18n.js"; +import { SYNC_MODULES } from "./copySettings.js"; + +/** Copy chosen groups from the active photo onto the other selected ones. Crop starts off. */ +export function SyncSettingsButton({ count, disabled, onApply }: { count: number; disabled?: boolean; onApply: (modules: Module[]) => Promise }) { + const [open, setOpen] = useState(false); + const [picked, setPicked] = useState(["basic"]); + const [busy, setBusy] = useState(false); + const toggle = (module: Module) => setPicked((cur) => (cur.includes(module) ? cur.filter((m) => m !== module) : [...cur, module])); + return ( + + + {open && ( +
+

{t.dev.syncHelp}

+
    + {SYNC_MODULES.map((module) => ( +
  • + +
  • + ))} +
+ +
+ )} +
+ ); +} diff --git a/apps/app/src/develop/copySettings.ts b/apps/app/src/develop/copySettings.ts new file mode 100644 index 0000000..06e4d98 --- /dev/null +++ b/apps/app/src/develop/copySettings.ts @@ -0,0 +1,76 @@ +import { CONTROLS, MODULES, controlsForModule, type EditCommand, type Module } from "@photoreport/contracts"; +import type { ApiClient } from "@photoreport/sdk"; +import { cache } from "../offline/cache.js"; +import { isNetworkError, offlineQueue } from "../offline/queue.js"; +import { type EngineModule, loadEngine } from "./engine.js"; +import { cropOf, localOutbox } from "./session.js"; + +/** Groups the photographer can copy. Crop is listed and starts off. */ +export const SYNC_MODULES: Module[] = MODULES.filter((m) => m === "crop" || controlsForModule(m).length > 0); + +/** Only the controls in the chosen groups. Other controls on the target photo stay as they are. */ +export function syncDevelopCommand(modules: readonly Module[], value: (id: string) => number): EditCommand | null { + const values: Record = {}; + for (const c of CONTROLS) { + if (c.module === "crop" || !modules.includes(c.module)) continue; + const v = value(c.id); + if (Number.isFinite(v)) values[c.id] = v; + } + if (!Object.keys(values).length) return null; + return { command: "develop.set", params: { values } }; +} + +export function syncCropCommand(settings: string): EditCommand { + const crop = cropOf(settings); + return { command: "crop.set", params: { rect: crop.rect, angle: crop.angle, aspect: crop.aspect } }; +} + +export function commandsFrom(modules: readonly Module[], settings: string, value: (id: string) => number): EditCommand[] { + const out: EditCommand[] = []; + const develop = syncDevelopCommand(modules, value); + if (develop) out.push(develop); + if (modules.includes("crop")) out.push(syncCropCommand(settings)); + return out; +} + +/** Settings of one photo: the cache, then anything newer on the server, then edits still waiting here. */ +export async function settingsOf(api: ApiClient, photoId: string): Promise { + const engine = await loadEngine(); + let settings = engine.defaultSettings(); + let seq = 0; + const cached = await cache.develop(photoId); + if (cached?.settings) { + settings = cached.settings; + seq = cached.seq; + } + if (!photoId.startsWith("local:")) { + try { + const state = await api.developState(photoId, cached ? seq : undefined); + if (!cached && state.snapshot) { + settings = JSON.stringify(state.snapshot); + seq = state.snapshotSeq; + } + for (const op of state.ops) { + if (op.seq > seq) settings = engine.apply(settings, JSON.stringify(op.command)); + } + } catch (err) { + if (!cached && !isNetworkError(err)) throw err; + } + } + for (const op of localOutbox.load(photoId)) settings = engine.apply(settings, JSON.stringify(op.command)); + return settings; +} + +export async function commandsForPhoto(api: ApiClient, photoId: string, modules: readonly Module[]): Promise { + const engine = await loadEngine(); + const settings = await settingsOf(api, photoId); + return commandsFrom(modules, settings, (id) => engine.value(settings, id)); +} + +/** Queue the commands for the other selected photos. They go out with the socket, and follow a local photo. */ +export function queueSync(orgId: string, photoIds: string[], commands: EditCommand[]): void { + const queue = offlineQueue(orgId); + for (const id of photoIds) for (const command of commands) queue.enqueueEdit(id, command); +} + +export type { EngineModule }; diff --git a/apps/app/src/develop/engine.ts b/apps/app/src/develop/engine.ts index abb9df8..4444a0e 100644 --- a/apps/app/src/develop/engine.ts +++ b/apps/app/src/develop/engine.ts @@ -12,6 +12,8 @@ export interface WasmPhoto { autoTone(settings: string): string; autoWb(): string; autoLevel(settings: string): string; + /** Sports level (boards and posts). Absent on an engine built before it. */ + autoLevelScene?(): string; wbAt(x: number, y: number): string; pixels(): Uint8Array; free(): void; diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 409bef8..2f735fd 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -1042,8 +1042,12 @@ export const t = { copy: "Copiar ajustes", paste: "Colar ajustes", pasted: (n: number) => `Ajustes colados em ${n} ${n === 1 ? "foto" : "fotos"}`, + sync: "Sincronizar ajustes", + syncHelp: "Copia os grupos escolhidos da foto activa para as outras seleccionadas. O recorte fica de fora até o ligares.", + syncApply: "Aplicar", + synced: (n: number) => `Ajustes sincronizados em ${n} ${n === 1 ? "foto" : "fotos"}`, noAccess: "Só podes revelar fotos que enviaste.", - shortcuts: "← → foto · P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · G grelha · I informação · Shift+A automático · \\ antes/depois · R recortar · W conta-gotas · Z 1:1 (arrastar move) · E lupa · Ctrl+Alt+1 biblioteca · Ctrl+Z anular", + shortcuts: "← → foto · Ctrl/Cmd+A todas · P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · G grelha · I informação · Shift+A automático · \\ antes/depois · R recortar · W conta-gotas · Z 1:1 (arrastar move) · E lupa · Ctrl+Alt+1 biblioteca · Ctrl+Z anular", groups: { wb: "Equilíbrio de brancos", tone: "Tom", presence: "Presença", profile: "Perfil" }, labels: { "profile.amount": "Intensidade", diff --git a/apps/app/src/library/CardScan.tsx b/apps/app/src/library/CardScan.tsx index 9b737fc..37d061b 100644 --- a/apps/app/src/library/CardScan.tsx +++ b/apps/app/src/library/CardScan.tsx @@ -3,6 +3,8 @@ import { ApiError } from "@photoreport/sdk"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { t } from "../i18n.js"; import { kv } from "../offline/kv.js"; +import { isNetworkError } from "../offline/queue.js"; +import { ensureRoster, matchRoster, savedRoster } from "../offline/roster.js"; import { asArrayBuffer, desktopInvoke, isDesktop } from "../platform.js"; type Face = CardReading["faces"][number]; @@ -160,6 +162,11 @@ export function CardScan({ const folderRef = useRef(""); const gameRef = useRef(gameId); gameRef.current = gameId; + useEffect(() => { + const game = games.find((g) => g.id === gameId); + if (!game) return; + void ensureRoster(api, orgId, game.id, game.away).catch(() => {}); + }, [api, orgId, gameId, games]); const choices = useMemo(() => [...games].sort((a, b) => b.startsAt.localeCompare(a.startsAt)), [games]); const runningRef = useRef(false); @@ -310,7 +317,14 @@ export function CardScan({ 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 }))) }); + const faces = batch.flatMap((row) => row.embeddings.map((embedding) => ({ embedding }))); + let named; + try { + named = await api.identifyFaces(orgId, { eventId: gameRef.current, faces }); + } catch (err) { + if (!isNetworkError(err)) throw err; + named = matchRoster(await savedRoster(orgId, gameRef.current), faces.map((f) => f.embedding)); + } setRoster(named.roster); let at = 0; for (const row of batch) { diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index 9da3358..1c56bf0 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -1,5 +1,7 @@ import type { PhotoSummary } from "@photoreport/contracts"; import type { EventSummary } from "@photoreport/sdk"; +import { useAuth } from "../auth.js"; +import { planLocalAutopilot } from "../offline/autopilot.js"; import { cache } from "../offline/cache.js"; import { exifDateTime, lisbonInstant, localPhoto, localPhotos, routeLocally } from "../offline/local.js"; import { localId, offlineQueue } from "../offline/queue.js"; @@ -89,6 +91,7 @@ const settingsError = (err: unknown): string => { * into the event's work folder. Failed ones stay in the ingest folder and go again with "retry" (or next start). */ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriInvoke, orgId = "") { + const { api } = useAuth(); const [status, setStatus] = useState(null); const [error, setError] = useState(null); /** An older desktop app without the FTP commands. */ @@ -168,7 +171,10 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn setCounts((c) => ({ ...c, sent: c.sent + 1 })); invoke("ftp_sent", { path: f.path, event: pinned?.title ?? (routed ? eventLabel(routed) : ""), date: pinned?.date ?? (routed ? routed.startsAt.slice(0, 10) : "") }).catch(() => {}); // Changes made to it meanwhile now go to the server's copy. - if (photo && orgId) offlineQueue(orgId).uploaded(info.sha256, photo.id); + if (photo && orgId) { + offlineQueue(orgId).uploaded(info.sha256, photo.id); + void offlineQueue(orgId).flush(api); + } localPhotos.remove(localId(info.sha256)); } else { // The upload failed. The preview stays, so it can still be culled and edited; the file stays in @@ -176,6 +182,8 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn setCounts((c) => ({ ...c, failed: c.failed + 1 })); } }; + const event = events.find((e) => e.id === eventId); + await planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {}); if (!full) { const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs }); add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info); @@ -212,7 +220,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn } })(); } - }, [add, invoke]); + }, [add, invoke, api, orgId]); const refresh = useCallback(async () => { try { diff --git a/apps/app/src/library/realtime.ts b/apps/app/src/library/realtime.ts index 1c1a426..88785c4 100644 --- a/apps/app/src/library/realtime.ts +++ b/apps/app/src/library/realtime.ts @@ -5,6 +5,14 @@ import { io } from "socket.io-client"; export type LiveState = "connecting" | "live" | "offline"; +const liveListeners = new Set<() => void>(); + +/** The library socket connected. Waiting edits go out on this, not on a timer. */ +export function onSocketLive(fn: () => void): () => void { + liveListeners.add(fn); + return () => liveListeners.delete(fn); +} + /** * Live library messages for the signed-in user's organizations (new photos from FTP, culling by colleagues, * delivery progress). Reconnects on its own and fetches a fresh token for every attempt. @@ -25,7 +33,10 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa ); }, }); - socket.on("connect", () => setState("live")); + socket.on("connect", () => { + setState("live"); + for (const fn of liveListeners) fn(); + }); socket.on("disconnect", () => setState("offline")); socket.on("connect_error", () => setState("offline")); socket.on(LIBRARY_CHANNEL, (message: LibraryMessage) => handler.current(message)); diff --git a/apps/app/src/offline/autopilot.ts b/apps/app/src/offline/autopilot.ts new file mode 100644 index 0000000..e736f53 --- /dev/null +++ b/apps/app/src/offline/autopilot.ts @@ -0,0 +1,88 @@ +import { AutopilotSettings } from "@photoreport/contracts"; +import type { ApiClient, AutopilotStyle, EventSummary } from "@photoreport/sdk"; +import { isReportage } from "../../../api/src/composition/compose.js"; +import { levelAngle, measuredValues, planFrame } from "../../../api/src/composition/planFrame.js"; +import { loadEngine } from "../develop/engine.js"; +import { isDesktop } from "../platform.js"; +import { detectPreview } from "./detectLocal.js"; +import { kv } from "./kv.js"; +import { localId, offlineQueue } from "./queue.js"; + +/** + * The same autopilot edit the server would make, on the preview already on this computer, before it is uploaded. + * If the model or the engine isn't available, nothing is queued and the server edits the photo as before. + */ +export async function planLocalAutopilot(args: { + api: ApiClient; + orgId: string; + event: EventSummary | undefined; + sha256: string; + preview: ArrayBuffer; + width: number; + height: number; + iso?: number | null; +}): Promise { + if (!isDesktop() || !args.orgId || !args.event?.autopilot) return; + const settings = AutopilotSettings.parse(args.event.autopilot); + if (!settings.enabled) return; + const reportage = isReportage(args.event); + const [measured, detections, style] = await Promise.all([ + measure(args.preview), + detectPreview(args.api, args.orgId, args.preview), + styleFor(args.api, args.orgId, args.event.venue), + ]); + // Both have to be here. A crop without the tone, or the reverse, would stop the server doing the rest. + if (!measured || !detections) return; + const angle = levelAngle(measured.angle, settings.level); + const values = measuredValues(measured.values, settings, reportage, args.iso ?? null, style?.offsets ?? {}); + const planned = planFrame({ + detections, + width: args.width, + height: args.height, + reportage, + values, + angle, + cropFactor: style?.cropFactor ?? null, + settings, + }); + if (!planned.ops.length) return; + const queue = offlineQueue(args.orgId); + const photoId = localId(args.sha256); + for (const command of planned.ops) queue.enqueueEdit(photoId, command); +} + +async function measure(bytes: ArrayBuffer): Promise<{ values: Record; angle: number | null } | null> { + try { + const engine = await loadEngine(); + const photo = new engine.Photo(new Uint8Array(bytes), 1024); + try { + const wb = JSON.parse(photo.autoWb()) as Record; + const settings = engine.apply(engine.defaultSettings(), JSON.stringify({ command: "develop.set", params: { values: wb } })); + const tone = JSON.parse(photo.autoTone(settings)) as Record; + let angle: number | null = null; + if (photo.autoLevelScene) { + const scene = JSON.parse(photo.autoLevelScene()) as Record; + if (typeof scene["crop.angle"] === "number") angle = scene["crop.angle"]; + } else { + const level = JSON.parse(photo.autoLevel(settings)) as Record; + if (typeof level["crop.angle"] === "number") angle = level["crop.angle"]; + } + return { values: { ...wb, ...tone }, angle }; + } finally { + photo.free(); + } + } catch { + return null; + } +} + +async function styleFor(api: ApiClient, orgId: string, venue: string | null): Promise { + const key = `style:${orgId}:${venue ?? ""}`; + try { + const res = await api.autopilotStyle(orgId, venue); + await kv.set(key, res.style); + return res.style; + } catch { + return (await kv.get(key)) ?? null; + } +} diff --git a/apps/app/src/offline/cache.ts b/apps/app/src/offline/cache.ts index b0b6487..9cbdf4c 100644 --- a/apps/app/src/offline/cache.ts +++ b/apps/app/src/offline/cache.ts @@ -88,6 +88,16 @@ export async function cachedImage(url: string): Promise { * The image to show for `url`, through the cache on the desktop app (so it shows again without a network); in the * browser, the URL itself. */ +/** Keep thumbnails and 2048 px previews on disk. Does not request originals. */ +export function warmImages(urls: string[]): void { + for (const url of urls) { + if (!url || url.startsWith("blob:") || url.startsWith("data:")) continue; + void cachedImage(url).then((src) => { + if (src?.startsWith("blob:")) URL.revokeObjectURL(src); + }); + } +} + export function useCachedImage(url: string | null, enabled: boolean): string | null { const [src, setSrc] = useState(enabled ? null : url); useEffect(() => { diff --git a/apps/app/src/offline/detectLocal.ts b/apps/app/src/offline/detectLocal.ts new file mode 100644 index 0000000..053341c --- /dev/null +++ b/apps/app/src/offline/detectLocal.ts @@ -0,0 +1,105 @@ +import type { Detections } from "../../../api/src/composition/compose.js"; +import { YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf, PERSON, BALL } from "../../../api/src/composition/yolox.js"; +import type { ApiClient } from "@photoreport/sdk"; +import { kv } from "./kv.js"; + +const MODEL_KEY = "model:yolox_s.onnx"; + +type Session = { + inputNames: readonly string[]; + outputNames: readonly string[]; + run(feeds: Record): Promise>; +}; + +let loading: Promise | null = null; + +async function modelBytes(api: ApiClient, orgId: string): Promise { + const hit = await kv.get(MODEL_KEY); + if (hit && typeof hit.arrayBuffer === "function" && hit.size > 1000) return hit.arrayBuffer(); + const token = await api.realtimeToken(); + const res = await fetch(api.absolute(`/v1/orgs/${orgId}/models/yolox_s.onnx`), { headers: { authorization: `Bearer ${token}` } }); + if (!res.ok) throw new Error("model"); + const buf = await res.arrayBuffer(); + await kv.set(MODEL_KEY, new Blob([buf])); + return buf; +} + +async function sessionFor(api: ApiClient, orgId: string): Promise { + loading ??= (async () => { + const ort = await import("onnxruntime-web/wasm"); + ort.env.wasm.numThreads = 1; + const bytes = await modelBytes(api, orgId); + return ort.InferenceSession.create(bytes, { executionProviders: ["wasm"] }) as Promise; + })(); + loading.catch(() => { + loading = null; + }); + return loading; +} + +function canvasOf(width: number, height: number): OffscreenCanvas | HTMLCanvasElement { + if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height); + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; +} + +function context2d(canvas: OffscreenCanvas | HTMLCanvasElement): OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D { + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + if (!ctx) throw new Error("canvas"); + return ctx as OffscreenCanvasRenderingContext2D; +} + +/** People and the ball, same boxes the server's YOLOX decode produces from this tensor. Null when the model isn't here. */ +export async function detectPreview(api: ApiClient, orgId: string, jpeg: ArrayBuffer): Promise { + let bmp: ImageBitmap; + try { + bmp = await createImageBitmap(new Blob([jpeg], { type: "image/jpeg" }), { imageOrientation: "from-image" }); + } catch { + return null; + } + try { + const width = bmp.width; + const height = bmp.height; + const scale = Math.min(YOLOX_SIZE / width, YOLOX_SIZE / height); + const rw = Math.max(1, Math.round(width * scale)); + const rh = Math.max(1, Math.round(height * scale)); + const box = canvasOf(YOLOX_SIZE, YOLOX_SIZE); + const ctx = context2d(box); + ctx.fillStyle = "rgb(114,114,114)"; + ctx.fillRect(0, 0, YOLOX_SIZE, YOLOX_SIZE); + ctx.imageSmoothingEnabled = true; + ctx.imageSmoothingQuality = "high"; + ctx.drawImage(bmp, 0, 0, rw, rh); + const px = ctx.getImageData(0, 0, YOLOX_SIZE, YOLOX_SIZE).data; + const plane = YOLOX_SIZE * YOLOX_SIZE; + const input = new Float32Array(3 * plane); + for (let i = 0; i < plane; i++) { + input[i] = px[i * 4 + 2]!; + input[plane + i] = px[i * 4 + 1]!; + input[2 * plane + i] = px[i * 4]!; + } + const session = await sessionFor(api, orgId); + const ort = await import("onnxruntime-web/wasm"); + const tensor = new ort.Tensor("float32", input, [1, 3, YOLOX_SIZE, YOLOX_SIZE]); + const out = await session.run({ [session.inputNames[0]!]: tensor }); + const raw = out[session.outputNames[0]!]!.data; + const all = decodeYolox(raw, scale, width, height); + const people = nmsKeep(all.filter((d) => d.cls === PERSON)); + const greyW = 1024; + const greyH = Math.max(1, Math.round(height * (greyW / width))); + const greyCanvas = canvasOf(greyW, greyH); + const gctx = context2d(greyCanvas); + gctx.drawImage(bmp, 0, 0, greyW, greyH); + const rgba = gctx.getImageData(0, 0, greyW, greyH).data; + const grey = new Uint8Array(greyW * greyH); + for (let i = 0; i < grey.length; i++) grey[i] = Math.round(0.299 * rgba[i * 4]! + 0.587 * rgba[i * 4 + 1]! + 0.114 * rgba[i * 4 + 2]!); + sharpnessOf(grey, greyW, greyH, people); + return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)) }; + } catch { + return null; + } finally { + bmp.close(); + } +} diff --git a/apps/app/src/offline/plan.test.ts b/apps/app/src/offline/plan.test.ts new file mode 100644 index 0000000..727e5d7 --- /dev/null +++ b/apps/app/src/offline/plan.test.ts @@ -0,0 +1,102 @@ +import { AutopilotSettings } from "@photoreport/contracts"; +import type { ApiClient } from "@photoreport/sdk"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { decodeYolox, nmsKeep, PERSON, YOLOX_SIZE } from "../../../api/src/composition/yolox.js"; +import { planFrame } from "../../../api/src/composition/planFrame.js"; +import { syncDevelopCommand } from "../develop/copySettings.js"; +import { OfflineQueue } from "./queue.js"; +import { matchRoster } from "./roster.js"; + +function memoryStore() { + const m = new Map(); + return { + get: (k: string) => m.get(k) ?? null, + set: (k: string, v: string) => void m.set(k, v), + remove: (k: string) => void m.delete(k), + keys: () => [...m.keys()], + }; +} + +describe("shared detector decode", () => { + it("reads one person from a YOLOX head and drops a weak neighbour", () => { + const raw = new Float32Array(8400 * 85); + const cell = 10 * (YOLOX_SIZE / 8) + 10; + const o = cell * 85; + raw[o] = 0; + raw[o + 1] = 0; + raw[o + 2] = Math.log(4); + raw[o + 3] = Math.log(8); + raw[o + 4] = 0.9; + raw[o + 5 + PERSON] = 0.9; + const found = decodeYolox(raw, 1, 640, 480); + expect(found).toHaveLength(1); + expect(found[0]?.cls).toBe(PERSON); + const kept = nmsKeep(found); + expect(kept).toHaveLength(1); + expect(kept[0]?.score).toBeCloseTo(0.81); + expect(kept[0]!.x1).toBeGreaterThan(kept[0]!.x0); + }); +}); + +describe("sync chosen groups", () => { + it("writes the chosen controls and leaves the crop for its own command", () => { + const cmd = syncDevelopCommand(["basic"], (id) => (id === "light.exposure" ? 0.4 : 0)); + expect(cmd?.command).toBe("develop.set"); + if (cmd?.command !== "develop.set") return; + expect(cmd.params.values["light.exposure"]).toBe(0.4); + expect(cmd.params.values["crop.angle"]).toBeUndefined(); + expect(syncDevelopCommand(["crop"], () => 1)).toBeNull(); + }); +}); + +describe("develop edits waiting here", () => { + let store: ReturnType; + beforeEach(() => (store = memoryStore())); + + it("sends a queued edit and clears it", async () => { + const q = new OfflineQueue("o1", store); + q.enqueueEdit("p9", { command: "develop.set", params: { values: { "light.exposure": 1 } } }); + expect(q.size).toBe(1); + const posted: unknown[] = []; + const api = { + postEdits: vi.fn(async (photoId: string, body: unknown) => { + posted.push({ photoId, body }); + return { developSeq: 1, ops: [] }; + }), + } as unknown as ApiClient; + await q.flush(api); + expect(posted).toEqual([{ photoId: "p9", body: { clientId: "offline-queue", ops: [{ opId: expect.any(String), command: { command: "develop.set", params: { values: { "light.exposure": 1 } } } }] } }]); + expect(q.size).toBe(0); + }); +}); + +describe("squad names on this computer", () => { + it("names nobody when the event is not a game, and a sure name when the face matches the squad", () => { + expect(matchRoster({ game: false, model: null, people: [] }, [[1, 0]]).people).toEqual([null]); + const face = [1, 0, 0]; + const named = matchRoster( + { game: true, model: "auraface-v1", people: [{ id: "a", name: "Ana", club: null, number: "7", model: "auraface-v1", embedding: face }] }, + [face], + ); + expect(named.roster).toBe(1); + expect(named.people[0]).toMatchObject({ id: "a", name: "Ana", level: "strong" }); + }); +}); + +describe("the same frame the server would plan", () => { + it("sets tone and a crop for a player in a match", () => { + const settings = AutopilotSettings.parse({ enabled: true }); + const planned = planFrame({ + detections: { width: 6000, height: 4000, people: [{ x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.92, score: 0.9, sharpness: 1 }], balls: [{ x0: 0.55, y0: 0.7, x1: 0.6, y1: 0.76, score: 0.8 }] }, + width: 6000, + height: 4000, + reportage: false, + values: { "wb.temp": 5200, "light.exposure": 0.2 }, + angle: 0, + cropFactor: null, + settings, + }); + expect(planned.ops.map((op) => op.command)).toContain("develop.set"); + expect(planned.ops.map((op) => op.command)).toContain("crop.set"); + }); +}); diff --git a/apps/app/src/offline/queue.ts b/apps/app/src/offline/queue.ts index 4194300..23bdd9a 100644 --- a/apps/app/src/offline/queue.ts +++ b/apps/app/src/offline/queue.ts @@ -1,4 +1,4 @@ -import type { PhotoPatch } from "@photoreport/contracts"; +import type { EditCommand, PhotoPatch } from "@photoreport/contracts"; import { ApiError, type ApiClient } from "@photoreport/sdk"; /** @@ -64,7 +64,7 @@ const OUTBOX = "pr:outbox:"; export class OfflineQueue { private ops: QueuedOp[]; private listeners = new Set<() => void>(); - private running: Promise | null = null; + private running: Promise = Promise.resolve(); constructor( readonly orgId: string, @@ -110,6 +110,22 @@ export class OfflineQueue { this.save(); } + /** A develop command for one photo, including one that is still only on this computer. Sent with the queue. */ + enqueueEdit(photoId: string, command: EditCommand): void { + const key = `${OUTBOX}${photoId}`; + let ops: { opId: string; command: EditCommand }[] = []; + try { + const raw = this.store.get(key); + const parsed = raw ? (JSON.parse(raw) as unknown) : []; + if (Array.isArray(parsed)) ops = parsed as { opId: string; command: EditCommand }[]; + } catch { + ops = []; + } + ops.push({ opId: crypto.randomUUID(), command }); + this.store.set(key, JSON.stringify(ops)); + for (const fn of this.listeners) fn(); + } + /** The server id of a photo first seen here, once it is uploaded. */ serverId(id: string): string | null { if (!isLocalId(id)) return id; @@ -152,10 +168,13 @@ export class OfflineQueue { * refuses for good. Changes to a photo not uploaded yet wait, and so do later changes to that photo. */ flush(api: ApiClient): Promise { - this.running ??= this.doFlush(api).finally(() => { - this.running = null; - }); - return this.running; + // A second flush while one is running (the next photo finished uploading) has to run after, not be dropped. + const next = this.running.then(() => this.doFlush(api)); + this.running = next.then( + () => undefined, + () => undefined, + ); + return next; } private async doFlush(api: ApiClient): Promise { diff --git a/apps/app/src/offline/roster.ts b/apps/app/src/offline/roster.ts new file mode 100644 index 0000000..e74768c --- /dev/null +++ b/apps/app/src/offline/roster.ts @@ -0,0 +1,53 @@ +import type { FaceIdentify, FaceRoster } from "@photoreport/sdk"; +import type { ApiClient } from "@photoreport/sdk"; +import { cosine, POSSIBLE_BELOW, THRESHOLDS } from "../../../api/src/faces/math.js"; +import { isNetworkError } from "./queue.js"; +import { kv } from "./kv.js"; + +const keyOf = (orgId: string, eventId: string) => `roster:${orgId}:${eventId}`; + +/** The squad saved for this game. Null when it was never downloaded. */ +export function savedRoster(orgId: string, eventId: string): Promise { + return kv.get(keyOf(orgId, eventId)).then((v) => v ?? null); +} + +/** + * Download the squad when the event is a game (it has an opponent). A training or a reportage stores + * `{ game: false }` so we don't ask again, and we never keep the rest of the archive. + */ +export async function ensureRoster(api: ApiClient, orgId: string, eventId: string, away: string | null | undefined): Promise { + if (!away?.trim()) { + const empty: FaceRoster = { game: false, model: null, people: [] }; + await kv.set(keyOf(orgId, eventId), empty); + return empty; + } + const cached = await savedRoster(orgId, eventId); + try { + const fresh = await api.faceRoster(orgId, eventId); + await kv.set(keyOf(orgId, eventId), fresh); + return fresh; + } catch (err) { + if (isNetworkError(err)) return cached; + throw err; + } +} + +/** Name faces from the saved squad only. Same cosine and the same thresholds as the server. */ +export function matchRoster(pack: FaceRoster | null, embeddings: number[][], model = "auraface-v1"): FaceIdentify { + if (!pack?.game) return { roster: null, people: embeddings.map(() => null) }; + const threshold = THRESHOLDS[model] ?? { match: 0.5, group: 0.55, margin: 0.05 }; + const floor = threshold.match - POSSIBLE_BELOW; + const people = pack.people.filter((p) => p.embedding.length && (!p.model || p.model === model)); + return { + roster: people.length, + people: embeddings.map((embedding) => { + let best: { id: string; name: string; club: string | null; number: string | null; score: number } | null = null; + for (const person of people) { + const score = cosine(embedding, person.embedding); + if (score >= floor && (!best || score > best.score)) best = { id: person.id, name: person.name, club: person.club, number: person.number, score }; + } + if (!best) return null; + return { id: best.id, name: best.name, club: best.club, number: best.number, level: best.score >= threshold.match ? "strong" : "possible" }; + }), + }; +} diff --git a/apps/app/src/offline/sync.ts b/apps/app/src/offline/sync.ts index 0ae29ce..f9a46bf 100644 --- a/apps/app/src/offline/sync.ts +++ b/apps/app/src/offline/sync.ts @@ -1,27 +1,31 @@ import type { PhotoPatch } from "@photoreport/contracts"; import type { ApiClient } from "@photoreport/sdk"; import { useEffect, useSyncExternalStore } from "react"; +import { onSocketLive } from "../library/realtime.js"; import { localPhotos } from "./local.js"; import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./queue.js"; -/** How often waiting changes are tried while there are some (and whenever the system says the network is back). */ -const EVERY_MS = 10_000; - -/** Sends the changes kept while offline, in the background, for as long as the organization is open. */ +/** + * Sends what was kept while the socket was down, the moment it is live again. A change made while the socket is + * already live goes out in `patchPhotos` itself. The socket is the clock: down, keep it; live, send it. + */ export function useOfflineSync(api: ApiClient, orgId: string): void { useEffect(() => { if (!orgId) return; const queue = offlineQueue(orgId); - const tick = () => { - if (queue.size) void queue.flush(api).catch(() => {}); - }; - tick(); - const timer = setInterval(tick, EVERY_MS); - window.addEventListener("online", tick); - return () => { - clearInterval(timer); - window.removeEventListener("online", tick); - }; + return onSocketLive(() => { + let tries = 0; + const send = () => { + void queue.flush(api).then(() => { + // Still waiting (the link dropped mid-send): try again while this connection stays up. + if (queue.size > 0 && tries < 5) { + tries += 1; + window.setTimeout(send, 1500); + } + }); + }; + send(); + }); }, [api, orgId]); } diff --git a/apps/app/src/pages/DevelopPage.tsx b/apps/app/src/pages/DevelopPage.tsx index da655b9..ffc1529 100644 --- a/apps/app/src/pages/DevelopPage.tsx +++ b/apps/app/src/pages/DevelopPage.tsx @@ -6,14 +6,16 @@ import { useAuth } from "../auth.js"; import { type EngineModule, loadEngine } from "../develop/engine.js"; import { DevelopPanels, Section, Slider } from "../develop/Panels.js"; import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/session.js"; +import { SyncSettingsButton } from "../develop/SyncSettings.js"; +import { commandsFrom, queueSync } from "../develop/copySettings.js"; import { clampUnit, constrainRotated, fitAspect, GUIDES, type Guide, rotateAspect } from "../develop/crop.js"; import { engineAuto, Viewer } from "../develop/Viewer.js"; import { IptcInfo } from "../library/IptcInfo.js"; import { activePhoto, savedFilter, setActivePhoto } from "../library/active.js"; import { cache } from "../offline/cache.js"; import { localPhotos } from "../offline/local.js"; -import { isNetworkError } from "../offline/queue.js"; -import { patchPhotos } from "../offline/sync.js"; +import { isNetworkError, offlineQueue } from "../offline/queue.js"; +import { patchPhotos, useOfflineSync } from "../offline/sync.js"; import { applyPatch, isMac, type LibraryFilter, matchesFilter, patchForKey, pmPatchForKey } from "../library/store.js"; import { t } from "../i18n.js"; import { useLibraryLive } from "../library/realtime.js"; @@ -81,9 +83,12 @@ const isTyping = (target: EventTarget | null) => export function DevelopPage() { const { api, organization, role, me } = useAuth(); const orgId = organization?.id ?? ""; + useOfflineSync(api, orgId); const { photoId } = useParams(); const navigate = useNavigate(); const [photos, setPhotos] = useState([]); + const [selected, setSelected] = useState>(new Set()); + const selectAll = useRef(() => {}); const [engine, setEngine] = useState("loading"); const [session, setSession] = useState(null); const [dragging, setDragging] = useState(false); @@ -157,6 +162,11 @@ export function DevelopPage() { }, [withLocal, filter]); // eslint-disable-line react-hooks/exhaustive-deps const current = photos.find((p) => p.id === photoId) ?? null; + selectAll.current = () => setSelected(new Set(photos.map((p) => p.id))); + useEffect(() => { + if (!current) return; + setSelected((prev) => (prev.has(current.id) ? prev : new Set([current.id]))); + }, [current?.id]); // Opened from the module link (no photo in the address): the active photo, the one you were on. useEffect(() => { if (photoId || !photos.length) return; @@ -205,7 +215,10 @@ export function DevelopPage() { const live = useLibraryLive(api, onMessage); // Reconnected: anything sent meanwhile is fetched in order. useEffect(() => { - if (live === "live" && session?.loaded) void session.catchUp(); + if (live === "live" && session?.loaded) { + void session.catchUp(); + void session.flush(); + } }, [live, session]); const autoAllRef = useRef<() => Promise>(async () => {}); @@ -244,6 +257,12 @@ export function DevelopPage() { useEffect(() => { const onKey = (e: KeyboardEvent) => { if (isTyping(e.target)) return; + if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "a") { + e.preventDefault(); + window.getSelection()?.removeAllRanges(); + selectAll.current(); + return; + } // Arrows move a focused slider, not the photo. if (e.target instanceof HTMLInputElement && e.target.type === "range" && e.key.startsWith("Arrow")) return; const mod = e.metaKey || e.ctrlKey; @@ -524,7 +543,7 @@ export function DevelopPage() { const clip = prefs.get(CLIPBOARD); return ( -
+
@@ -718,6 +737,21 @@ export function DevelopPage() { > {t.dev.copy} + {current && selected.size > 1 && ( + id !== current.id).length} + disabled={!canEdit || !session?.loaded} + onApply={async (modules) => { + if (!session?.loaded || !current) return; + const commands = commandsFrom(modules, session.settings, (id) => session.value(id)); + const ids = [...selected].filter((id) => id !== current.id); + if (!commands.length || !ids.length) return; + queueSync(orgId, ids, commands); + await offlineQueue(orgId).flush(api); + setNote(t.dev.synced(ids.length)); + }} + /> + )} + /> )} Result { + values_json( + self.source + .auto_level_scene() + .map(|d| ("crop.angle", d)) + .into_iter() + .collect(), + ) + } + /// Automatic white balance: `{"wb.temp": .., "wb.tint": ..}`. #[wasm_bindgen(js_name = autoWb)] pub fn auto_wb(&self) -> Result { diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index a6cb157..6de2519 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, FaceIdentify, CloudFolderSummary, CloudSource, CloudTreeFolder, 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, FaceRoster, CloudFolderSummary, CloudSource, CloudTreeFolder, 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 @@ -739,6 +739,11 @@ export class ApiClient { return this.request("POST", `/v1/orgs/${orgId}/faces/identify`, input); } + /** Squad embeddings for one game. Empty when the event has no opponent: the full archive stays on the server. */ + faceRoster(orgId: string, eventId: string) { + return this.request("GET", `/v1/orgs/${orgId}/events/${eventId}/face-roster`); + } + /** * 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 f2880bc..c9409ba 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -499,6 +499,13 @@ export interface CardScan { }[]; } +/** The squad of one game, cached on the desktop. `game` is false when the event has no opponent. */ +export interface FaceRoster { + game: boolean; + model: string | null; + people: { id: string; name: string; club: string | null; number: string | null; model: string | null; embedding: number[] }[]; +} + /** 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. */ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6bf7d0f..2ba78b2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -156,6 +156,9 @@ importers: '@tauri-apps/plugin-opener': specifier: ^2.7.1 version: 2.7.1 + onnxruntime-web: + specifier: 1.29.0 + version: 1.29.0 qrcode: specifier: 1.5.4 version: 1.5.4 @@ -1022,6 +1025,33 @@ packages: react: ^18.0.0 || ^19.0.0 react-dom: ^18.0.0 || ^19.0.0 + '@protobufjs/aspromise@1.1.2': + resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} + + '@protobufjs/base64@1.1.2': + resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==} + + '@protobufjs/codegen@2.0.5': + resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==} + + '@protobufjs/eventemitter@1.1.1': + resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==} + + '@protobufjs/fetch@1.1.1': + resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==} + + '@protobufjs/float@1.0.2': + resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==} + + '@protobufjs/path@1.1.2': + resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==} + + '@protobufjs/pool@1.1.0': + resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==} + + '@protobufjs/utf8@1.1.2': + resolution: {integrity: sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==} + '@radix-ui/primitive@1.1.3': resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==} @@ -2086,6 +2116,9 @@ packages: resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} engines: {node: '>=8'} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} + foreground-child@3.3.1: resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} engines: {node: '>=14'} @@ -2143,6 +2176,9 @@ packages: graphmatch@1.1.1: resolution: {integrity: sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg==} + guid-typescript@1.0.9: + resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==} + has-property-descriptors@1.0.2: resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} @@ -2462,6 +2498,9 @@ packages: resolution: {integrity: sha512-WjiVVB72riILz8HbYvxvmjKyE/WmkYoSfKY++axo5jAR609HQg8MwiG/HhShpTcJfmmAdzxxmB+MMST3A+SiPA==} os: [win32, darwin, linux] + onnxruntime-web@1.29.0: + resolution: {integrity: sha512-LuQlpX6MFLJZu756erwUeb1mNfoJGbs1kzDwJGNlf5RvfYMdqhcY3vNpDPK40CUV2HoWTkIj+uS0o36GFHjeYw==} + p-limit@2.3.0: resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} engines: {node: '>=6'} @@ -2558,6 +2597,9 @@ packages: pkg-types@2.3.3: resolution: {integrity: sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==} + platform@1.3.6: + resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} + pngjs@5.0.0: resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==} engines: {node: '>=10.13.0'} @@ -2613,6 +2655,10 @@ packages: proper-lockfile@4.1.2: resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==} + protobufjs@7.6.6: + resolution: {integrity: sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==} + engines: {node: '>=12.0.0'} + punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -3776,6 +3822,26 @@ snapshots: transitivePeerDependencies: - '@types/react-dom' + '@protobufjs/aspromise@1.1.2': {} + + '@protobufjs/base64@1.1.2': {} + + '@protobufjs/codegen@2.0.5': {} + + '@protobufjs/eventemitter@1.1.1': {} + + '@protobufjs/fetch@1.1.1': + dependencies: + '@protobufjs/aspromise': 1.1.2 + + '@protobufjs/float@1.0.2': {} + + '@protobufjs/path@1.1.2': {} + + '@protobufjs/pool@1.1.0': {} + + '@protobufjs/utf8@1.1.2': {} + '@radix-ui/primitive@1.1.3': {} '@radix-ui/react-compose-refs@1.1.2(@types/react@19.3.0)(react@19.3.0)': @@ -4840,6 +4906,8 @@ snapshots: locate-path: 5.0.0 path-exists: 4.0.0 + flatbuffers@25.9.23: {} + foreground-child@3.3.1: dependencies: cross-spawn: 7.0.6 @@ -4899,6 +4967,8 @@ snapshots: graphmatch@1.1.1: {} + guid-typescript@1.0.9: {} + has-property-descriptors@1.0.2: dependencies: es-define-property: 1.0.1 @@ -5187,6 +5257,15 @@ snapshots: global-agent: 4.1.3 onnxruntime-common: 1.29.0 + onnxruntime-web@1.29.0: + dependencies: + flatbuffers: 25.9.23 + guid-typescript: 1.0.9 + long: 5.3.2 + onnxruntime-common: 1.29.0 + platform: 1.3.6 + protobufjs: 7.6.6 + p-limit@2.3.0: dependencies: p-try: 2.2.0 @@ -5290,6 +5369,8 @@ snapshots: exsolve: 1.1.3 pathe: 2.0.3 + platform@1.3.6: {} + pngjs@5.0.0: {} postcss@8.5.28: @@ -5344,6 +5425,20 @@ snapshots: retry: 0.12.0 signal-exit: 3.0.7 + protobufjs@7.6.6: + dependencies: + '@protobufjs/aspromise': 1.1.2 + '@protobufjs/base64': 1.1.2 + '@protobufjs/codegen': 2.0.5 + '@protobufjs/eventemitter': 1.1.1 + '@protobufjs/fetch': 1.1.1 + '@protobufjs/float': 1.0.2 + '@protobufjs/path': 1.1.2 + '@protobufjs/pool': 1.1.0 + '@protobufjs/utf8': 1.1.2 + '@types/node': 22.20.5 + long: 5.3.2 + punycode@2.3.1: {} pure-rand@6.1.0: {}