From 906226b68efccc0a7231272eb04cd54ea20fb217 Mon Sep 17 00:00:00 2001 From: spark Date: Tue, 13 Oct 2026 00:56:58 +0100 Subject: [PATCH] Auto crop (people, ball, focus; fitted to Peter crops), Shift+A first pass, Info window (I) Faces are read again when the original replaces a desktop preview. Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW --- apps/api/src/app.ts | 2 + apps/api/src/composition/compose.ts | 171 ++++++++++++++++++++++++++++ apps/api/src/composition/detect.ts | 139 ++++++++++++++++++++++ apps/api/src/composition/routes.ts | 47 ++++++++ apps/api/src/ingest/service.ts | 7 +- apps/api/src/lib/models.ts | 10 ++ apps/api/src/library/photos.ts | 36 +++++- apps/api/src/worker.ts | 8 +- apps/api/test/compose.test.ts | 61 ++++++++++ apps/api/test/faces.test.ts | 17 +++ apps/api/test/library.test.ts | 18 +++ apps/app/src/i18n.ts | 17 ++- apps/app/src/library/IptcInfo.tsx | 165 +++++++++++++++++++++++++++ apps/app/src/pages/DevelopPage.tsx | 52 ++++++++- apps/app/src/pages/LibraryPage.tsx | 9 +- infra/faces/download-models.sh | 2 + packages/sdk/src/client.ts | 14 ++- 17 files changed, 761 insertions(+), 14 deletions(-) create mode 100644 apps/api/src/composition/compose.ts create mode 100644 apps/api/src/composition/detect.ts create mode 100644 apps/api/src/composition/routes.ts create mode 100644 apps/api/src/lib/models.ts create mode 100644 apps/api/test/compose.test.ts create mode 100644 apps/app/src/library/IptcInfo.tsx diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 34b287a..badf51d 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -16,6 +16,7 @@ import { DeliveryService } from "./delivery/service.js"; import { registerEventRoutes } from "./library/events.js"; import { registerFtpRoutes } from "./library/ftp.js"; import { registerPhotoRoutes } from "./library/photos.js"; +import { registerCompositionRoutes } from "./composition/routes.js"; import { registerUploadRoutes } from "./library/uploads.js"; import { IngestService } from "./ingest/service.js"; import { registerDevelopRoutes } from "./develop/routes.js"; @@ -91,6 +92,7 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr await registerOrgRoutes(app, { db, sessions }); await registerEventRoutes(app, { db, sessions }); await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster }); + await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT }); await registerSearchRoutes(app, { db, sessions, signer }); await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY }); const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log }); diff --git a/apps/api/src/composition/compose.ts b/apps/api/src/composition/compose.ts new file mode 100644 index 0000000..61e266a --- /dev/null +++ b/apps/api/src/composition/compose.ts @@ -0,0 +1,171 @@ +/** + * Automatic sports crop: who the photo is about and the frame around them, the way a photojournalist crops a + * first pass. Pure geometry over detections (people, balls, and how sharp each person is), so it is fast, + * testable and easy to tune. Tuned against Peter's own Lightroom crops (handball, October 2026): + * + * - The subject is who is in focus, not who is biggest: blurred players in the foreground are scenery. + * - With a ball near the subject, the ball and the sharp players contesting it come along. + * - The crop is usually two thirds of the frame (the same shape), moved to put the subject in the middle with + * room above the heads. Legs may be cut; heads and the ball may not. + * - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter. + * + * Boxes are fractions of the upright photo (0..1, y down). + */ + +export interface Box { + x0: number; + y0: number; + x1: number; + y1: number; +} + +export interface Detection extends Box { + score: number; + /** How sharp the person is, relative to the sharpest one in the photo (0..1). Absent: unknown (all equal). */ + sharpness?: number; +} + +export interface Detections { + /** Upright photo size in pixels. */ + width: number; + height: number; + people: Detection[]; + balls: Detection[]; +} + +export interface Composition { + /** The proposed crop. */ + rect: Box; + /** What the crop is built around. */ + subject: Box; + reason: "ball" | "group" | "person"; + /** People counted in the subject. */ + people: number; +} + +const MIN_PERSON = 0.4; +const MIN_BALL = 0.3; +/** Smaller people (in photo heights) are too far away to be what the photo is about. */ +const MIN_HEIGHT = 0.08; +/** Sharp enough to be part of the story (relative to the sharpest person). */ +/** Tuning, fitted to Peter's crops (exported so the evaluation script can sweep it). */ +export const TUNING = { inFocus: 0.55, usualScale: 0.72, wScale: 1.0, wFill: 0.6, wCentre: 1.2, wHead: 0.8, headAt: 0.1, wCut: 1.2 }; + +const h = (b: Box) => b.y1 - b.y0; +const w = (b: Box) => b.x1 - b.x0; +const cx = (b: Box) => (b.x0 + b.x1) / 2; +const cy = (b: Box) => (b.y0 + b.y1) / 2; +const union = (a: Box, b: Box): Box => ({ x0: Math.min(a.x0, b.x0), y0: Math.min(a.y0, b.y0), x1: Math.max(a.x1, b.x1), y1: Math.max(a.y1, b.y1) }); +const area = (b: Box) => Math.max(0, w(b)) * Math.max(0, h(b)); +function overlap(a: Box, b: Box): number { + return area({ x0: Math.max(a.x0, b.x0), y0: Math.max(a.y0, b.y0), x1: Math.min(a.x1, b.x1), y1: Math.min(a.y1, b.y1) }); +} +/** Touches the photo's left or right edge: someone only partly in the photo. */ +const atEdge = (b: Box) => b.x0 < 0.01 || b.x1 > 0.99; +const sharp = (p: Detection) => p.sharpness ?? 1; + +/** Who the photo is about. Null when there is nobody clear enough (empty pitch, distant crowd). */ +export function findSubject(d: Detections): { box: Box; reason: Composition["reason"]; people: Detection[] } | null { + const people = d.people.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT); + if (!people.length) return null; + // The main subject: in focus first, then a reasonable size, then whole in the photo. + const weight = (p: Detection) => sharp(p) ** 2 * Math.min(1, h(p) / 0.3) * (atEdge(p) ? 0.4 : 1) * (0.5 + 0.5 * p.score); + const main = people.reduce((a, b) => (weight(b) > weight(a) ? b : a)); + if (weight(main) < 0.05) return null; + const focused = people.filter((p) => sharp(p) >= TUNING.inFocus * sharp(main) && !atEdge(p)); + + // A ball in play near the subject: in the hands, at the feet, or in the air just above. + const balls = d.balls.filter((b) => b.score >= MIN_BALL && w(b) < 0.6 * h(main) && w(b) > 0.02 * h(main)); + const ball = balls.find((b) => Math.abs(cx(b) - cx(main)) <= w(main) / 2 + 0.5 * h(main) && cy(b) > main.y0 - 0.4 * h(main) && cy(b) < main.y1 + 0.1 * h(main)); + if (ball) { + // Everyone big and close to the ball is in the duel, in focus or not (the goalkeeper facing the shot). + const contest = people.filter((p) => p === main || (h(p) >= 0.6 * h(main) && Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) && overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p))); + if (!contest.includes(main)) contest.push(main); + const box = contest.reduce((u, p) => union(u, p), { x0: ball.x0, y0: ball.y0, x1: ball.x1, y1: ball.y1 }); + return { box, reason: "ball", people: contest }; + } + + // No ball: the subject and the sharp people standing with them (a duel, a celebration, a line-up). + const group: Detection[] = [main]; + let grown = true; + while (grown) { + grown = false; + for (const p of focused) { + if (group.includes(p) || h(p) < 0.6 * h(main) || h(p) > 1.7 * h(main)) continue; + const near = group.some((g) => overlap(g, p) > 0 || Math.max(g.x0, p.x0) - Math.min(g.x1, p.x1) < 0.45 * h(main)); + if (near) { + group.push(p); + grown = true; + } + } + } + const box = group.reduce((u, p) => union(u, p), { x0: main.x0, y0: main.y0, x1: main.x1, y1: main.y1 }); + return { box, reason: group.length > 1 ? "group" : "person", people: group }; +} + +/** + * The crop around the subject. `aspect` is width/height in pixels (null: the photo's own). Candidates of a few + * sizes and positions are scored; the best one wins. Null when there is no subject. + */ +export function compose(d: Detections, aspect: number | null = null): Composition | null { + const found = findSubject(d); + if (!found) return null; + const { box: s, reason, people: inSubject } = found; + const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions + const tallest = Math.max(...inSubject.map(h)); + const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p)); + const headroom = 0.04 * tallest; + // Whole bodies, feet included; only when that can't fit, down to the waist. + return frame(d, s, ratio, s.y1, headroom, tallest, others, inSubject, reason) ?? frame(d, s, ratio, s.y0 + 0.55 * tallest, headroom, tallest, others, inSubject, reason); +} + +function frame(d: Detections, s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"]): Composition | null { + void d; + const mainSharp = Math.max(...inSubject.map(sharp)); + let best: { rect: Box; cost: number } | null = null; + for (let k = 0.35; k <= 1.0001; k += 0.025) { + // k: crop height as a fraction of the frame height; the width follows the aspect. + let ch = Math.min(1, k); + let cw = ch * ratio; + if (cw > 1) { + cw = 1; + ch = cw / ratio; + } + if (cw < w(s) + 0.01 || ch < mustBottom - s.y0 + headroom) continue; + for (let i = 0; i <= 24; i++) { + const x0 = Math.min(Math.max(0, s.x1 - cw + (i / 24) * (cw - w(s))), 1 - cw); + for (let j = 0; j <= 16; j++) { + const y0 = Math.min(Math.max(0, s.y0 - headroom - (j / 16) * 0.3 * ch), 1 - ch); + const r = { x0, y0, x1: x0 + cw, y1: y0 + ch }; + if (r.x0 > s.x0 + 1e-6 || r.x1 < s.x1 - 1e-6 || r.y0 > Math.max(0, s.y0 - headroom) + 1e-6 || r.y1 < mustBottom - 1e-6) continue; + const c = cost(r, s, others, ch, tallest, mainSharp, ratio); + if (!best || c < best.cost) best = { rect: r, cost: c }; + } + } + } + if (!best) return null; + return { rect: best.rect, subject: s, reason, people: inSubject.length }; +} + +function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number): number { + let c = 0; + // Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter. + for (const p of others) { + const f = overlap(r, p) / Math.max(area(p), 1e-9); + if (f <= 0.03 || f >= 0.95) continue; + const focus = Math.min(1, sharp(p) / Math.max(mainSharp, 1e-6)); + if (focus < TUNING.inFocus) continue; + const size = Math.min(1, h(p) / tallest); + c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f)); + } + // Peter's usual crop is two thirds of the frame; bigger only when the subject needs it. + const k = Math.max(ch, w(r) / ratio); + c += TUNING.wScale * Math.abs(k - TUNING.usualScale); + // The subject fills a good part of the height (people tall in the frame). + c += TUNING.wFill * Math.max(0, 0.55 - tallest / ch); + // Centred across. + c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r)); + // Heads a little below the top. + c += TUNING.wHead * Math.abs((s.y0 - r.y0) / ch - TUNING.headAt); + return c; +} diff --git a/apps/api/src/composition/detect.ts b/apps/api/src/composition/detect.ts new file mode 100644 index 0000000..5509de2 --- /dev/null +++ b/apps/api/src/composition/detect.ts @@ -0,0 +1,139 @@ +import * as ort from "onnxruntime-node"; +import sharp from "sharp"; +import type { Detection, Detections } from "./compose.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" + +export class SubjectDetector { + private constructor(private readonly session: ort.InferenceSession) {} + + static async load(file: string): Promise { + return new SubjectDetector(await ort.InferenceSession.create(file, { intraOpNumThreads: 2 })); + } + + /** Detections in `file` (any JPEG/PNG), upright, as fractions of the photo. */ + async detect(file: string | Buffer): Promise { + const img = sharp(file).rotate(); + const meta = await img.metadata(); + const width = meta.autoOrient?.width ?? meta.width ?? 1; + const height = meta.autoOrient?.height ?? meta.height ?? 1; + const scale = Math.min(SIZE / width, SIZE / height); + const rw = Math.round(width * scale); + const rh = Math.round(height * scale); + const { data } = await sharp(file) + .rotate() + .resize(rw, rh, { fit: "fill" }) + .removeAlpha() + .extend({ right: SIZE - rw, bottom: SIZE - rh, background: { r: 114, g: 114, b: 114 } }) + .raw() + .toBuffer({ resolveWithObject: true }); + // YOLOX wants BGR, 0..255, planar. + const plane = SIZE * SIZE; + const input = new Float32Array(3 * plane); + for (let i = 0; i < plane; i++) { + input[i] = data[i * 3 + 2]!; + input[plane + i] = data[i * 3 + 1]!; + input[2 * plane + i] = data[i * 3]!; + } + const name = this.session.inputNames[0]!; + const out = await this.session.run({ [name]: new ort.Tensor("float32", input, [1, 3, SIZE, SIZE]) }); + const raw = out[this.session.outputNames[0]!]!.data as Float32Array; + const all = decode(raw, scale, width, height); + const people = nms(all.filter((d) => d.cls === PERSON)); + await addSharpness(file, people); + return { width, height, people, balls: nms(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; + * that someone is the subject. + */ +async function addSharpness(file: string | Buffer, people: Detection[]): Promise { + if (!people.length) return; + const W = 1024; + const { data, info } = await sharp(file).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)); +} diff --git a/apps/api/src/composition/routes.ts b/apps/api/src/composition/routes.ts new file mode 100644 index 0000000..022c826 --- /dev/null +++ b/apps/api/src/composition/routes.ts @@ -0,0 +1,47 @@ +import { existsSync } from "node:fs"; +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 { compose } from "./compose.js"; +import { SubjectDetector } from "./detect.js"; + +const Params = z.object({ photoId: z.uuid() }); +const Body = z.object({ aspect: z.tuple([z.number().positive(), z.number().positive()]).nullable().optional() }).default({}); + +/** + * Automatic crop (Revelar → Recorte → Auto): who the photo is about and a news crop around them, from the 2048 px + * preview. The detector loads on first use; without its model the endpoint answers 503 and the button says so. + */ +export async function registerCompositionRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; storage: LocalStorage; storageRoot: string }) { + const { db, storage } = deps; + const authenticate = requireAuth(deps.sessions); + let detector: Promise | null = null; + const load = () => { + const dir = modelsDir(deps.storageRoot); + const file = dir && join(dir, "yolox_s.onnx"); + if (!file || !existsSync(file)) return null; + detector ??= SubjectDetector.load(file).catch((err: unknown) => { + detector = null; + throw err; + }); + return detector; + }; + + app.post("/v1/photos/:photoId/auto-crop", { preHandler: authenticate }, async (req, reply) => { + const { photoId } = Params.parse(req.params); + const { aspect } = Body.parse(req.body ?? {}); + const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, sha256: true, status: true } }); + if (!photo || photo.status !== "READY") throw notFound("photo_not_found"); + await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER"); + const pending = load(); + if (!pending) return reply.code(503).send({ error: "auto_crop_unavailable" }); + const detections = await (await pending).detect(storage.resolve(storage.derivedKey(photo.organizationId, photo.sha256, "preview"))); + return { crop: compose(detections, aspect ? aspect[0] / aspect[1] : null) }; + }); +} diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 911d145..4ebe29f 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -205,7 +205,12 @@ export class IngestService { if (key !== photo.storageKey) await rm(storage.resolve(photo.storageKey), { force: true }); await storage.adopt(file, key); // Previews (thumb/preview) stay: they already show this photo. Only the stored file changes. - const updated = await db.photo.update({ where: { id: photo.id }, data: { storageKey: key, byteSize: size, originalStored: true } }); + // Faces and shirt numbers were read from the 2048 px preview: read them again from the full photo. + const org = await db.organization.findUnique({ where: { id: photo.organizationId }, select: { biometricsEnabled: true } }); + const updated = await db.photo.update({ + where: { id: photo.id }, + data: { storageKey: key, byteSize: size, originalStored: true, ...(org?.biometricsEnabled && { facesStatus: "PENDING" }) }, + }); log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview"); this.deps.broadcaster.library(photo.organizationId, { type: "original.stored", photoId: photo.id }); return { status: "ingested", photoId: photo.id, eventId: updated.eventId }; diff --git a/apps/api/src/lib/models.ts b/apps/api/src/lib/models.ts new file mode 100644 index 0000000..19ae09b --- /dev/null +++ b/apps/api/src/lib/models.ts @@ -0,0 +1,10 @@ +import { existsSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; + +/** + * Where the deploy puts the downloaded models (infra/faces/download-models.sh): next to the storage, or the + * default data folder. Null when none is there yet. + */ +export function modelsDir(storageRoot: string): string | null { + return [join(dirname(resolve(storageRoot)), "models"), "/srv/photoreport-data/models"].find((d) => existsSync(join(d, "face_detection_yunet_2023mar.onnx")) || existsSync(join(d, "yolox_s.onnx"))) ?? null; +} diff --git a/apps/api/src/library/photos.ts b/apps/api/src/library/photos.ts index 4862faf..eb798d2 100644 --- a/apps/api/src/library/photos.ts +++ b/apps/api/src/library/photos.ts @@ -1,6 +1,6 @@ import { createReadStream } from "node:fs"; import { PhotoBatchPatch } from "@photoreport/contracts"; -import { expandCodes, parseCodeList } from "@photoreport/metadata"; +import { expandCodes, IptcTemplate, parseCodeList } from "@photoreport/metadata"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { ROLE_RANK, requireAuth, requireMembership } from "../auth/guard.js"; @@ -26,6 +26,11 @@ const ListQuery = z.object({ offset: z.coerce.number().int().min(0).default(0), limit: z.coerce.number().int().min(1).max(500).default(200), }); +const IptcField = z.union([z.string().max(2000), z.array(z.string().max(200)).max(100), z.null()]); +const IptcBatch = z.object({ + ids: z.array(z.uuid()).min(1).max(1000), + set: z.partialRecord(z.enum(Object.keys(IptcTemplate.shape) as [keyof typeof IptcTemplate.shape, ...(keyof typeof IptcTemplate.shape)[]]), IptcField), +}); const FileParams = z.object({ photoId: z.uuid(), variant: z.enum(["thumb", "preview", "source", "original"]) }); const FileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(10).max(100) }); const CodeListBody = z.object({ content: z.string().max(500_000) }); @@ -96,13 +101,36 @@ export async function registerPhotoRoutes( /** The IPTC a delivery would write for this photo, with anything that needs attention. */ app.get("/v1/photos/:photoId/iptc", { preHandler: authenticate }, async (req) => { const { photoId } = PhotoParams.parse(req.params); - const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, eventId: true, embeddedIptc: true } }); + const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, eventId: true, embeddedIptc: true, iptcOverrides: true, event: { select: { iptcTemplate: true } } } }); if (!photo) throw notFound("photo_not_found"); await requireMembership(db, req, photo.organizationId, "INGESTER"); const embedded = photo.embeddedIptc ?? null; - if (!photo.eventId) return { values: {}, issues: [], embedded }; + // What the event's template says and what this photo changes (the Info window edits the latter). + const overrides = IptcTemplate.partial().parse(photo.iptcOverrides ?? {}); + const template = photo.event ? IptcTemplate.parse(photo.event.iptcTemplate) : {}; + if (!photo.eventId) return { values: {}, issues: [], embedded, overrides, template }; const result = await iptcForPhoto(db, photoId); - return { values: result?.values ?? {}, issues: result?.issues ?? [], embedded }; + return { values: result?.values ?? {}, issues: result?.issues ?? [], embedded, overrides, template }; + }); + + /** + * Photo Mechanic's Info window: IPTC fields set on one or many photos, on top of their event's template. A field + * set to null goes back to the template; fields not sent are left as they are. Variables and codes still apply. + */ + app.put("/v1/orgs/:orgId/photos/iptc", { preHandler: authenticate }, async (req) => { + const { orgId } = OrgParams.parse(req.params); + const body = IptcBatch.parse(req.body); + await requireMembership(db, req, orgId, "INGESTER"); + const photos = await db.photo.findMany({ where: { organizationId: orgId, id: { in: body.ids } }, select: { id: true, iptcOverrides: true } }); + for (const p of photos) { + const merged: Record = { ...IptcTemplate.partial().parse(p.iptcOverrides ?? {}) }; + for (const [k, v] of Object.entries(body.set)) { + if (v === null) delete merged[k]; + else merged[k] = v; + } + await db.photo.update({ where: { id: p.id }, data: { iptcOverrides: IptcTemplate.partial().parse(merged) } }); + } + return { updated: photos.length }; }); /** diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 3bf5d50..17bae88 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -3,6 +3,7 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import pino from "pino"; import { loadConfig } from "./config.js"; +import { modelsDir } from "./lib/models.js"; import { createDb } from "./db.js"; import { closeRenderer } from "./delivery/render.js"; import { SecretBox } from "./delivery/secrets.js"; @@ -32,11 +33,12 @@ const log = pino({ level: config.LOG_LEVEL, name: "worker" }); */ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); const built = (name: string) => [join(repoRoot, "target/release", name)].find((f) => existsSync(f)); -const modelsDir = [join(dirname(resolve(config.STORAGE_ROOT)), "models"), "/srv/photoreport-data/models"].find((d) => existsSync(join(d, "face_detection_yunet_2023mar.onnx"))); +const models = modelsDir(config.STORAGE_ROOT); +const faceModels = models && existsSync(join(models, "face_detection_yunet_2023mar.onnx")) ? models : undefined; config.FACES_BIN ??= built("photoreport-faces"); -config.FACES_MODELS_DIR ??= modelsDir; +config.FACES_MODELS_DIR ??= faceModels; config.RENDER_BIN ??= built("photoreport-render"); -if (!config.JERSEY_MODEL_DIR && modelsDir && existsSync(join(modelsDir, "jersey", "jersey.onnx"))) config.JERSEY_MODEL_DIR = join(modelsDir, "jersey"); +if (!config.JERSEY_MODEL_DIR && models && existsSync(join(models, "jersey", "jersey.onnx"))) config.JERSEY_MODEL_DIR = join(models, "jersey"); log.info({ faces: config.FACES_BIN ?? null, models: config.FACES_MODELS_DIR ?? null, render: config.RENDER_BIN ?? null, jersey: config.JERSEY_MODEL_DIR ?? null }, "engines"); const db = createDb(config.DATABASE_URL); const storage = new LocalStorage(config.STORAGE_ROOT); diff --git a/apps/api/test/compose.test.ts b/apps/api/test/compose.test.ts new file mode 100644 index 0000000..c9b45c9 --- /dev/null +++ b/apps/api/test/compose.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; +import { compose, type Detection, findSubject } from "../src/composition/compose.js"; + +const person = (x0: number, y0: number, x1: number, y1: number, score = 0.9): Detection => ({ x0, y0, x1, y1, score }); +const inside = (r: { x0: number; y0: number; x1: number; y1: number }, b: { x0: number; y0: number; x1: number; y1: number }) => r.x0 <= b.x0 + 1e-9 && r.y0 <= b.y0 + 1e-9 && r.x1 >= b.x1 - 1e-9 && r.y1 >= b.y1 - 1e-9; +const frame = { width: 3000, height: 2000 }; + +describe("automatic crop", () => { + it("builds the crop around the ball and the players contesting it", () => { + const a = person(0.4, 0.2, 0.5, 0.8); + const b = person(0.52, 0.22, 0.62, 0.82); + const far = person(0.05, 0.3, 0.1, 0.5); // small, behind + const ball = { x0: 0.5, y0: 0.74, x1: 0.53, y1: 0.78, score: 0.8 }; + const c = compose({ ...frame, people: [a, b, far], balls: [ball] })!; + expect(c.reason).toBe("ball"); + expect(c.people).toBe(2); + expect(inside(c.rect, a) && inside(c.rect, b) && inside(c.rect, ball)).toBe(true); + // Same shape as the photo, tighter than it. + expect(((c.rect.x1 - c.rect.x0) * 3000) / ((c.rect.y1 - c.rect.y0) * 2000)).toBeCloseTo(1.5, 2); + expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.8); + }); + + it("ignores a ball nobody is playing, and people cut by the photo's edge", () => { + const main = person(0.35, 0.15, 0.5, 0.85); + const edge = person(0.0, 0.1, 0.06, 0.9); // half out of the photo + const s = findSubject({ ...frame, people: [main, edge], balls: [{ x0: 0.9, y0: 0.1, x1: 0.92, y1: 0.13, score: 0.9 }] })!; + expect(s.reason).toBe("person"); + expect(main).toMatchObject(s.box); + }); + + it("keeps a group together, and doesn't slice a big body at the crop's edge", () => { + const a = person(0.3, 0.2, 0.42, 0.8); + const b = person(0.4, 0.22, 0.52, 0.82); + const passer = person(0.62, 0.15, 0.78, 0.95); // big, next to the group but apart + const c = compose({ ...frame, people: [a, b, passer], balls: [] })!; + expect(c.reason).toBe("group"); + const f = Math.max(0, Math.min(c.rect.x1, passer.x1) - Math.max(c.rect.x0, passer.x0)) / (passer.x1 - passer.x0); + expect(f < 0.03 || f > 0.97).toBe(true); + }); + + it("builds around who is in focus, not the biggest blurred player in front", () => { + const blurred = { ...person(0.02, 0.05, 0.3, 1.0), sharpness: 0.15 }; + const referee = { ...person(0.45, 0.25, 0.55, 0.7), sharpness: 1 }; + const c = compose({ ...frame, people: [blurred, referee], balls: [] })!; + expect(c.reason).toBe("person"); + expect(referee).toMatchObject(c.subject); + // About two thirds of the frame, with the referee in the middle. + expect(c.rect.x1 - c.rect.x0).toBeGreaterThan(0.55); + expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.85); + expect(Math.abs((c.rect.x0 + c.rect.x1) / 2 - 0.5)).toBeLessThan(0.05); + }); + + it("proposes nothing for an empty pitch or a distant crowd", () => { + expect(compose({ ...frame, people: [person(0.1, 0.4, 0.13, 0.45), person(0.5, 0.4, 0.52, 0.46)], balls: [] })).toBeNull(); + }); + + it("uses the aspect asked for", () => { + const c = compose({ ...frame, people: [person(0.4, 0.2, 0.55, 0.85)], balls: [] }, 4 / 5)!; + expect(((c.rect.x1 - c.rect.x0) * 3000) / ((c.rect.y1 - c.rect.y0) * 2000)).toBeCloseTo(0.8, 2); + }); +}); diff --git a/apps/api/test/faces.test.ts b/apps/api/test/faces.test.ts index 9c9b837..993e620 100644 --- a/apps/api/test/faces.test.ts +++ b/apps/api/test/faces.test.ts @@ -125,6 +125,23 @@ describe("faces", () => { expect(await faces.claim(5)).toEqual([id]); }); + it("reads the faces again from the original when it replaces a desktop preview", async () => { + const { orgId } = await setup(); + const user = await ctx.db.user.findFirstOrThrow(); + const original = await sharp({ create: { width: 1200, height: 800, channels: 3, background: "#345" } }).jpeg().toBuffer(); + const { createHash } = await import("node:crypto"); + const sha256 = createHash("sha256").update(original).digest("hex"); + const preview = path.join(dir, "preview.jpg"); + await writeFile(preview, await sharp(original).resize(600).jpeg().toBuffer()); + const sent = await ingest.ingest(preview, { organizationId: orgId, userId: user.id, source: "DESKTOP", originalName: "IMG_9.JPG", original: { sha256, size: original.length } }); + await drain(); + expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: sent.photoId } })).facesStatus).toBe("DONE"); + const full = path.join(dir, "IMG_9.JPG"); + await writeFile(full, original); + await ingest.ingest(full, { organizationId: orgId, userId: user.id, source: "DESKTOP", originalName: "IMG_9.JPG" }); + expect(await faces.claim(5)).toEqual([sent.photoId]); + }); + it("groups faces of the same person within an event", async () => { const { token, day1 } = await setup(); await photo("2026:09:23 21:00:00", [1, 2]); diff --git a/apps/api/test/library.test.ts b/apps/api/test/library.test.ts index dd71ed5..9e5eba8 100644 --- a/apps/api/test/library.test.ts +++ b/apps/api/test/library.test.ts @@ -222,6 +222,24 @@ describe("library", () => { }); }); + it("sets IPTC fields on several photos at once (Photo Mechanic's Info window), over the event's template", async () => { + const { orgId, admin } = await setup(); + const a = (await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#111111" })))) as { photoId: string }; + const b = (await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#222222" })))) as { photoId: string }; + const put = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/photos/iptc`, headers: bearer(admin), payload: { ids: [a.photoId, b.photoId], set: { caption: "Golo de {home}, em {city}", keywords: ["ANDEBOL", "GOLO"] } } }); + expect(put.json()).toEqual({ updated: 2 }); + const got = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${b.photoId}/iptc`, headers: bearer(admin) })).json() as { values: Record; overrides: Record; template: Record }; + expect(got.values).toMatchObject({ caption: "Golo de VSC, em Guimarães", keywords: ["ANDEBOL", "GOLO"], event: "VSC x AAAS" }); + expect(got.overrides).toEqual({ caption: "Golo de {home}, em {city}", keywords: ["ANDEBOL", "GOLO"] }); + // Back to the template for one field; the other stays. + await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/photos/iptc`, headers: bearer(admin), payload: { ids: [b.photoId], set: { caption: null } } }); + const again = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${b.photoId}/iptc`, headers: bearer(admin) })).json() as { values: Record; overrides: Record }; + expect(again.overrides).toEqual({ keywords: ["ANDEBOL", "GOLO"] }); + expect(again.values.caption).toBe("VSC x AAAS, em Guimarães, no Pavilhão Unidade Vimaranense"); + const bad = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/photos/iptc`, headers: bearer(admin), payload: { ids: [a.photoId], set: { nonsense: "x" } } }); + expect(bad.statusCode).toBe(400); + }); + it("accepts uploads from the browser into the same pipeline, live", async () => { const { orgId, foto, event } = await setup(); const form = (name: string, data: Buffer) => { diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index be63240..14bf662 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -40,7 +40,7 @@ export const t = { noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.", filter: "Filtro", filters: { all: "Todas", PICK: "Escolhidas", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas", stars: "★ 3+", noPlayers: "Sem jogador" }, - shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · E/Enter lupa · G/Esc grelha · D revelar", + shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · I informação · E/Enter lupa · G/Esc grelha · D revelar", selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`), ofTotal: (n: number, total: number) => `${n} de ${total}`, players: "Jogadores", @@ -152,6 +152,16 @@ export const t = { captured: "Captura", photographer: "Fotógrafo", deliverTo: "Entregar em", + info: { + title: "Informação (IPTC)", + count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`), + fields: { title: "Título", headline: "Título curto", caption: "Legenda", personsShown: "Pessoas", keywords: "Palavras-chave", event: "Evento", city: "Cidade", location: "Local" }, + mixed: "(vários — escreve para mudar em todas)", + empty: "(vazio)", + help: "Vazio = o modelo do evento. Variáveis: {players} {home} {away} {city} {venue} {event} {photographer}; códigos como \\v7\\. Ctrl/Cmd+Enter guarda; com Shift guarda e envia.", + now: "Legenda atual", + saveAndSend: "Guardar e enviar", + }, deliverN: (n: number) => `Entregar ${n}`, noTargets: "Sem destinos configurados.", delivered: (q: number, s: number) => (s ? `${q} na fila, ${s} ignoradas` : `${q} na fila`), @@ -358,6 +368,9 @@ export const t = { aspectOriginal: "Original", cropHelp: "A proporção escolhida fica por defeito nas fotos seguintes. Arrasta sobre a foto para desenhar o recorte; Ctrl/Cmd + arrastar move a foto dentro dele.", level: "Nivelar", + autoCropHelp: "Recorte automático à volta de quem a foto é: a bola e quem a disputa, ou o grupo principal, sem cortar corpos a meio.", + autoCropNone: "Não encontrei um assunto claro nesta foto para recortar.", + autoCropMissing: "O recorte automático ainda não está instalado neste servidor.", levelHelp: "Endireita a foto pelo horizonte ou pelas linhas verticais (como o Auto do Lightroom).", levelNone: "Não encontrei horizonte nem linhas verticais claras nesta foto: endireita com o ângulo.", flagState: "Marcação", @@ -366,7 +379,7 @@ export const t = { paste: "Colar ajustes", pasted: (n: number) => `Ajustes colados 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 · \\ antes/depois · R recortar · W conta-gotas · Z 1:1 (arrastar move) · Ctrl+Z anular", + 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) · 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/IptcInfo.tsx b/apps/app/src/library/IptcInfo.tsx new file mode 100644 index 0000000..b6b086d --- /dev/null +++ b/apps/app/src/library/IptcInfo.tsx @@ -0,0 +1,165 @@ +import type { PhotoSummary } from "@photoreport/contracts"; +import type { ApiClient, DeliveryTarget } from "@photoreport/sdk"; +import { useEffect, useRef, useState } from "react"; +import { t } from "../i18n.js"; + +/** The fields of Photo Mechanic's Info window, in its order. Lists are comma separated. */ +const FIELDS = [ + { id: "title", list: false, long: false }, + { id: "headline", list: false, long: false }, + { id: "caption", list: false, long: true }, + { id: "personsShown", list: true, long: false }, + { id: "keywords", list: true, long: false }, + { id: "event", list: false, long: false }, + { id: "city", list: false, long: false }, + { id: "location", list: false, long: false }, +] as const; +type FieldId = (typeof FIELDS)[number]["id"]; + +const show = (v: string | string[] | undefined) => (Array.isArray(v) ? v.join(", ") : (v ?? "")); +const MIXED = "\\u0000mixed"; + +/** + * Info (I): IPTC for the selected photos, on top of their event's template, with variables and codes, then + * optionally send them straight away (rendered with their edits) to a delivery target, like Photo Mechanic's + * Info window followed by Upload. + */ +export function IptcInfo(props: { api: ApiClient; orgId: string; photos: PhotoSummary[]; targets: DeliveryTarget[]; canDeliver: boolean; onClose: () => void }) { + const { api, photos } = props; + const [values, setValues] = useState>({} as Record); + const [template, setTemplate] = useState>({}); + const [preview, setPreview] = useState>({}); + const [touched, setTouched] = useState>(new Set()); + const [targetId, setTargetId] = useState(props.targets[0]?.id ?? ""); + const [state, setState] = useState<"loading" | "idle" | "saving" | "error">("loading"); + const [note, setNote] = useState(null); + const first = useRef(null); + + useEffect(() => { + let alive = true; + void (async () => { + try { + const all = await Promise.all(photos.slice(0, 60).map((p) => api.photoIptc(p.id))); + if (!alive) return; + // A field shows its value when every selected photo agrees, "(vários)" otherwise. + const common = {} as Record; + for (const f of FIELDS) { + const vals = new Set(all.map((r) => show(r.overrides?.[f.id]))); + common[f.id] = vals.size === 1 ? [...vals][0]! : MIXED; + } + setValues(common); + setTemplate(all[0]?.template ?? {}); + setPreview(all[0]?.values ?? {}); + setState("idle"); + setTimeout(() => first.current?.focus(), 0); + } catch { + if (alive) setState("error"); + } + })(); + return () => { + alive = false; + }; + }, [api, photos]); + + const save = async (send: boolean) => { + setState("saving"); + setNote(null); + try { + const set: Record = {}; + for (const f of FIELDS) { + if (!touched.has(f.id)) continue; + const v = values[f.id].trim(); + set[f.id] = v === "" ? null : f.list ? v.split(",").map((x) => x.trim()).filter(Boolean) : v; + } + const ids = photos.map((p) => p.id); + if (Object.keys(set).length) await api.setPhotosIptc(props.orgId, ids, set); + if (send && targetId) { + const r = await api.deliver(props.orgId, targetId, ids); + setNote(t.delivered(r.queued.length, r.skipped.length)); + setState("idle"); + return; + } + props.onClose(); + } catch { + setState("error"); + } + }; + + const onKey = (e: React.KeyboardEvent) => { + e.stopPropagation(); // typing here never culls or navigates + if (e.key === "Escape") props.onClose(); + if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { + e.preventDefault(); + void save(e.shiftKey); + } + }; + + const input = "w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none"; + return ( +
+
+
+ {t.info.title} + {t.info.count(photos.length)} +
+ {state === "loading" ? ( +

…

+ ) : ( +
+ {FIELDS.map((f, i) => { + const mixed = values[f.id] === MIXED; + const common = { + "aria-label": t.info.fields[f.id], + className: `${input} ${f.long ? "min-h-20 py-1.5" : "h-8"}`, + value: mixed ? "" : (values[f.id] ?? ""), + placeholder: mixed ? t.info.mixed : show(template[f.id]) || t.info.empty, + onChange: (e: React.ChangeEvent) => { + setValues({ ...values, [f.id]: e.target.value }); + setTouched(new Set(touched).add(f.id)); + }, + }; + return ( +