Autopilot: edit and pick photos as they arrive (per event), photojournalism rules
Joint-aware, resolution-aware crop; burst grouping and best-frame selection; render worker auto request. Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
1 parent
906226b68e
commit
2bc9aa7ea8
23 files changed
+943
-31
No files matched your search
@@ -0,0 +1,4 @@
|
||||
-- Autopilot: per-event settings, and per-photo queue state and result.
|
||||
ALTER TABLE "events" ADD COLUMN "autopilot" JSONB;
|
||||
ALTER TABLE "photos" ADD COLUMN "autopilot_status" "FacesStatus" NOT NULL DEFAULT 'NONE';
|
||||
ALTER TABLE "photos" ADD COLUMN "autopilot" JSONB;
|
||||
@@ -209,6 +209,8 @@ model Event {
|
||||
ingestUntil DateTime @map("ingest_until")
|
||||
/// IPTC template (packages/metadata IptcTemplate), filled for every photo of the event.
|
||||
iptcTemplate Json @map("iptc_template")
|
||||
/// Autopilot settings (contracts AutopilotSettings); null: off.
|
||||
autopilot Json?
|
||||
createdById String? @map("created_by_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
@@ -296,6 +298,10 @@ model Photo {
|
||||
embeddedIptc Json? @map("embedded_iptc")
|
||||
/// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED.
|
||||
facesStatus FacesStatus @default(NONE) @map("faces_status")
|
||||
/// Autopilot queue (docs/photo-editing-rules.md): NONE unless the event's autopilot took this photo.
|
||||
autopilotStatus FacesStatus @default(NONE) @map("autopilot_status")
|
||||
/// What the autopilot saw and did: subject, crop, angle, frame score, burst decision.
|
||||
autopilot Json? @map("autopilot")
|
||||
/// Last op-log sequence number (0: never edited).
|
||||
developSeq Int @default(0) @map("develop_seq")
|
||||
/// Develop settings replayed up to `snapshotSeq` by the render worker (LightCraft JSON); clients
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Bursts: the photos a camera fired at one moment (docs/photo-editing-rules.md §3). Frames from the same camera
|
||||
* closer than `gapMs` belong together; the best `n` of each are kept.
|
||||
*/
|
||||
|
||||
export interface Frame {
|
||||
id: string;
|
||||
capturedAt: Date | null;
|
||||
/** Camera serial (or make/model, or uploader): bursts never mix cameras. */
|
||||
camera: string;
|
||||
/** Frame score from the analysis (higher is better); null: not analysed yet. */
|
||||
score: number | null;
|
||||
}
|
||||
|
||||
/** Groups frames into bursts, in capture order. Frames without a capture time are bursts of one. */
|
||||
export function groupBursts<F extends Frame>(frames: F[], gapMs: number): F[][] {
|
||||
const byCamera = new Map<string, F[]>();
|
||||
const loose: F[][] = [];
|
||||
for (const f of frames) {
|
||||
if (!f.capturedAt) {
|
||||
loose.push([f]);
|
||||
continue;
|
||||
}
|
||||
const list = byCamera.get(f.camera) ?? [];
|
||||
list.push(f);
|
||||
byCamera.set(f.camera, list);
|
||||
}
|
||||
const bursts: F[][] = [];
|
||||
for (const list of byCamera.values()) {
|
||||
list.sort((a, b) => a.capturedAt!.getTime() - b.capturedAt!.getTime());
|
||||
let current: F[] = [];
|
||||
for (const f of list) {
|
||||
const last = current[current.length - 1];
|
||||
if (last && f.capturedAt!.getTime() - last.capturedAt!.getTime() > gapMs) {
|
||||
bursts.push(current);
|
||||
current = [];
|
||||
}
|
||||
current.push(f);
|
||||
}
|
||||
if (current.length) bursts.push(current);
|
||||
}
|
||||
return [...bursts, ...loose].sort((a, b) => (a[0]!.capturedAt?.getTime() ?? 0) - (b[0]!.capturedAt?.getTime() ?? 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* The best `n` frames of a burst: highest score first; on a near tie (within 3%), the earlier frame (usually the
|
||||
* peak of the action). Returned in capture order.
|
||||
*/
|
||||
export function bestOf<F extends Frame>(burst: F[], n: number): F[] {
|
||||
if (n <= 0) return [];
|
||||
const ranked = burst
|
||||
.map((f, i) => ({ f, i }))
|
||||
.filter((x) => x.f.score !== null)
|
||||
.sort((a, b) => {
|
||||
const sa = a.f.score!;
|
||||
const sb = b.f.score!;
|
||||
if (Math.abs(sa - sb) <= 0.03 * Math.max(sa, sb)) return a.i - b.i;
|
||||
return sb - sa;
|
||||
});
|
||||
return ranked
|
||||
.slice(0, n)
|
||||
.sort((a, b) => a.i - b.i)
|
||||
.map((x) => x.f);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import { AutopilotSettings, type EditCommand } from "@photoreport/contracts";
|
||||
import type { Db } from "../db.js";
|
||||
import type { DeliveryService } from "../delivery/service.js";
|
||||
import type { RenderEngine } from "../develop/engine.js";
|
||||
import type { DevelopService } from "../develop/service.js";
|
||||
import { type Box, compose, frameScore, minCropWidth } from "../composition/compose.js";
|
||||
import type { SubjectDetector } from "../composition/detect.js";
|
||||
import { constrainRotated, tighter } from "../composition/geometry.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { bestOf, groupBursts } from "./bursts.js";
|
||||
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
/** A burst is decided once no new frame of it has arrived for this long. */
|
||||
const BURST_SETTLE_MS = 15_000;
|
||||
/** Straightening beyond this is more likely a creative tilt than a crooked horizon: left alone. */
|
||||
const MAX_LEVEL = 5;
|
||||
const MIN_LEVEL = 0.3;
|
||||
const TONE_KEYS = ["light.exposure", "light.contrast", "light.highlights", "light.shadows", "light.whites", "light.blacks", "color.vibrance", "color.saturation"];
|
||||
const WB_KEYS = ["wb.temp", "wb.tint"];
|
||||
|
||||
export interface AutopilotRecord {
|
||||
score: number;
|
||||
reason: string | null;
|
||||
subject: Box | null;
|
||||
crop: Box | null;
|
||||
angle: number;
|
||||
/** Set when the photo's burst was decided: whether it was picked. */
|
||||
decided?: boolean;
|
||||
picked?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The autopilot (docs/photo-editing-rules.md §4): edits each photo as it arrives (white balance, tone, level,
|
||||
* crop, as ordinary undoable edits by "autopilot"), then picks the best frames of each burst and optionally
|
||||
* delivers them. Runs in the worker.
|
||||
*/
|
||||
export class AutopilotService {
|
||||
constructor(
|
||||
private readonly deps: {
|
||||
db: Db;
|
||||
storage: LocalStorage;
|
||||
broadcaster: Broadcaster;
|
||||
log: IngestLogger;
|
||||
develop: DevelopService;
|
||||
engine?: RenderEngine | undefined;
|
||||
detector: () => Promise<SubjectDetector> | null;
|
||||
deliveries?: DeliveryService | undefined;
|
||||
},
|
||||
) {}
|
||||
|
||||
async claim(limit: number): Promise<string[]> {
|
||||
if (limit <= 0) return [];
|
||||
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
|
||||
UPDATE photos SET autopilot_status = 'RUNNING', updated_at = now()
|
||||
WHERE id IN (
|
||||
SELECT id FROM photos WHERE autopilot_status = 'PENDING' AND status = 'READY'
|
||||
ORDER BY captured_at NULLS LAST, created_at LIMIT ${limit} FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id`;
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
async requeueStale(now = new Date()): Promise<number> {
|
||||
const r = await this.deps.db.photo.updateMany({
|
||||
where: { autopilotStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } },
|
||||
data: { autopilotStatus: "PENDING" },
|
||||
});
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/** Analyses and edits one claimed photo. Never throws. */
|
||||
async process(photoId: string): Promise<void> {
|
||||
const { db, storage, log, develop, engine } = this.deps;
|
||||
try {
|
||||
const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId }, include: { event: { select: { autopilot: true, createdById: true } } } });
|
||||
const settings = AutopilotSettings.parse(photo.event?.autopilot ?? {});
|
||||
if (!settings.enabled) {
|
||||
await db.photo.update({ where: { id: photoId }, data: { autopilotStatus: "NONE" } });
|
||||
return;
|
||||
}
|
||||
const preview = storage.resolve(storage.derivedKey(photo.organizationId, photo.sha256, "preview"));
|
||||
const W = photo.width ?? 3;
|
||||
const H = photo.height ?? 2;
|
||||
const ops: EditCommand[] = [];
|
||||
|
||||
// White balance and tone (a measured amount), and the level angle.
|
||||
let angle = 0;
|
||||
if (engine && (settings.tone || settings.whiteBalance || settings.level)) {
|
||||
const auto = await engine.auto(preview, null);
|
||||
const values: Record<string, number> = {};
|
||||
if (settings.whiteBalance) for (const k of WB_KEYS) if (auto.values[k] !== undefined) values[k] = auto.values[k]!;
|
||||
if (settings.tone) for (const k of TONE_KEYS) if (auto.values[k]) values[k] = Math.round(auto.values[k]! * settings.toneStrength * 100) / 100;
|
||||
if (Object.keys(values).length) ops.push({ command: "develop.set", params: { values } } as EditCommand);
|
||||
if (settings.level && auto.angle !== null && Math.abs(auto.angle) >= MIN_LEVEL && Math.abs(auto.angle) <= MAX_LEVEL) angle = auto.angle;
|
||||
}
|
||||
|
||||
// The crop around who the photo is about.
|
||||
const load = this.deps.detector();
|
||||
const detections = load ? await (await load).detect(preview) : null;
|
||||
const aspect = settings.aspect ? settings.aspect[0] / settings.aspect[1] : null;
|
||||
const composition = detections ? compose(detections, aspect, { minWidth: minCropWidth(W, H, settings.minLongEdge) }) : null;
|
||||
let crop: Box | null = null;
|
||||
if (settings.crop && composition) crop = constrainRotated(composition.rect, angle, W, H);
|
||||
else if (angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
|
||||
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } } as EditCommand);
|
||||
|
||||
if (ops.length) {
|
||||
await develop.append(photoId, photo.uploaderId ?? photo.event?.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
ops: ops.map((command, i) => ({ opId: `autopilot-${photoId}-${i}`, command })),
|
||||
});
|
||||
}
|
||||
const record: AutopilotRecord = {
|
||||
score: detections ? frameScore(detections, composition) : 0,
|
||||
reason: composition?.reason ?? null,
|
||||
subject: composition?.subject ?? null,
|
||||
crop,
|
||||
angle,
|
||||
};
|
||||
await db.photo.update({ where: { id: photoId }, data: { autopilotStatus: "DONE", autopilot: record as object } });
|
||||
log.info({ photoId, edits: ops.length, reason: record.reason }, "autopilot: photo edited");
|
||||
} catch (err) {
|
||||
log.warn({ photoId, err: (err as Error).message }, "autopilot: failed");
|
||||
await db.photo.update({ where: { id: photoId }, data: { autopilotStatus: "FAILED" } }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the best frames of each settled burst: flagged PICK (never overriding a flag someone set), the second
|
||||
* one with a slightly tighter crop for variety, and delivered when the event says so.
|
||||
*/
|
||||
async decideBursts(now = new Date()): Promise<number> {
|
||||
const { db, broadcaster, develop, log } = this.deps;
|
||||
const undecided = await db.$queryRaw<{ event_id: string }[]>`
|
||||
SELECT DISTINCT event_id FROM photos
|
||||
WHERE autopilot_status = 'DONE' AND event_id IS NOT NULL AND (autopilot->>'decided') IS NULL`;
|
||||
let picked = 0;
|
||||
for (const { event_id: eventId } of undecided) {
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, organizationId: true, autopilot: true, createdById: true } });
|
||||
if (!event) continue;
|
||||
const settings = AutopilotSettings.parse(event.autopilot ?? {});
|
||||
const busy = await db.photo.count({ where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } } });
|
||||
if (busy) continue;
|
||||
const photos = await db.photo.findMany({
|
||||
where: { eventId, autopilotStatus: "DONE" },
|
||||
select: { id: true, capturedAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, createdAt: true, flag: true, autopilot: true, width: true, height: true },
|
||||
});
|
||||
const frames = photos.map((p) => {
|
||||
const rec = p.autopilot as AutopilotRecord | null;
|
||||
return { ...p, rec, camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?", score: rec?.score ?? null };
|
||||
});
|
||||
for (const burst of groupBursts(frames, settings.burstGapSec * 1000)) {
|
||||
if (burst.every((f) => f.rec?.decided)) continue;
|
||||
// Still arriving: wait until the burst has settled.
|
||||
if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue;
|
||||
const best = bestOf(burst, settings.picksPerBurst);
|
||||
const toFlag = best.filter((f) => f.flag === "NONE").map((f) => f.id);
|
||||
if (toFlag.length) {
|
||||
await db.photo.updateMany({ where: { id: { in: toFlag } }, data: { flag: "PICK" } });
|
||||
broadcaster.library(event.organizationId, { type: "photo.updated", ids: toFlag, patch: { flag: "PICK" } });
|
||||
picked += toFlag.length;
|
||||
}
|
||||
// Variety: the second pick gets a slightly tighter frame than the first.
|
||||
const second = best[1];
|
||||
if (second?.rec?.crop && second.rec.subject && settings.crop) {
|
||||
const rect = constrainRotated(tighter(second.rec.crop, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2);
|
||||
await develop
|
||||
.append(second.id, second.uploaderId ?? event.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
ops: [{ opId: `autopilot-${second.id}-variant`, command: { command: "crop.set", params: { rect, angle: second.rec.angle, aspect: settings.aspect ?? [second.width ?? 3, second.height ?? 2] } } as EditCommand }],
|
||||
})
|
||||
.catch((err: unknown) => log.warn({ err }, "autopilot: variant crop failed"));
|
||||
}
|
||||
const pickedIds = new Set(best.map((f) => f.id));
|
||||
for (const f of burst) {
|
||||
await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } });
|
||||
}
|
||||
if (settings.deliverTargetId && toFlag.length && this.deps.deliveries && event.createdById) {
|
||||
await this.deps.deliveries
|
||||
.enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: toFlag, again: false, requestedById: event.createdById })
|
||||
.catch((err: unknown) => log.warn({ err }, "autopilot: delivery not queued"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
}
|
||||
|
||||
/** Polls the autopilot queue and settles bursts. */
|
||||
export class AutopilotWorker {
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private inFlight = 0;
|
||||
private stopped = false;
|
||||
private lastDecide = 0;
|
||||
|
||||
constructor(
|
||||
private readonly service: AutopilotService,
|
||||
private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger },
|
||||
) {}
|
||||
|
||||
start(): void {
|
||||
void this.service.requeueStale();
|
||||
const tick = async () => {
|
||||
try {
|
||||
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
|
||||
for (const id of ids) {
|
||||
this.inFlight++;
|
||||
void this.service.process(id).finally(() => {
|
||||
this.inFlight--;
|
||||
});
|
||||
}
|
||||
if (Date.now() - this.lastDecide > 5000) {
|
||||
this.lastDecide = Date.now();
|
||||
await this.service.decideBursts();
|
||||
}
|
||||
} catch (err) {
|
||||
this.opts.log.warn({ err }, "autopilot: poll failed");
|
||||
}
|
||||
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
|
||||
};
|
||||
this.timer = setTimeout(tick, 0);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ 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;
|
||||
/** The same measure, absolute (variance of the Laplacian at 1024 px): compares frames of a burst. */
|
||||
focus?: number;
|
||||
}
|
||||
|
||||
export interface Detections {
|
||||
@@ -47,9 +49,20 @@ 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 };
|
||||
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, wJoint: 0.8 };
|
||||
|
||||
/**
|
||||
* Where the joints of a standing person roughly are, as fractions of their box from the top (neck, hips, knees,
|
||||
* ankles). A crop edge across a body should fall between them, mid-limb, never on one (docs/photo-editing-rules.md).
|
||||
*/
|
||||
const JOINTS = [0.17, 0.53, 0.74, 0.95];
|
||||
const JOINT_BAND = 0.035;
|
||||
|
||||
export interface ComposeOptions {
|
||||
/** Narrowest crop allowed, as a fraction of the photo's width (from the delivery's minimum resolution). */
|
||||
minWidth?: number;
|
||||
}
|
||||
|
||||
const h = (b: Box) => b.y1 - b.y0;
|
||||
const w = (b: Box) => b.x1 - b.x0;
|
||||
@@ -107,7 +120,7 @@ export function findSubject(d: Detections): { box: Box; reason: Composition["rea
|
||||
* 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 {
|
||||
export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null {
|
||||
const found = findSubject(d);
|
||||
if (!found) return null;
|
||||
const { box: s, reason, people: inSubject } = found;
|
||||
@@ -116,11 +129,17 @@ export function compose(d: Detections, aspect: number | null = null): Compositio
|
||||
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);
|
||||
const minWidth = opts.minWidth ?? 0;
|
||||
return frame(s, ratio, s.y1, headroom, tallest, others, inSubject, reason, minWidth) ?? frame(s, ratio, s.y0 + 0.55 * tallest, headroom, tallest, others, inSubject, reason, minWidth);
|
||||
}
|
||||
|
||||
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;
|
||||
/** Recommended narrowest crop for a photo `width` px wide when deliveries need `minLongEdge` px (and never below a third). */
|
||||
export function minCropWidth(width: number, height: number, minLongEdge = 2400): number {
|
||||
const long = Math.max(width, height);
|
||||
return Math.min(1, Math.max(0.35, minLongEdge / long) * (width >= height ? 1 : height / width));
|
||||
}
|
||||
|
||||
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number): Composition | null {
|
||||
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) {
|
||||
@@ -131,14 +150,14 @@ function frame(d: Detections, s: Box, ratio: number, mustBottom: number, headroo
|
||||
cw = 1;
|
||||
ch = cw / ratio;
|
||||
}
|
||||
if (cw < w(s) + 0.01 || ch < mustBottom - s.y0 + headroom) continue;
|
||||
if (cw < w(s) + 0.01 || ch < mustBottom - s.y0 + headroom || cw < minWidth - 1e-9) 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);
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio) + jointCost(r, inSubject, others, mainSharp);
|
||||
if (!best || c < best.cost) best = { rect: r, cost: c };
|
||||
}
|
||||
}
|
||||
@@ -169,3 +188,31 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
|
||||
c += TUNING.wHead * Math.abs((s.y0 - r.y0) / ch - TUNING.headAt);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Crop edges that cross a body at a joint (ankle, knee, hip, neck): the "amputation" look. */
|
||||
function jointCost(r: Box, subject: Detection[], others: Detection[], mainSharp: number): number {
|
||||
let c = 0;
|
||||
const bodies = [...subject, ...others.filter((p) => sharp(p) >= TUNING.inFocus * mainSharp)];
|
||||
for (const p of bodies) {
|
||||
// Only edges that actually cut through this person, horizontally inside their box.
|
||||
if (r.x1 <= p.x0 || r.x0 >= p.x1) continue;
|
||||
for (const edge of [r.y0, r.y1]) {
|
||||
if (edge <= p.y0 || edge >= p.y1) continue;
|
||||
const at = (edge - p.y0) / h(p);
|
||||
if (JOINTS.some((j) => Math.abs(at - j) < JOINT_BAND)) c += TUNING.wJoint * Math.min(1, h(p) / 0.4);
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* How good a frame is, to pick the best of a burst (docs/photo-editing-rules.md §3): the subject in focus (no motion
|
||||
* blur), big enough, with the ball when there is one. Only meaningful between frames of the same burst.
|
||||
*/
|
||||
export function frameScore(d: Detections, c: Composition | null): number {
|
||||
if (!c) return 0;
|
||||
const subject = d.people.filter((p) => p.x0 >= c.subject.x0 - 1e-9 && p.x1 <= c.subject.x1 + 1e-9 && p.y0 >= c.subject.y0 - 1e-9 && p.y1 <= c.subject.y1 + 1e-9);
|
||||
const focus = Math.max(0, ...subject.map((p) => p.focus ?? 0));
|
||||
const tallest = Math.max(0, ...subject.map(h));
|
||||
return Math.log10(1 + focus) * (0.6 + Math.min(1, tallest / 0.5)) * (c.reason === "ball" ? 1.15 : 1);
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import * as ort from "onnxruntime-node";
|
||||
import { modelsDir } from "../lib/models.js";
|
||||
import sharp from "sharp";
|
||||
import type { Detection, Detections } from "./compose.js";
|
||||
|
||||
@@ -10,6 +13,21 @@ const SIZE = 640;
|
||||
const PERSON = 0;
|
||||
const BALL = 32; // COCO "sports ball"
|
||||
|
||||
/** Loads the detector on first use from the downloaded models (null while the model isn't there). */
|
||||
export function lazyDetector(storageRoot: string): () => Promise<SubjectDetector> | null {
|
||||
let loading: Promise<SubjectDetector> | null = null;
|
||||
return () => {
|
||||
const dir = modelsDir(storageRoot);
|
||||
const file = dir && join(dir, "yolox_s.onnx");
|
||||
if (!file || !existsSync(file)) return null;
|
||||
loading ??= SubjectDetector.load(file).catch((err: unknown) => {
|
||||
loading = null;
|
||||
throw err;
|
||||
});
|
||||
return loading;
|
||||
};
|
||||
}
|
||||
|
||||
export class SubjectDetector {
|
||||
private constructor(private readonly session: ort.InferenceSession) {}
|
||||
|
||||
@@ -135,5 +153,8 @@ async function addSharpness(file: string | Buffer, people: Detection[]): Promise
|
||||
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));
|
||||
people.forEach((p, i) => {
|
||||
p.sharpness = values[i]! / max;
|
||||
p.focus = values[i]!;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Box } from "./compose.js";
|
||||
|
||||
/**
|
||||
* Crop geometry shared with the app's editor (apps/app/src/develop/Viewer.tsx, same maths): a crop is a box in the
|
||||
* frame rotated by the straighten angle, normalised to the photo's size.
|
||||
*/
|
||||
|
||||
/** Whether every corner of `r` lies on a `w`×`h` photo rotated by `angle` degrees about its centre. */
|
||||
export function insideRotated(r: Box, angle: number, w: number, h: number): boolean {
|
||||
const a = (-angle * Math.PI) / 180;
|
||||
const [c, s] = [Math.cos(a), Math.sin(a)];
|
||||
const eps = 1e-6;
|
||||
return [
|
||||
[r.x0, r.y0],
|
||||
[r.x1, r.y0],
|
||||
[r.x0, r.y1],
|
||||
[r.x1, r.y1],
|
||||
].every(([nx, ny]) => {
|
||||
const px = nx! * w - w / 2;
|
||||
const py = ny! * h - h / 2;
|
||||
const qx = px * c - py * s + w / 2;
|
||||
const qy = px * s + py * c + h / 2;
|
||||
return qx >= -eps * w && qy >= -eps * h && qx <= w * (1 + eps) && qy <= h * (1 + eps);
|
||||
});
|
||||
}
|
||||
|
||||
/** The crop kept on the straightened photo: moved towards the centre, then shrunk about it keeping its shape. */
|
||||
export function constrainRotated(r: Box, angle: number, w: number, h: number): Box {
|
||||
if (insideRotated(r, angle, w, h)) return r;
|
||||
const cx = (r.x0 + r.x1) / 2;
|
||||
const cy = (r.y0 + r.y1) / 2;
|
||||
const rw = r.x1 - r.x0;
|
||||
const rh = r.y1 - r.y0;
|
||||
for (let i = 1; i <= 32; i++) {
|
||||
const t = i / 32;
|
||||
const nx = cx + (0.5 - cx) * t;
|
||||
const ny = cy + (0.5 - cy) * t;
|
||||
const cand = { x0: nx - rw / 2, y0: ny - rh / 2, x1: nx + rw / 2, y1: ny + rh / 2 };
|
||||
if (insideRotated(cand, angle, w, h)) return cand;
|
||||
}
|
||||
const a = Math.abs((angle * Math.PI) / 180);
|
||||
const [sn, cs] = [Math.sin(a), Math.cos(a)];
|
||||
const hx = (rw * w) / 2;
|
||||
const hy = (rh * h) / 2;
|
||||
const k = Math.min(1, w / 2 / (hx * cs + hy * sn), h / 2 / (hx * sn + hy * cs));
|
||||
return { x0: 0.5 - (rw * k) / 2, y0: 0.5 - (rh * k) / 2, x1: 0.5 + (rw * k) / 2, y1: 0.5 + (rh * k) / 2 };
|
||||
}
|
||||
|
||||
/** `r` shrunk by `factor` about the subject's centre, keeping the subject inside and the crop on the photo. */
|
||||
export function tighter(r: Box, subject: Box, factor: number): Box {
|
||||
const w = (r.x1 - r.x0) * factor;
|
||||
const h = (r.y1 - r.y0) * factor;
|
||||
if (w < subject.x1 - subject.x0 || h < subject.y1 - subject.y0) return r;
|
||||
const cx = Math.min(Math.max((subject.x0 + subject.x1) / 2, subject.x1 - w / 2), subject.x0 + w / 2);
|
||||
const cy = Math.min(Math.max((r.y0 + r.y1) / 2, subject.y1 - h / 2), subject.y0 + h / 2);
|
||||
const x0 = Math.min(Math.max(0, cx - w / 2), 1 - w);
|
||||
const y0 = Math.min(Math.max(0, cy - h / 2), 1 - h);
|
||||
return { x0, y0, x1: x0 + w, y1: y0 + h };
|
||||
}
|
||||
@@ -1,15 +1,12 @@
|
||||
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";
|
||||
import { lazyDetector } 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({});
|
||||
@@ -21,17 +18,7 @@ const Body = z.object({ aspect: z.tuple([z.number().positive(), z.number().posit
|
||||
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;
|
||||
};
|
||||
const load = lazyDetector(deps.storageRoot);
|
||||
|
||||
app.post("/v1/photos/:photoId/auto-crop", { preHandler: authenticate }, async (req, reply) => {
|
||||
const { photoId } = Params.parse(req.params);
|
||||
|
||||
@@ -22,9 +22,16 @@ export interface RenderEngine {
|
||||
/** `unedited`: the result equals the defaults (e.g. after a reset), so the original is shown as is. */
|
||||
replay(base: Settings | null, commands: unknown[]): Promise<Replayed>;
|
||||
render(job: RenderJob): Promise<{ width: number; height: number }>;
|
||||
/** Automatic white balance and tone values (control id -> value) and the level angle (null: no clear lines). */
|
||||
auto(input: string, settings: Settings | null): Promise<AutoResult>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface AutoResult {
|
||||
values: Record<string, number>;
|
||||
angle: number | null;
|
||||
}
|
||||
|
||||
export class RenderProcess implements RenderEngine {
|
||||
private readonly proc: LineProcess;
|
||||
|
||||
@@ -42,6 +49,11 @@ export class RenderProcess implements RenderEngine {
|
||||
return { width: Number(r.width), height: Number(r.height) };
|
||||
}
|
||||
|
||||
async auto(input: string, settings: Settings | null): Promise<AutoResult> {
|
||||
const r = await this.proc.request({ auto: { input, settings } });
|
||||
return { values: (r.values as Record<string, number> | undefined) ?? {}, angle: typeof r.angle === "number" ? r.angle : null };
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.proc.close();
|
||||
}
|
||||
@@ -58,6 +70,9 @@ export class RenderPool implements RenderEngine {
|
||||
render(job: RenderJob) {
|
||||
return this.pool.use((e) => e.render(job));
|
||||
}
|
||||
auto(input: string, settings: Settings | null) {
|
||||
return this.pool.use((e) => e.auto(input, settings));
|
||||
}
|
||||
async close(): Promise<void> {
|
||||
await Promise.all(this.engines.map((e) => e.close()));
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ export class DevelopService {
|
||||
}
|
||||
|
||||
/** Appends ops in order. A repeated `opId` (a retry) returns the stored entry and is not broadcast again. */
|
||||
async append(photoId: string, userId: string, body: PostEdits): Promise<{ developSeq: number; ops: EditLogEntry[] }> {
|
||||
async append(photoId: string, userId: string | null, body: PostEdits): Promise<{ developSeq: number; ops: EditLogEntry[] }> {
|
||||
for (const op of body.ops) validate(op.command);
|
||||
const { db, broadcaster } = this.deps;
|
||||
const result = await db.$transaction(async (tx) => {
|
||||
|
||||
@@ -180,9 +180,12 @@ export class IngestService {
|
||||
const made = await this.makeDerivatives(orgId, sha256, storageKey);
|
||||
const { width, height } = origin.original?.width && origin.original.height ? { width: origin.original.width, height: origin.original.height } : made;
|
||||
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
|
||||
// The event's autopilot edits what arrives by FTP or the desktop app's ingest; hand uploads stay as sent.
|
||||
const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true } }) : null;
|
||||
const autopilot = origin.source !== "UPLOAD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true;
|
||||
photo = await db.photo.update({
|
||||
where: { id: photo.id },
|
||||
data: { status: "READY", width, height, facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE" },
|
||||
data: { status: "READY", width, height, facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", ...(autopilot && { autopilotStatus: "PENDING" }) },
|
||||
});
|
||||
outcome = { status: "ingested", photoId: photo.id, eventId };
|
||||
log.info({ photoId: photo.id, eventId, source: origin.source }, "ingest: photo ready");
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { AutopilotSettings } from "@photoreport/contracts";
|
||||
import { IptcTemplate, NEWSROOM_TEMPLATE } from "@photoreport/metadata";
|
||||
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { ROLE_RANK, currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
|
||||
import type { SessionService } from "../auth/sessions.js";
|
||||
import type { Db } from "../db.js";
|
||||
import type { Event, Prisma } from "../generated/prisma/client.js";
|
||||
import { type Event, Prisma } from "../generated/prisma/client.js";
|
||||
import { compact } from "../lib/compact.js";
|
||||
import { badRequest, notFound } from "../lib/errors.js";
|
||||
|
||||
@@ -32,6 +33,8 @@ const EventFields = z.object({
|
||||
ingestUntil: z.coerce.date().optional(),
|
||||
iptcTemplate: IptcTemplate.optional(),
|
||||
photographerIds: z.array(z.uuid()).max(50).optional(),
|
||||
/** Autopilot settings; null switches it off. */
|
||||
autopilot: AutopilotSettings.nullable().optional(),
|
||||
});
|
||||
const CreateEvent = EventFields;
|
||||
const UpdateEvent = EventFields.partial().extend({ archived: z.boolean().optional() });
|
||||
@@ -107,10 +110,11 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
const body = CreateEvent.parse(req.body);
|
||||
await requireMembership(db, req, orgId, "EDITOR");
|
||||
if (body.photographerIds?.length) await assertMembers(orgId, body.photographerIds);
|
||||
const { photographerIds, iptcTemplate, ingestFrom, ingestUntil, ...fields } = body;
|
||||
const { photographerIds, iptcTemplate, ingestFrom, ingestUntil, autopilot, ...fields } = body;
|
||||
const event = await db.event.create({
|
||||
data: {
|
||||
...compact(fields),
|
||||
...(autopilot && { autopilot }),
|
||||
home: fields.home,
|
||||
away: fields.away,
|
||||
startsAt: fields.startsAt,
|
||||
@@ -135,7 +139,7 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
const body = UpdateEvent.parse(req.body);
|
||||
const current = await loadEvent(req, eventId, "EDITOR");
|
||||
if (body.photographerIds) await assertMembers(current.organizationId, body.photographerIds);
|
||||
const { photographerIds, archived, iptcTemplate, ingestFrom, ingestUntil, startsAt, ...fields } = body;
|
||||
const { photographerIds, archived, iptcTemplate, ingestFrom, ingestUntil, startsAt, autopilot, ...fields } = body;
|
||||
const window =
|
||||
startsAt || ingestFrom || ingestUntil
|
||||
? ingestWindow(startsAt ?? current.startsAt, ingestFrom ?? (startsAt ? undefined : current.ingestFrom), ingestUntil ?? (startsAt ? undefined : current.ingestUntil))
|
||||
@@ -152,6 +156,7 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
...(startsAt && { startsAt }),
|
||||
...window,
|
||||
...(iptcTemplate && { iptcTemplate }),
|
||||
...(autopilot !== undefined && { autopilot: autopilot ?? Prisma.DbNull }),
|
||||
...(archived !== undefined && { archivedAt: archived ? (current.archivedAt ?? new Date()) : null }),
|
||||
},
|
||||
include,
|
||||
|
||||
+12
-1
@@ -11,6 +11,8 @@ import { DeliveryService, DeliveryWorker } from "./delivery/service.js";
|
||||
import { RenderPool, RenderProcess } from "./develop/engine.js";
|
||||
import { DevelopService, RenderWorker } from "./develop/service.js";
|
||||
import { FacePool, FaceProcess } from "./faces/process.js";
|
||||
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
|
||||
import { lazyDetector } from "./composition/detect.js";
|
||||
import { smtpMailer } from "./lib/mailer.js";
|
||||
import { FulfilmentWorker, ShopService } from "./shop/service.js";
|
||||
import { FaceService, FaceWorker } from "./faces/service.js";
|
||||
@@ -64,7 +66,8 @@ if (!renderEngine) log.warn("RENDER_BIN not set: edited photos get no new thumbn
|
||||
const develop = new DevelopService({ db, storage, signer, broadcaster, log, engine: renderEngine });
|
||||
const renders = renderEngine ? new RenderWorker(develop, { concurrency: config.RENDER_PROCESSES, intervalMs: 500, log }) : undefined;
|
||||
|
||||
const deliveries = new DeliveryWorker(new DeliveryService({ db, storage, secrets, broadcaster, log, develop }), {
|
||||
const deliveryService = new DeliveryService({ db, storage, secrets, broadcaster, log, develop });
|
||||
const deliveries = new DeliveryWorker(deliveryService, {
|
||||
concurrency: config.DELIVERY_CONCURRENCY,
|
||||
intervalMs: 1000,
|
||||
log,
|
||||
@@ -88,7 +91,14 @@ const faces = faceEngine
|
||||
: undefined;
|
||||
if (!faces) log.warn("FACES_BIN/FACES_MODELS_DIR not set: face analysis is off in this worker");
|
||||
|
||||
// Autopilot: edits and picks what arrives at events that have it switched on (docs/photo-editing-rules.md).
|
||||
const autopilot = new AutopilotWorker(
|
||||
new AutopilotService({ db, storage, broadcaster, log, develop, engine: renderEngine, detector: lazyDetector(config.STORAGE_ROOT), deliveries: deliveryService }),
|
||||
{ concurrency: 2, intervalMs: 1000, log },
|
||||
);
|
||||
|
||||
scanner.start();
|
||||
autopilot.start();
|
||||
deliveries.start();
|
||||
faces?.start();
|
||||
renders?.start();
|
||||
@@ -98,6 +108,7 @@ log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "work
|
||||
const shutdown = async (signal: string) => {
|
||||
log.info({ signal }, "worker stopping");
|
||||
scanner.stop();
|
||||
autopilot.stop();
|
||||
deliveries.stop();
|
||||
faces?.stop();
|
||||
renders?.stop();
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { copyFile, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { AutopilotService } from "../src/autopilot/service.js";
|
||||
import { bestOf, groupBursts } from "../src/autopilot/bursts.js";
|
||||
import type { Detections } from "../src/composition/compose.js";
|
||||
import type { SubjectDetector } from "../src/composition/detect.js";
|
||||
import type { RenderEngine, RenderJob, Settings } from "../src/develop/engine.js";
|
||||
import { DevelopService } from "../src/develop/service.js";
|
||||
import { IngestService } from "../src/ingest/service.js";
|
||||
import { MemoryBroadcaster } from "../src/realtime.js";
|
||||
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
|
||||
import { createTestApp, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
|
||||
const quiet = { info() {}, warn() {}, error() {} };
|
||||
|
||||
class FakeEngine implements RenderEngine {
|
||||
async replay(base: Settings | null, commands: unknown[]) {
|
||||
return { settings: { ...(base ?? {}), n: commands.length }, skipped: [], unedited: false };
|
||||
}
|
||||
async render(job: RenderJob) {
|
||||
await copyFile(job.input, job.output);
|
||||
return { width: 600, height: 400 };
|
||||
}
|
||||
async auto() {
|
||||
return { values: { "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.4, "light.contrast": 20 }, angle: 1.5 };
|
||||
}
|
||||
async close() {}
|
||||
}
|
||||
|
||||
/** A player in the middle; `focus` per photo (keyed by the sha in the preview's file name). */
|
||||
class FakeDetector {
|
||||
readonly focus = new Map<string, number>();
|
||||
async detect(file: string): Promise<Detections> {
|
||||
const sha = path.basename(file).split(".")[0]!;
|
||||
const focus = this.focus.get(sha) ?? 100;
|
||||
return { width: 600, height: 400, people: [{ x0: 0.42, y0: 0.2, x1: 0.58, y1: 0.85, score: 0.9, sharpness: 1, focus }], balls: [] };
|
||||
}
|
||||
}
|
||||
|
||||
describe("bursts", () => {
|
||||
const f = (id: string, ms: number | null, camera = "R1", score: number | null = 1) => ({ id, capturedAt: ms === null ? null : new Date(1_800_000_000_000 + ms), camera, score });
|
||||
it("groups frames of one camera closer than the gap, never across cameras", () => {
|
||||
const bursts = groupBursts([f("a", 0), f("b", 200), f("c", 400), f("d", 5000), f("e", 300, "Z9"), f("x", null)], 1500);
|
||||
expect(bursts.map((b) => b.map((x) => x.id))).toEqual([["x"], ["a", "b", "c"], ["e"], ["d"]]);
|
||||
});
|
||||
it("keeps the best frames, the earlier one on a near tie, in capture order", () => {
|
||||
const burst = [f("a", 0, "R1", 5), f("b", 100, "R1", 9), f("c", 200, "R1", 9.1), f("d", 300, "R1", 2)];
|
||||
expect(bestOf(burst, 1).map((x) => x.id)).toEqual(["b"]);
|
||||
expect(bestOf(burst, 2).map((x) => x.id)).toEqual(["b", "c"]);
|
||||
expect(bestOf(burst, 0)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("autopilot", () => {
|
||||
let ctx: TestContext;
|
||||
let dir: string;
|
||||
let ingest: IngestService;
|
||||
let develop: DevelopService;
|
||||
let autopilot: AutopilotService;
|
||||
let detector: FakeDetector;
|
||||
const broadcaster = new MemoryBroadcaster();
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "pr-autopilot-"));
|
||||
const ingestRoot = path.join(dir, "ingest");
|
||||
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }, broadcaster);
|
||||
const storage = new LocalStorage(ctx.config.STORAGE_ROOT);
|
||||
const signer = new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC);
|
||||
const engine = new FakeEngine();
|
||||
detector = new FakeDetector();
|
||||
ingest = new IngestService({ db: ctx.db, storage, signer, broadcaster, ingestRoot, log: quiet });
|
||||
develop = new DevelopService({ db: ctx.db, storage, signer, broadcaster, log: quiet, engine });
|
||||
autopilot = new AutopilotService({ db: ctx.db, storage, broadcaster, log: quiet, develop, engine, detector: () => Promise.resolve(detector as unknown as SubjectDetector) });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.app.close();
|
||||
await ctx.db.$disconnect();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await resetDb(ctx.db);
|
||||
broadcaster.sent.length = 0;
|
||||
});
|
||||
|
||||
let n = 0;
|
||||
async function shot(orgId: string, userId: string, eventId: string, at: number, focus: number, source: "FTP" | "UPLOAD" = "FTP") {
|
||||
n++;
|
||||
const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: (n * 31) % 256, g: 90, b: 120 } } }).jpeg().toBuffer();
|
||||
const { createHash } = await import("node:crypto");
|
||||
detector.focus.set(createHash("sha256").update(data).digest("hex"), focus);
|
||||
const file = path.join(dir, `IMG_${n}.JPG`);
|
||||
await writeFile(file, data);
|
||||
const out = await ingest.ingest(file, { organizationId: orgId, userId, source, originalName: `IMG_${n}.JPG`, eventId });
|
||||
await ctx.db.photo.update({ where: { id: out.photoId }, data: { capturedAt: new Date(1_800_000_000_000 + at), cameraSerial: "R1-001" } });
|
||||
return out.photoId;
|
||||
}
|
||||
|
||||
async function setup(autopilotOn = true) {
|
||||
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "EDITOR" });
|
||||
const event = await ctx.db.event.create({
|
||||
data: {
|
||||
organizationId: org!.id,
|
||||
home: "ABC",
|
||||
away: "CDE",
|
||||
startsAt: new Date("2026-10-11T14:00:00Z"),
|
||||
ingestFrom: new Date("2026-10-11T12:00:00Z"),
|
||||
ingestUntil: new Date("2026-10-11T18:00:00Z"),
|
||||
iptcTemplate: {},
|
||||
...(autopilotOn && { autopilot: { enabled: true, picksPerBurst: 2 } }),
|
||||
},
|
||||
});
|
||||
return { orgId: org!.id, userId: user.id, eventId: event.id };
|
||||
}
|
||||
|
||||
async function runQueue() {
|
||||
for (let ids = await autopilot.claim(10); ids.length; ids = await autopilot.claim(10)) for (const id of ids) await autopilot.process(id);
|
||||
}
|
||||
|
||||
it("edits what arrives by FTP: measured tone, level, a crop around the subject; hand uploads stay as sent", async () => {
|
||||
const { orgId, userId, eventId } = await setup();
|
||||
const ftp = await shot(orgId, userId, eventId, 0, 300);
|
||||
const hand = await shot(orgId, userId, eventId, 60_000, 300, "UPLOAD");
|
||||
await runQueue();
|
||||
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: ftp }, orderBy: { seq: "asc" } });
|
||||
expect(edits.map((e) => (e.command as { command: string }).command)).toEqual(["develop.set", "crop.set"]);
|
||||
expect(edits.every((e) => e.clientId === "autopilot")).toBe(true);
|
||||
// White balance stays as shot (off by default); tone at half strength.
|
||||
expect((edits[0]!.command as { params: { values: Record<string, number> } }).params.values).toEqual({ "light.exposure": 0.2, "light.contrast": 10 });
|
||||
const crop = (edits[1]!.command as { params: { rect: { x0: number; x1: number }; angle: number } }).params;
|
||||
expect(crop.angle).toBe(1.5);
|
||||
expect(crop.rect.x0).toBeLessThan(0.42);
|
||||
expect(crop.rect.x1).toBeGreaterThan(0.58);
|
||||
expect(await ctx.db.photoEdit.count({ where: { photoId: hand } })).toBe(0);
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: hand } })).autopilotStatus).toBe("NONE");
|
||||
});
|
||||
|
||||
it("picks the sharpest frames of each burst once it has settled, never overriding a human flag", async () => {
|
||||
const { orgId, userId, eventId } = await setup();
|
||||
const a = await shot(orgId, userId, eventId, 0, 100);
|
||||
const b = await shot(orgId, userId, eventId, 100, 900);
|
||||
const c = await shot(orgId, userId, eventId, 200, 500);
|
||||
const d = await shot(orgId, userId, eventId, 300, 50);
|
||||
const lone = await shot(orgId, userId, eventId, 10_000, 200);
|
||||
await ctx.db.photo.update({ where: { id: lone }, data: { flag: "REJECT" } });
|
||||
await runQueue();
|
||||
// Too soon: the burst may still be arriving.
|
||||
expect(await autopilot.decideBursts(new Date())).toBe(0);
|
||||
expect(await autopilot.decideBursts(new Date(Date.now() + 20_000))).toBe(2);
|
||||
const flags = Object.fromEntries((await ctx.db.photo.findMany({ where: { eventId } })).map((p) => [p.id, p.flag]));
|
||||
expect(flags).toEqual({ [a]: "NONE", [b]: "PICK", [c]: "PICK", [d]: "NONE", [lone]: "REJECT" });
|
||||
// The second pick gets a tighter variant of its crop.
|
||||
expect(await ctx.db.photoEdit.count({ where: { photoId: c, opId: `autopilot-${c}-variant` } })).toBe(1);
|
||||
// Decided once: running again changes nothing.
|
||||
expect(await autopilot.decideBursts(new Date(Date.now() + 40_000))).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves events without autopilot alone", async () => {
|
||||
const { orgId, userId, eventId } = await setup(false);
|
||||
await shot(orgId, userId, eventId, 0, 100);
|
||||
expect(await autopilot.claim(10)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { compose, type Detection, findSubject } from "../src/composition/compose.js";
|
||||
import { compose, type Detection, findSubject, minCropWidth } 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;
|
||||
@@ -50,6 +50,17 @@ describe("automatic crop", () => {
|
||||
expect(Math.abs((c.rect.x0 + c.rect.x1) / 2 - 0.5)).toBeLessThan(0.05);
|
||||
});
|
||||
|
||||
it("never crops across a knee or an ankle, and keeps the delivery's resolution", () => {
|
||||
// A tall player who can't fit whole in a two-thirds crop: the bottom edge must miss the joints.
|
||||
const p = { ...person(0.42, 0.05, 0.58, 1.0), sharpness: 1 };
|
||||
const c = compose({ ...frame, people: [p], balls: [] }, null, { minWidth: 0.5 })!;
|
||||
const at = (c.rect.y1 - p.y0) / (p.y1 - p.y0);
|
||||
for (const j of [0.74, 0.95]) if (c.rect.y1 < 1) expect(Math.abs(at - j)).toBeGreaterThanOrEqual(0.035);
|
||||
expect(c.rect.x1 - c.rect.x0).toBeGreaterThanOrEqual(0.5 - 1e-9);
|
||||
expect(minCropWidth(6000, 4000)).toBeCloseTo(0.4, 5);
|
||||
expect(minCropWidth(2048, 1365)).toBe(1);
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -32,6 +32,9 @@ class FakeEngine implements RenderEngine {
|
||||
await copyFile(job.input, job.output);
|
||||
return { width: 600, height: 400 };
|
||||
}
|
||||
async auto() {
|
||||
return { values: {}, angle: null };
|
||||
}
|
||||
async close() {}
|
||||
}
|
||||
|
||||
|
||||
@@ -152,6 +152,21 @@ export const t = {
|
||||
captured: "Captura",
|
||||
photographer: "Fotógrafo",
|
||||
deliverTo: "Entregar em",
|
||||
autopilot: {
|
||||
button: "Piloto automático",
|
||||
enable: "Ligar o piloto automático neste evento",
|
||||
help: "As fotos que chegam por FTP ou pelo ingest da app são editadas ao chegar (recorte, nivelar, tom) e as melhores de cada sequência ficam escolhidas. Tudo pode ser desfeito no Revelar. Fotos importadas à mão não são tocadas.",
|
||||
crop: "Recortar",
|
||||
level: "Nivelar",
|
||||
tone: "Tom",
|
||||
whiteBalance: "Equilíbrio de brancos",
|
||||
toneStrength: (n: number) => `Intensidade do tom: ${n}%`,
|
||||
picksPerBurst: "Escolher por sequência",
|
||||
noPicks: "Não escolher",
|
||||
minLongEdge: "Resolução mínima do recorte",
|
||||
deliver: "Enviar as escolhidas para",
|
||||
noDelivery: "Não enviar",
|
||||
},
|
||||
info: {
|
||||
title: "Informação (IPTC)",
|
||||
count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { AutopilotSettings } from "@photoreport/contracts";
|
||||
import type { ApiClient, DeliveryTarget, EventSummary } from "@photoreport/sdk";
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
|
||||
/**
|
||||
* Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest
|
||||
* are edited (tone, level, crop) and the best frames of each burst picked, and optionally delivered.
|
||||
*/
|
||||
export function AutopilotButton(props: { api: ApiClient; event: EventSummary; targets: DeliveryTarget[]; canEdit: boolean; onSaved: (e: EventSummary) => void }) {
|
||||
const L = t.autopilot;
|
||||
const [open, setOpen] = useState(false);
|
||||
const [s, setS] = useState<AutopilotSettings>(() => AutopilotSettings.parse(props.event.autopilot ?? {}));
|
||||
const [state, setState] = useState<"idle" | "saving" | "error">("idle");
|
||||
useEffect(() => setS(AutopilotSettings.parse(props.event.autopilot ?? {})), [props.event]);
|
||||
|
||||
const save = async (next: AutopilotSettings) => {
|
||||
setS(next);
|
||||
setState("saving");
|
||||
try {
|
||||
props.onSaved(await props.api.updateEvent(props.event.id, { autopilot: next }));
|
||||
setState("idle");
|
||||
} catch {
|
||||
setState("error");
|
||||
}
|
||||
};
|
||||
const check = (key: "crop" | "level" | "tone" | "whiteBalance") => (
|
||||
<label key={key} className="flex items-center gap-2">
|
||||
<input type="checkbox" disabled={!props.canEdit} checked={s[key]} onChange={(e) => void save({ ...s, [key]: e.target.checked })} />
|
||||
<span>{L[key]}</span>
|
||||
</label>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-expanded={open}
|
||||
className={`flex h-6 items-center gap-1.5 border border-black px-2.5 text-[12px] ${s.enabled ? "bg-accent text-white" : "bg-cell text-ink hover:bg-cell-on"}`}
|
||||
>
|
||||
{L.button}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute right-0 top-7 z-30 w-[360px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span className="font-semibold uppercase tracking-wide text-ink">{L.button}</span>
|
||||
<input type="checkbox" disabled={!props.canEdit} checked={s.enabled} onChange={(e) => void save({ ...s, enabled: e.target.checked })} aria-label={L.enable} />
|
||||
</label>
|
||||
<p className="text-faint">{L.help}</p>
|
||||
<fieldset className="grid grid-cols-2 gap-1.5" disabled={!s.enabled || !props.canEdit}>
|
||||
{check("crop")}
|
||||
{check("level")}
|
||||
{check("tone")}
|
||||
{check("whiteBalance")}
|
||||
</fieldset>
|
||||
<label className="block">
|
||||
<span className="text-faint">{L.toneStrength(Math.round(s.toneStrength * 100))}</span>
|
||||
<input type="range" min={0} max={100} value={Math.round(s.toneStrength * 100)} disabled={!s.enabled || !s.tone || !props.canEdit} className="w-full" onChange={(e) => setS({ ...s, toneStrength: Number(e.target.value) / 100 })} onPointerUp={() => void save(s)} />
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.picksPerBurst}</span>
|
||||
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.picksPerBurst} onChange={(e) => void save({ ...s, picksPerBurst: Number(e.target.value) })}>
|
||||
{[0, 1, 2, 3].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n === 0 ? L.noPicks : n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.minLongEdge}</span>
|
||||
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.minLongEdge} onChange={(e) => void save({ ...s, minLongEdge: Number(e.target.value) })}>
|
||||
{[1600, 2400, 3000, 4000].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n} px
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.deliver}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{state === "error" && <p className="text-danger">{t.unexpectedError}</p>}
|
||||
{state === "saving" && <p className="text-faint">…</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { useIngest } from "../library/ingest.js";
|
||||
import { LocalFtpButton } from "../library/LocalFtp.js";
|
||||
import { AutopilotButton } from "../library/Autopilot.js";
|
||||
import { type FilterId, initialLibrary, libraryReducer, matchesFilter, patchForKey } from "../library/store.js";
|
||||
import { prefs } from "../platform.js";
|
||||
|
||||
@@ -109,6 +110,7 @@ export function LibraryPage() {
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") ? state.scope : undefined;
|
||||
const openEvent = events.find((e) => e.id === uploadInto);
|
||||
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
|
||||
const failed = uploads.items.filter((i) => i.status === "failed");
|
||||
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
|
||||
@@ -242,6 +244,9 @@ export function LibraryPage() {
|
||||
{t.importPhotos}
|
||||
</button>
|
||||
{desktop && <LocalFtpButton ftp={localFtp} events={events} openEventId={uploadInto} />}
|
||||
{canCull && openEvent && (
|
||||
<AutopilotButton api={api} event={openEvent} targets={targets} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
|
||||
)}
|
||||
{canCull && selection.length > 0 && (
|
||||
<select
|
||||
aria-label={t.shop.addToGallery}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Photo editing rules (autopilot and automatic crop)
|
||||
|
||||
What the automatic editor may do to a news or sports photo, and how it chooses. These rules are the contract for
|
||||
`apps/api/src/composition/` and `apps/api/src/autopilot/`. Peter (and any editor) can tighten them per
|
||||
organisation or event; nothing here may be loosened past the ethics section.
|
||||
|
||||
## 1. Ethics (fixed)
|
||||
|
||||
Following the AP and NPPA codes:
|
||||
|
||||
- **Allowed:** crop, straighten, white balance, exposure and contrast, colour and toning "minimally needed for
|
||||
clear, accurate reproduction", conversion to black and white, dust removal.
|
||||
- **Not allowed:** adding, removing, moving or cloning anything in the scene; blurring or darkening the background
|
||||
to hide it; changes of density, contrast, colour or saturation that alter the scene; obscuring faces.
|
||||
- **A crop must not change what happened.** If removing someone changes the story (the defender in a duel, the
|
||||
referee showing a card, the goalkeeper facing the shot), they stay.
|
||||
- Every automatic edit is an ordinary, undoable step in the photo's edit history, marked as made by the autopilot.
|
||||
The original is never touched.
|
||||
|
||||
## 2. Crop
|
||||
|
||||
- **Who:** the subject is the person in focus, not the biggest one. With a ball in play, the ball and everyone
|
||||
contesting it. Without one, the subject and the sharp people with them (a duel, a celebration, a line-up).
|
||||
- **Shape:** the photo's own aspect unless the event or the editor chose another. Peter's usual crop is about two
|
||||
thirds of the frame; larger only when the subject needs it.
|
||||
- **Never cut:** heads, faces, hands holding the ball, the ball itself.
|
||||
- **Limbs:** if a body has to be cut, cut mid-limb (mid-thigh, mid-shin, mid-forearm), never at a joint (ankle,
|
||||
knee, hip, wrist, elbow, neck). The engine estimates joints from the body box and avoids crop edges there.
|
||||
- **Feet:** keep whole bodies when they fit; otherwise cut above the knee rather than at the ankle.
|
||||
- **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and
|
||||
background people don't count.
|
||||
- **Headroom:** heads a little below the top edge, not touching it, not floating in empty space.
|
||||
- **Distractions:** prefer the crop that leaves out half-bodies, empty floor and bright clutter at the edges,
|
||||
as long as nothing that matters goes with them.
|
||||
- **Resolution:** never crop below what the delivery needs. Default: the crop keeps at least 2400 px on its long
|
||||
edge of the original (configurable per organisation; agencies often ask for more).
|
||||
- **Not too much:** if the only crop that works is tighter than the resolution allows, keep the wider frame. A good
|
||||
photo uncropped beats a bad crop.
|
||||
|
||||
## 3. Bursts (sequences)
|
||||
|
||||
A camera at 10–30 frames per second sends several photos of the same moment.
|
||||
|
||||
- **A burst** is a run of photos from the same camera with less than 1.5 s between frames (configurable).
|
||||
- **Score** of each frame: sharpness of the subject (focus landed on them, no motion blur), subject size, ball in
|
||||
frame and near the subject, faces visible. Ties go to the earliest frame (usually the peak of the action).
|
||||
- **Keep:** the best 1–2 frames per burst (configurable), flagged as picks. The rest stay unflagged (never
|
||||
rejected or deleted automatically).
|
||||
- **Variety:** when two frames of a burst are kept, the second gets a slightly different crop (tighter or wider) so
|
||||
the client has a choice.
|
||||
- **Saturation:** an event can cap how many picks one burst, or one minute of play, may produce, so a long attack
|
||||
doesn't flood the delivery.
|
||||
|
||||
## 4. Autopilot
|
||||
|
||||
Per event (and an organisation default), off unless switched on. When on, every photo that arrives through FTP,
|
||||
the local FTP of the desktop app or auto-ingest is, in order:
|
||||
|
||||
1. analysed (people, ball, focus);
|
||||
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop;
|
||||
3. scored within its burst; when the burst ends, its best frames are flagged as picks;
|
||||
4. optionally delivered (rendered with the edits, IPTC from the event) to the event's delivery target.
|
||||
|
||||
Uploads made by hand in the browser are not touched. Anything the autopilot did can be undone, changed or reset
|
||||
in Revelar, and the editor's corrections are kept as examples to tune these rules.
|
||||
|
||||
## Sources
|
||||
|
||||
- AP and NPPA codes, summarised by the CUNY Newmark J-School: https://photo.journalism.cuny.edu/?p=201
|
||||
- Cropping at mid-limb, not at joints; keep meaning; avoid clutter: https://www.walsworthyearbooks.com/top-10-essential-rules-for-good-photo-cropping/
|
||||
- Burst culling criteria (subject sharpness, eyes, ball, peak action, 1–3 per burst): https://filterpixel.com/blog/sports-photography-burst-mode-culling
|
||||
- Peter's own Lightroom crops (65 picked photos, handball, October 2026): crops in the photo's aspect, often
|
||||
exactly two thirds of the frame, straightening of 0.5–3.3°.
|
||||
@@ -21,6 +21,31 @@ export const PhotoPatch = z
|
||||
.refine((p) => Object.values(p).some((v) => v !== undefined), { message: "nothing to change" });
|
||||
export type PhotoPatch = z.infer<typeof PhotoPatch>;
|
||||
|
||||
/**
|
||||
* Autopilot (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest are edited and the
|
||||
* best frames of each burst picked, automatically. Per event; off unless enabled.
|
||||
*/
|
||||
export const AutopilotSettings = z.object({
|
||||
enabled: z.boolean().default(false),
|
||||
crop: z.boolean().default(true),
|
||||
level: z.boolean().default(true),
|
||||
tone: z.boolean().default(true),
|
||||
/** How much of the automatic tone to apply (news photos want minimal toning). */
|
||||
toneStrength: z.number().min(0).max(1).default(0.5),
|
||||
whiteBalance: z.boolean().default(false),
|
||||
/** Crop shape (width, height); null: the photo's own. */
|
||||
aspect: z.tuple([z.number().positive(), z.number().positive()]).nullable().default(null),
|
||||
/** The crop keeps at least this many pixels on its long edge of the original. */
|
||||
minLongEdge: z.number().int().min(800).max(12000).default(2400),
|
||||
/** Best frames flagged as picks per burst (0: don't pick). */
|
||||
picksPerBurst: z.number().int().min(0).max(5).default(2),
|
||||
/** Frames closer than this (seconds) belong to the same burst. */
|
||||
burstGapSec: z.number().min(0.2).max(10).default(1.5),
|
||||
/** Deliver the picks to this target as they are chosen (null: don't). */
|
||||
deliverTargetId: z.string().uuid().nullable().default(null),
|
||||
});
|
||||
export type AutopilotSettings = z.infer<typeof AutopilotSettings>;
|
||||
|
||||
export const PhotoBatchPatch = z.object({
|
||||
ids: z.array(z.string().uuid()).min(1).max(1000),
|
||||
patch: PhotoPatch,
|
||||
|
||||
@@ -66,6 +66,8 @@ export interface EventSummary {
|
||||
archivedAt: string | null;
|
||||
photographers: { id: string; name: string }[];
|
||||
photoCount: number;
|
||||
/** Autopilot settings (contracts AutopilotSettings); null: off. */
|
||||
autopilot?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface EventInput {
|
||||
@@ -83,6 +85,7 @@ export interface EventInput {
|
||||
ingestUntil?: string;
|
||||
iptcTemplate?: Record<string, string | string[]>;
|
||||
photographerIds?: string[];
|
||||
autopilot?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface PhotoQuery {
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
//! "maxEdge": 4000, "quality": 100}
|
||||
//! out: {"id": "...", "width": W, "height": H} or {"id": "...", "error": "..."}
|
||||
//! `maxEdge` 0 keeps the full size. The output is sRGB without metadata; the caller copies EXIF and IPTC.
|
||||
//! Automatic first pass (autopilot): white balance, tone (under that white balance) and the level angle:
|
||||
//! in: {"id": "...", "auto": {"input": "/abs/preview.jpg", "settings": {..} | null}}
|
||||
//! out: {"id": "...", "values": {"wb.temp": .., "light.exposure": .., ..}, "angle": -1.2 | null}
|
||||
//! Settings from an op log:
|
||||
//! in: {"id": "...", "base": {..settings..} | null, "commands": [{"command": "develop.set", "params": {..}}, ..]}
|
||||
//! out: {"id": "...", "settings": {..}, "skipped": [indexes of commands that were refused], "unedited": bool}
|
||||
@@ -42,6 +45,50 @@ fn replay(job: &Replay) -> Result<(serde_json::Value, Vec<usize>, bool), String>
|
||||
Ok((settings.to_json(), skipped, settings.is_unedited()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AutoRequest {
|
||||
id: String,
|
||||
auto: AutoJob,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AutoJob {
|
||||
input: String,
|
||||
#[serde(default)]
|
||||
settings: serde_json::Value,
|
||||
}
|
||||
|
||||
/// White balance first, then tone under it (as an editor would), and the angle that levels the photo.
|
||||
fn auto(job: &AutoJob) -> Result<(serde_json::Value, Option<f64>), String> {
|
||||
let mut settings = if job.settings.is_null() {
|
||||
DevelopSettings::default()
|
||||
} else {
|
||||
DevelopSettings::from_json(&job.settings).map_err(|e| e.to_string())?
|
||||
};
|
||||
let bytes = std::fs::read(&job.input).map_err(|e| format!("{}: {e}", job.input))?;
|
||||
// A 1024 px working image is plenty for statistics and lines, and keeps this fast.
|
||||
let source = Source::decode(&bytes, 1024).map_err(|e| e.to_string())?;
|
||||
let mut values = serde_json::Map::new();
|
||||
let wb = source.auto_wb();
|
||||
let set = |settings: &DevelopSettings,
|
||||
pairs: &[(&'static str, f64)]|
|
||||
-> Result<DevelopSettings, String> {
|
||||
let command: EditCommand = serde_json::from_value(serde_json::json!({
|
||||
"command": "develop.set",
|
||||
"params": { "values": pairs.iter().map(|(k, v)| ((*k).to_string(), serde_json::json!(v))).collect::<serde_json::Map<_, _>>() }
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
apply_command(settings, &command).map_err(|e| e.to_string())
|
||||
};
|
||||
settings = set(&settings, &wb)?;
|
||||
let tone = source.auto_tone(&settings);
|
||||
for (k, v) in wb.iter().chain(tone.iter()) {
|
||||
values.insert((*k).to_string(), serde_json::json!(v));
|
||||
}
|
||||
let angle = source.auto_level(&settings);
|
||||
Ok((serde_json::Value::Object(values), angle))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Job {
|
||||
@@ -105,6 +152,22 @@ fn main() {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if value.get("auto").is_some() {
|
||||
let reply = match serde_json::from_value::<AutoRequest>(value) {
|
||||
Ok(req) => match auto(&req.auto) {
|
||||
Ok((values, angle)) => {
|
||||
serde_json::json!({ "id": req.id, "values": values, "angle": angle })
|
||||
}
|
||||
Err(error) => serde_json::json!({ "id": req.id, "error": error }),
|
||||
},
|
||||
Err(e) => {
|
||||
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
|
||||
}
|
||||
};
|
||||
let _ = writeln!(out, "{reply}");
|
||||
let _ = out.flush();
|
||||
continue;
|
||||
}
|
||||
if value.get("commands").is_some() {
|
||||
let reply = match serde_json::from_value::<Replay>(value) {
|
||||
Ok(job) => match replay(&job) {
|
||||
|
||||
Reference in new issue
Block a user