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
This commit is contained in:
1 parent
10406eef02
commit
906226b68e
17 files changed
+761
-14
No files matched your search
@@ -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 });
|
||||
|
||||
@@ -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<Box>((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<Box>((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;
|
||||
}
|
||||
@@ -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<SubjectDetector> {
|
||||
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<Detections> {
|
||||
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<void> {
|
||||
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));
|
||||
}
|
||||
@@ -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<SubjectDetector> | 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) };
|
||||
});
|
||||
}
|
||||
@@ -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 };
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<string, unknown> = { ...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 };
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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]);
|
||||
|
||||
@@ -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<string, unknown>; overrides: Record<string, unknown>; template: Record<string, unknown> };
|
||||
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<string, unknown>; overrides: Record<string, unknown> };
|
||||
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) => {
|
||||
|
||||
+15
-2
@@ -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",
|
||||
|
||||
@@ -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<Record<FieldId, string>>({} as Record<FieldId, string>);
|
||||
const [template, setTemplate] = useState<Record<string, string | string[]>>({});
|
||||
const [preview, setPreview] = useState<Record<string, string | string[]>>({});
|
||||
const [touched, setTouched] = useState<Set<FieldId>>(new Set());
|
||||
const [targetId, setTargetId] = useState(props.targets[0]?.id ?? "");
|
||||
const [state, setState] = useState<"loading" | "idle" | "saving" | "error">("loading");
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const first = useRef<HTMLTextAreaElement | HTMLInputElement | null>(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<FieldId, string>;
|
||||
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<string, string | string[] | null> = {};
|
||||
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 (
|
||||
<div role="dialog" aria-modal="true" aria-label={t.info.title} className="fixed inset-0 z-30 flex items-center justify-center bg-black/60 p-4" onKeyDown={onKey}>
|
||||
<div className="max-h-full w-full max-w-2xl overflow-y-auto border border-line bg-panel shadow-2xl">
|
||||
<div className="panel-head">
|
||||
<span>{t.info.title}</span>
|
||||
<span className="text-[11px] font-normal normal-case text-faint">{t.info.count(photos.length)}</span>
|
||||
</div>
|
||||
{state === "loading" ? (
|
||||
<p className="p-4 text-[12px] text-faint">…</p>
|
||||
) : (
|
||||
<div className="grid gap-3 p-4">
|
||||
{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<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
setValues({ ...values, [f.id]: e.target.value });
|
||||
setTouched(new Set(touched).add(f.id));
|
||||
},
|
||||
};
|
||||
return (
|
||||
<label key={f.id} className="grid grid-cols-[120px_1fr] items-start gap-3 max-sm:grid-cols-1">
|
||||
<span className="pt-1.5 text-[12px] text-muted">{t.info.fields[f.id]}</span>
|
||||
{f.long ? <textarea ref={i === 0 ? (first as React.Ref<HTMLTextAreaElement>) : undefined} {...common} /> : <input ref={i === 0 ? (first as React.Ref<HTMLInputElement>) : undefined} {...common} />}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
<p className="text-[11px] text-faint">{t.info.help}</p>
|
||||
{preview.caption && (
|
||||
<p className="border-l-2 border-accent pl-2 text-[12px] text-muted">
|
||||
{t.info.now}: {show(preview.caption)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{state === "error" && <p className="px-4 pb-2 text-[12px] text-danger">{t.unexpectedError}</p>}
|
||||
{note && <p className="px-4 pb-2 text-[12px] text-ok">{note}</p>}
|
||||
<div className="flex flex-wrap items-center gap-2 border-t border-line px-4 py-3">
|
||||
{props.canDeliver && props.targets.length > 0 && (
|
||||
<>
|
||||
<select aria-label={t.deliverTo} className="h-8 border border-black bg-cell px-2 text-[12px]" value={targetId} onChange={(e) => setTargetId(e.target.value)}>
|
||||
{props.targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button disabled={state !== "idle"} onClick={() => void save(true)} className="h-8 border border-black bg-cell px-3 text-[12px] disabled:opacity-40">
|
||||
{t.info.saveAndSend}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<span className="ml-auto flex gap-2">
|
||||
<button onClick={props.onClose} className="h-8 border border-black bg-cell px-3 text-[12px]">
|
||||
{t.cancel}
|
||||
</button>
|
||||
<button disabled={state !== "idle"} onClick={() => void save(false)} className="h-8 border border-black bg-accent px-3 text-[12px] text-white disabled:opacity-40">
|
||||
{t.save}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CONTROLS, DEFAULT_MODULES, type EditCommand, type LibraryMessage, type PhotoPatch, type PhotoSummary } from "@photoreport/contracts";
|
||||
import { hasRole } from "@photoreport/sdk";
|
||||
import { type DeliveryTarget, hasRole } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useAuth } from "../auth.js";
|
||||
@@ -7,6 +7,7 @@ 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 { constrainRotated, engineAuto, fitAspect, Viewer } from "../develop/Viewer.js";
|
||||
import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { applyPatch, patchForKey } from "../library/store.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
@@ -74,6 +75,8 @@ export function DevelopPage() {
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [before, setBefore] = useState(false);
|
||||
const [cropping, setCropping] = useState(false);
|
||||
const [info, setInfo] = useState(false);
|
||||
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
|
||||
const [sourceSize, setSourceSize] = useState<{ w: number; h: number } | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const strip = useRef<HTMLDivElement>(null);
|
||||
@@ -82,6 +85,10 @@ export function DevelopPage() {
|
||||
useEffect(() => {
|
||||
loadEngine().then(setEngine, () => setEngine("missing"));
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!orgId || !role || !hasRole(role, "INGESTER")) return;
|
||||
api.listDeliveryTargets(orgId).then((r) => setTargets(r.targets.filter((x) => !x.disabledAt)), () => {});
|
||||
}, [api, orgId, role]);
|
||||
|
||||
// The event (or inbox) the library has open.
|
||||
useEffect(() => {
|
||||
@@ -138,6 +145,7 @@ export function DevelopPage() {
|
||||
if (live === "live" && session?.loaded) void session.catchUp();
|
||||
}, [live, session]);
|
||||
|
||||
const autoAllRef = useRef<() => Promise<void>>(async () => {});
|
||||
// Lightroom's culling keys work here too: P pick, X reject, U unflag, 0–5 stars, 6–9 colour.
|
||||
const canCull = !!role && hasRole(role, "INGESTER");
|
||||
const flagCurrent = useCallback(
|
||||
@@ -184,6 +192,8 @@ export function DevelopPage() {
|
||||
else if (e.key === "ArrowLeft") go(-1);
|
||||
else if (e.key === "\\") setBefore((b) => !b);
|
||||
else if (!mod && !e.altKey && e.key.toLowerCase() === "g") navigate("/", { state: { focus: current?.id } });
|
||||
else if (!mod && e.shiftKey && e.key.toLowerCase() === "a" && canEdit) void autoAllRef.current();
|
||||
else if (!mod && !e.shiftKey && e.key.toLowerCase() === "i" && canCull && current) setInfo(true);
|
||||
else if (!mod && !e.altKey && patchForKey(e.key)) {
|
||||
e.preventDefault();
|
||||
flagCurrent(patchForKey(e.key)!);
|
||||
@@ -198,7 +208,7 @@ export function DevelopPage() {
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [session, go, canEdit, navigate, current?.id, flagCurrent]);
|
||||
}, [session, go, canEdit, canCull, navigate, current, flagCurrent]);
|
||||
|
||||
const settings = session?.loaded ? session.settings : null;
|
||||
const crop = useMemo(() => (settings ? cropOf(settings) : { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null }), [settings]);
|
||||
@@ -274,6 +284,26 @@ export function DevelopPage() {
|
||||
}
|
||||
}, [session, current, setAngle]);
|
||||
|
||||
// Automatic news crop around who the photo is about (people and ball found on the server), in the default aspect.
|
||||
const autoCrop = useCallback(async () => {
|
||||
if (!session?.loaded || !current || !sourceSize) return;
|
||||
const choice = cropOf(session.settings).aspect ? null : defaultAspect();
|
||||
const c0 = cropOf(session.settings);
|
||||
const aspect: [number, number] | null = c0.aspect ?? (choice === "original" || choice === null ? null : choice);
|
||||
try {
|
||||
const { crop } = await api.request<{ crop: { rect: Crop["rect"]; reason: string } | null }>("POST", `/v1/photos/${current.id}/auto-crop`, { aspect });
|
||||
if (!crop) return setNote(t.dev.autoCropNone);
|
||||
const c = cropOf(session.settings);
|
||||
const rect = constrainRotated(crop.rect, c.angle, sourceSize.w, sourceSize.h);
|
||||
session.edit({ command: "crop.set", params: { rect, angle: c.angle, aspect: c.aspect ?? (aspect ?? [sourceSize.w, sourceSize.h]) } });
|
||||
session.endGesture();
|
||||
setNote(null);
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string }).code;
|
||||
setNote(code === "auto_crop_unavailable" ? t.dev.autoCropMissing : t.unexpectedError);
|
||||
}
|
||||
}, [api, session, current, sourceSize]);
|
||||
|
||||
const autoValues = useCallback(
|
||||
async (kind: "tone" | "wb" | "pick", at?: { x: number; y: number }) => {
|
||||
if (!session?.loaded || !current) return;
|
||||
@@ -288,6 +318,15 @@ export function DevelopPage() {
|
||||
},
|
||||
[session, current],
|
||||
);
|
||||
// Shift+A: the whole first pass at once (tone, white balance, level, crop), each step undoable.
|
||||
const autoAll = useCallback(async () => {
|
||||
await autoValues("wb");
|
||||
await autoValues("tone");
|
||||
await autoLevel();
|
||||
await autoCrop();
|
||||
}, [autoValues, autoLevel, autoCrop]);
|
||||
|
||||
autoAllRef.current = autoAll;
|
||||
const endGesture = useCallback(() => {
|
||||
setDragging(false);
|
||||
session?.endGesture();
|
||||
@@ -409,6 +448,14 @@ export function DevelopPage() {
|
||||
>
|
||||
{cropping ? t.dev.cropDone : t.dev.crop}
|
||||
</button>
|
||||
<button
|
||||
disabled={!canEdit || !session?.loaded || !sourceSize}
|
||||
onClick={() => void autoCrop()}
|
||||
title={t.dev.autoCropHelp}
|
||||
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
|
||||
>
|
||||
{t.dev.auto}
|
||||
</button>
|
||||
<span className="text-[11px] text-faint">{t.dev.aspect}</span>
|
||||
</div>
|
||||
<div className="mb-2 flex flex-wrap gap-1">
|
||||
@@ -519,6 +566,7 @@ export function DevelopPage() {
|
||||
))}
|
||||
</div>
|
||||
<div className="border-t border-line bg-raised px-3 py-1 text-[11px] text-faint">{t.dev.shortcuts}</div>
|
||||
{info && current && <IptcInfo api={api} orgId={orgId} photos={[current]} targets={targets} canDeliver={!!role && hasRole(role, "INGESTER")} onClose={() => setInfo(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { EventsPanel } from "../library/EventsPanel.js";
|
||||
import { FacesView } from "../library/FacesView.js";
|
||||
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
|
||||
import { InfoPanel } from "../library/InfoPanel.js";
|
||||
import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { useIngest } from "../library/ingest.js";
|
||||
import { LocalFtpButton } from "../library/LocalFtp.js";
|
||||
@@ -32,6 +33,7 @@ export function LibraryPage() {
|
||||
const [events, setEvents] = useState<EventSummary[]>([]);
|
||||
const [inboxCount, setInboxCount] = useState(0);
|
||||
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
|
||||
const [iptcOpen, setIptcOpen] = useState(false);
|
||||
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
|
||||
const [filter, setFilter] = useState<FilterId>("all");
|
||||
const [loupe, setLoupe] = useState(false);
|
||||
@@ -150,6 +152,10 @@ export function LibraryPage() {
|
||||
}
|
||||
if ((e.key === "Enter" || e.key.toLowerCase() === "e") && focus) return setLoupe(true);
|
||||
if (e.key.toLowerCase() === "g") return setLoupe(false);
|
||||
if (e.key.toLowerCase() === "i" && selection.length && canCull) {
|
||||
e.preventDefault();
|
||||
return setIptcOpen(true);
|
||||
}
|
||||
if (e.key.toLowerCase() === "d" && focus) return navigate(`/develop/${focus.id}`);
|
||||
if (e.key === "Escape") return setLoupe(false);
|
||||
const change = patchForKey(e.key);
|
||||
@@ -164,7 +170,7 @@ export function LibraryPage() {
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [visibleIds, selection, focus, loupe, patch, navigate]);
|
||||
}, [visibleIds, selection, focus, loupe, patch, navigate, canCull]);
|
||||
|
||||
// Back from Develop (G): the photo that was open there is the one selected here.
|
||||
const location = useLocation();
|
||||
@@ -372,6 +378,7 @@ export function LibraryPage() {
|
||||
onPlayers={(ids, players) => patch(ids, { players })}
|
||||
/>
|
||||
|
||||
{iptcOpen && <IptcInfo api={api} orgId={orgId} photos={selection} targets={targets} canDeliver={canCull} onClose={() => setIptcOpen(false)} />}
|
||||
{creating && (
|
||||
<EventForm
|
||||
api={api}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
# - YuNet 2023mar (detector), MIT
|
||||
# - AuraFace v1 (recognition, default), Apache-2.0, 261 MB
|
||||
# - SFace 2021dec (recognition, faster), licence questions upstream; only needed with FACES_EMBEDDER=sface
|
||||
# - YOLOX-s (people and balls, for the automatic crop), Apache-2.0, 36 MB
|
||||
set -euo pipefail
|
||||
DIR="${1:-/srv/photoreport-data/models}"
|
||||
mkdir -p "$DIR"
|
||||
@@ -24,3 +25,4 @@ fetch glintr100.onnx "https://huggingface.co/fal/AuraFace-v1/resolve/af6d057c9b0
|
||||
if [[ "${WITH_SFACE:-0}" == "1" ]]; then
|
||||
fetch face_recognition_sface_2021dec.onnx "$OPENCV/face_recognition_sface/face_recognition_sface_2021dec.onnx" 0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79
|
||||
fi
|
||||
fetch yolox_s.onnx "https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.onnx" c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063
|
||||
@@ -227,7 +227,19 @@ export class ApiClient {
|
||||
}
|
||||
|
||||
photoIptc(photoId: string) {
|
||||
return this.request<{ values: Record<string, string | string[]>; issues: IptcIssue[]; embedded: Record<string, string | string[]> | null }>("GET", `/v1/photos/${photoId}/iptc`);
|
||||
return this.request<{
|
||||
values: Record<string, string | string[]>;
|
||||
issues: IptcIssue[];
|
||||
embedded: Record<string, string | string[]> | null;
|
||||
/** What this photo sets on top of its event's template (the Info window), and the template itself. */
|
||||
overrides?: Record<string, string | string[]>;
|
||||
template?: Record<string, string | string[]>;
|
||||
}>("GET", `/v1/photos/${photoId}/iptc`);
|
||||
}
|
||||
|
||||
/** Sets IPTC fields on many photos; null puts a field back to the event's template. */
|
||||
setPhotosIptc(orgId: string, ids: string[], set: Record<string, string | string[] | null>) {
|
||||
return this.request<{ updated: number }>("PUT", `/v1/orgs/${orgId}/photos/iptc`, { ids, set });
|
||||
}
|
||||
|
||||
getCodeList(orgId: string) {
|
||||
|
||||
Reference in new issue
Block a user