Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
769793b6af | ||
|
|
5ccbab8baf | ||
|
|
75ca04f890 | ||
|
|
791c59e077 | ||
|
|
062fdd263c | ||
|
|
9efb64b994 | ||
|
|
6abea99c26 | ||
|
|
635160b66e | ||
|
|
ef591d8fd8 | ||
|
|
f5f7c2fa59 | ||
|
|
b1dde5657a | ||
|
|
41598aa1ae | ||
|
|
2645138f54 |
No files matched your search
@@ -22,6 +22,16 @@ Read `docs/ARCHITECTURE.md` before any task. One task id per branch/PR (`task/BI
|
||||
ends in `_test`. Never run `prisma migrate reset` or other destructive commands against shared databases.
|
||||
11. **Green CI before merge:** `pnpm -r build && pnpm -r typecheck && pnpm -r test` and `cargo fmt --check`,
|
||||
`cargo clippy -D warnings`, `cargo test`.
|
||||
12. **Local-first; web is sync glue.** **Every** photographer-facing feature must work on the desktop without
|
||||
the network (library, cull, develop, autopilot picks, export of what is already on disk, local FTP/USB),
|
||||
except genuinely heavy shared jobs called out as such (e.g. org-wide face clustering across the federation).
|
||||
The web app is how several people work from anywhere and how the desktop syncs when it has a link — it must
|
||||
not be the only place a feature exists. Offline work is done locally and synced later; never force uploading
|
||||
every frame just so the server can decide. Autopilot culls and edits on the desktop
|
||||
(`apps/app/src/offline/autopilot.ts`) with the same rules as the worker.
|
||||
13. **Prefer Rust for local heavy work.** Detection, measure, level, develop and anything CPU-bound on the
|
||||
desktop should live in `engine/` (native / WASM), not in ad-hoc TypeScript, when practical. TypeScript
|
||||
orchestrates; Rust does the pixels and the scores. Safer, faster, one implementation with the workers.
|
||||
|
||||
## Porting from the old projects
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Candidate, actionScore } from "./curate.js";
|
||||
import { fillToCount } from "./best.js";
|
||||
|
||||
const start = 1_800_000_000_000;
|
||||
|
||||
function c(id: string, at: number, burst: number, score: number, extra: Partial<Candidate> = {}): Candidate {
|
||||
return {
|
||||
id,
|
||||
at: start + at,
|
||||
burst,
|
||||
score,
|
||||
reason: "person",
|
||||
people: 1,
|
||||
subjectHeight: 0.5,
|
||||
rating: 0,
|
||||
rejected: false,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
describe("fillToCount", () => {
|
||||
it("honours the requested gallery size when enough candidates exist", () => {
|
||||
const seed = [c("a", 0, 0, 9), c("b", 60_000, 1, 8)];
|
||||
const spare = Array.from({ length: 200 }, (_, i) => c(`s${i}`, 120_000 + i * 2_000, i + 2, 5 - (i % 5) * 0.1));
|
||||
const filled = fillToCount(seed, spare, 150);
|
||||
expect(filled).toHaveLength(150);
|
||||
expect(new Set(filled.map((x) => x.id)).size).toBe(150);
|
||||
});
|
||||
|
||||
it("does not stop early because of the 8s twin gap when the count still has room", () => {
|
||||
// Dense bursts 2s apart: the old 8s gate capped a 80-minute match far below 200.
|
||||
const spare = Array.from({ length: 250 }, (_, i) => c(`d${i}`, i * 2_000, i, 3));
|
||||
const filled = fillToCount([], spare, 200);
|
||||
expect(filled).toHaveLength(200);
|
||||
});
|
||||
|
||||
it("returns every usable candidate when the ask is larger than the pool", () => {
|
||||
const spare = [c("a", 0, 0, 2), c("b", 10_000, 1, 2), c("c", 20_000, 2, 0, { reason: null })];
|
||||
const filled = fillToCount([], spare, 300);
|
||||
expect(filled.map((x) => x.id).sort()).toEqual(["a", "b"]);
|
||||
expect(filled.every((x) => actionScore(x) > 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -52,12 +52,14 @@ export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided
|
||||
const best = frame === "second" && second && second.flag !== "REJECT" ? second : first;
|
||||
if (!best) return;
|
||||
const rec = best.rec;
|
||||
const marked = best.flag === "PICK" || best.rating > 0;
|
||||
out.push({
|
||||
id: best.id,
|
||||
at: (best.capturedAt ?? best.createdAt).getTime(),
|
||||
burst: i,
|
||||
score: best.score ?? 0,
|
||||
reason: rec ? rec.reason : best.score ? "person" : null,
|
||||
// A pick or a starred frame without autopilot analysis is still a candidate (training days, cull by hand).
|
||||
reason: rec?.reason ?? (best.score || marked ? "person" : null),
|
||||
people: rec?.people ?? null,
|
||||
subjectHeight: rec?.subject ? rec.subject.y1 - rec.subject.y0 : null,
|
||||
rating: best.rating,
|
||||
@@ -93,6 +95,36 @@ export function restBeside(
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grow a curated set up to `count`. First prefers spread (no twin within `minGapMs`), then drops the time gap,
|
||||
* then — only if still short — takes a second frame from bursts already used. The number the photographer asked
|
||||
* for is the target; under-filling to ~100 when they asked for 300 is a bug.
|
||||
*/
|
||||
export function fillToCount(picked: readonly Candidate[], spare: readonly Candidate[], count: number, minGapMs = 8_000): Candidate[] {
|
||||
const out: Candidate[] = [...picked];
|
||||
const have = new Set(out.map((c) => c.id));
|
||||
const usedBurst = new Set(out.map((c) => c.burst));
|
||||
const ranked = [...spare].filter((c) => actionScore(c) > 0 && !have.has(c.id)).sort((a, b) => actionScore(b) - actionScore(a));
|
||||
|
||||
const take = (pool: readonly Candidate[], opts: { gap: boolean; reuseBurst: boolean }) => {
|
||||
for (const c of pool) {
|
||||
if (out.length >= count) return;
|
||||
if (have.has(c.id)) continue;
|
||||
if (!opts.reuseBurst && usedBurst.has(c.burst)) continue;
|
||||
if (opts.gap && out.some((o) => Math.abs(o.at - c.at) < minGapMs)) continue;
|
||||
out.push(c);
|
||||
have.add(c.id);
|
||||
usedBurst.add(c.burst);
|
||||
}
|
||||
};
|
||||
|
||||
take(ranked, { gap: true, reuseBurst: false });
|
||||
if (out.length < count) take(ranked, { gap: false, reuseBurst: false });
|
||||
// Still short: the ask is larger than the number of bursts — allow a second frame from busy moments.
|
||||
if (out.length < count) take(ranked, { gap: false, reuseBurst: true });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The best `count` photos of an event, spread over the match, and the other picks and sequence frames beside them. */
|
||||
export async function bestOfEvent(
|
||||
db: Db,
|
||||
@@ -104,23 +136,28 @@ export async function bestOfEvent(
|
||||
const photos = await db.photo.findMany({ where: { eventId, status: "READY" }, select: CANDIDATE_SELECT });
|
||||
const look = await sequenceWeights(db, photos, 1500, files ? (p) => files.preview(p.organizationId, p.sha256) : null);
|
||||
const ranked = photos.map((p) => ({ ...p, look: look.get(p.id) ?? 1 }));
|
||||
const candidates = candidatesOf(ranked, 1500, false);
|
||||
// Best and second of each burst: filling a large gallery (200–300) needs more than one frame per moment.
|
||||
const primary = candidatesOf(ranked, 1500, false, "best");
|
||||
const seconds = candidatesOf(ranked, 1500, false, "second").filter((c) => !primary.some((p) => p.id === c.id));
|
||||
const candidates = [...primary, ...seconds];
|
||||
if (!candidates.length) return { chosen: [], rest: restBeside(photos, []) };
|
||||
const times = candidates.map((c) => c.at);
|
||||
// From kick-off (warm-up and line-ups are not game moments).
|
||||
const start = event.startsAt.getTime();
|
||||
const end = Math.max(...times, start + matchMinutes(event.sport) * 60_000);
|
||||
const decisions: WindowDecision[] = curate(candidates, [], { count, start, durationMs: Math.max(end - start, 10 * 60_000), now: Number.MAX_SAFE_INTEGER, settleMs: 0 });
|
||||
const decisions: WindowDecision[] = curate(primary, [], { count, start, durationMs: Math.max(end - start, 10 * 60_000), now: Number.MAX_SAFE_INTEGER, settleMs: 0 });
|
||||
const chosenIds = new Set(decisions.flatMap((d) => d.chosen));
|
||||
// The windows' shares are rounded, and photos may cover only part of the match: the best of the rest fill the
|
||||
// gallery up to its size (never twins of a chosen frame).
|
||||
const spare = candidates.filter((c) => !chosenIds.has(c.id) && actionScore(c) > 0 && c.at >= start - 5 * 60_000).sort((a, b) => actionScore(b) - actionScore(a));
|
||||
const picked = candidates.filter((c) => chosenIds.has(c.id));
|
||||
for (const c of spare) {
|
||||
if (picked.length >= count) break;
|
||||
if (picked.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < 8_000)) continue;
|
||||
picked.push(c);
|
||||
}
|
||||
const seed = primary.filter((c) => chosenIds.has(c.id));
|
||||
// Warm-up stays out of the first pass; if the count is still short (training days, long sessions), the fill
|
||||
// may use those frames so the number asked for is actually delivered.
|
||||
const spare = candidates
|
||||
.filter((c) => !chosenIds.has(c.id) && actionScore(c) > 0)
|
||||
.sort((a, b) => {
|
||||
const aw = a.at >= start - 5 * 60_000 ? 1 : 0;
|
||||
const bw = b.at >= start - 5 * 60_000 ? 1 : 0;
|
||||
if (aw !== bw) return bw - aw;
|
||||
return actionScore(b) - actionScore(a);
|
||||
});
|
||||
const picked = fillToCount(seed, spare, count);
|
||||
const chosen = picked.sort((a, b) => a.at - b.at).map((c) => c.id);
|
||||
return { chosen, rest: restBeside(photos, chosen) };
|
||||
}
|
||||
@@ -6,18 +6,28 @@
|
||||
export interface Frame {
|
||||
id: string;
|
||||
capturedAt: Date | null;
|
||||
/**
|
||||
* Ingest time. Used when `capturedAt` is missing (USB/FTP without EXIF) so a burst is not split into one
|
||||
* singleton pick per file.
|
||||
*/
|
||||
createdAt?: 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. */
|
||||
/** Capture or ingest time used to place the frame in a burst. */
|
||||
function atOf(f: Frame): Date | null {
|
||||
return f.capturedAt ?? f.createdAt ?? null;
|
||||
}
|
||||
|
||||
/** Groups frames into bursts, in capture order. Frames with neither capture nor ingest 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) {
|
||||
if (!atOf(f)) {
|
||||
loose.push([f]);
|
||||
continue;
|
||||
}
|
||||
@@ -27,11 +37,11 @@ export function groupBursts<F extends Frame>(frames: F[], gapMs: number): F[][]
|
||||
}
|
||||
const bursts: F[][] = [];
|
||||
for (const list of byCamera.values()) {
|
||||
list.sort((a, b) => a.capturedAt!.getTime() - b.capturedAt!.getTime());
|
||||
list.sort((a, b) => atOf(a)!.getTime() - atOf(b)!.getTime());
|
||||
let current: F[] = [];
|
||||
for (const f of list) {
|
||||
const last = current[current.length - 1];
|
||||
if (last && f.capturedAt!.getTime() - last.capturedAt!.getTime() > gapMs) {
|
||||
if (last && atOf(f)!.getTime() - atOf(last)!.getTime() > gapMs) {
|
||||
bursts.push(current);
|
||||
current = [];
|
||||
}
|
||||
@@ -39,7 +49,7 @@ export function groupBursts<F extends Frame>(frames: F[], gapMs: number): F[][]
|
||||
}
|
||||
if (current.length) bursts.push(current);
|
||||
}
|
||||
return [...bursts, ...loose].sort((a, b) => (a[0]!.capturedAt?.getTime() ?? 0) - (b[0]!.capturedAt?.getTime() ?? 0));
|
||||
return [...bursts, ...loose].sort((a, b) => (atOf(a[0]!)?.getTime() ?? 0) - (atOf(b[0]!)?.getTime() ?? 0));
|
||||
}
|
||||
|
||||
/** A good reportage sequence can yield several plans. More than this of one moment is too many. */
|
||||
|
||||
@@ -7,21 +7,32 @@ describe("sequence choice", () => {
|
||||
{ facing: 0, eyes: 0.2 },
|
||||
{ facing: 1, eyes: 0.8 },
|
||||
]);
|
||||
expect(weights[0]).toBeLessThan(0.5);
|
||||
expect(weights[0]).toBeLessThan(0.05);
|
||||
expect(weights[1]).toBe(1);
|
||||
expect(sequenceWeight([{ facing: 0, eyes: null }])).toEqual([1]);
|
||||
expect(sequenceWeight([{ facing: 1, eyes: 0.5 }, { facing: 1, eyes: 0.52 }])).toEqual([1, 1]);
|
||||
});
|
||||
|
||||
it("makes a shut eye lose harder in reportage than in a match", () => {
|
||||
it("never keeps a blink when the same burst has open eyes, even in a match", () => {
|
||||
const frames = [
|
||||
{ facing: 1 as const, eyes: 0.25 },
|
||||
{ facing: 1 as const, eyes: 0.8 },
|
||||
];
|
||||
const match = sequenceWeight(frames);
|
||||
const reportage = sequenceWeight(frames, true);
|
||||
expect(reportage[0]).toBeLessThan(match[0]!);
|
||||
expect(reportage[0]).toBeLessThanOrEqual(0.2);
|
||||
expect(match[0]!).toBeLessThanOrEqual(0.08);
|
||||
expect(reportage[0]!).toBeLessThanOrEqual(0.05);
|
||||
expect(match[1]).toBe(1);
|
||||
expect(reportage[1]).toBe(1);
|
||||
});
|
||||
|
||||
it("prefers open eyes over a grimace or a shot face when both are in the sequence", () => {
|
||||
const weights = sequenceWeight([
|
||||
{ facing: 1, eyes: 0.3 },
|
||||
{ facing: 1, eyes: 0.7 },
|
||||
{ facing: 1, eyes: 0.65 },
|
||||
]);
|
||||
expect(weights[0]!).toBeLessThan(weights[1]!);
|
||||
expect(weights[0]!).toBeLessThan(weights[2]!);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,9 @@ import { groupBursts } from "./bursts.js";
|
||||
* Which frame of a sequence to keep (docs/photo-editing-rules.md §3). A player from behind loses to a frame
|
||||
* where the face is visible, and shut eyes lose to open ones, when the difference is clear. If every frame is
|
||||
* a back, or the eyes cannot be told apart, nothing changes.
|
||||
*
|
||||
* Open eyes always beat shut ones when both are measured in the same burst — even on a shot or a grimace.
|
||||
* A clear face always beats a back when the burst has both.
|
||||
*/
|
||||
export interface SequenceLook {
|
||||
/** 1: a face on the subject. 0: the subject was seen and has no face (a back). null: not analysed yet. */
|
||||
@@ -15,18 +18,28 @@ export interface SequenceLook {
|
||||
eyes: number | null;
|
||||
}
|
||||
|
||||
/** Below this, eyes count as shut when another frame in the burst is clearly more open. */
|
||||
const EYES_SHUT = 0.45;
|
||||
/** At or above this, eyes count as open enough to prefer over a blink. */
|
||||
const EYES_OPEN = 0.55;
|
||||
/** Minimum gap between best and this frame before a blink penalty applies. */
|
||||
const EYES_GAP = 0.08;
|
||||
|
||||
export function sequenceWeight(frames: readonly SequenceLook[], reportage = false): number[] {
|
||||
const front = frames.some((f) => f.facing === 1);
|
||||
const known = frames.map((f) => f.eyes).filter((v): v is number => v !== null);
|
||||
const best = known.length ? Math.max(...known) : 0;
|
||||
const worst = known.length ? Math.min(...known) : 0;
|
||||
const spread = known.length >= 2 && best - worst >= 0.12;
|
||||
// Reportage: a blink loses hard. Sharpness does not rescue a shut eye when another frame is open.
|
||||
const shut = reportage ? 0.2 : 0.45;
|
||||
const hasOpen = known.some((v) => v >= EYES_OPEN);
|
||||
// A blink loses hard whenever the burst has a clearer open-eye frame. Match and reportage both refuse it.
|
||||
const shut = reportage ? 0.05 : 0.08;
|
||||
return frames.map((f) => {
|
||||
let w = 1;
|
||||
if (front && f.facing === 0) w *= 0.4;
|
||||
if (spread && f.eyes !== null && best - f.eyes >= 0.12 && f.eyes < best * 0.8) w *= shut;
|
||||
if (front && f.facing === 0) w *= 0.05;
|
||||
if (f.eyes === null || !known.length) return w;
|
||||
const gap = best - f.eyes;
|
||||
const clearlyShut = hasOpen && f.eyes < EYES_SHUT && gap >= EYES_GAP;
|
||||
const relativelyShut = gap >= EYES_GAP && f.eyes < best * 0.85;
|
||||
if (clearlyShut || relativelyShut) w *= shut;
|
||||
return w;
|
||||
});
|
||||
}
|
||||
@@ -41,6 +54,7 @@ interface Box {
|
||||
export interface LookPhoto {
|
||||
id: string;
|
||||
capturedAt: Date | null;
|
||||
createdAt?: Date | null;
|
||||
cameraSerial: string | null;
|
||||
cameraModel: string | null;
|
||||
uploaderId: string | null;
|
||||
@@ -131,6 +145,8 @@ export async function sequenceWeights(db: Db, photos: readonly LookPhoto[], gapM
|
||||
...p,
|
||||
camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?",
|
||||
score: 0,
|
||||
// USB / FTP without EXIF: still group by ingest time so a burst is not ten singleton picks.
|
||||
capturedAt: p.capturedAt ?? p.createdAt ?? null,
|
||||
}));
|
||||
const jobs: { photo: LookPhoto; face: FaceBox }[] = [];
|
||||
const looks = new Map<string, SequenceLook>();
|
||||
|
||||
@@ -60,12 +60,17 @@ export interface AutopilotRecord {
|
||||
/** "Only the best": set when the photo's window was decided, and whether it went into the gallery. */
|
||||
curated?: boolean;
|
||||
chosen?: boolean;
|
||||
/**
|
||||
* Planned develop/crop ops from analysis. Applied only when this frame is picked for the burst — never on the
|
||||
* near-duplicates left unflagged.
|
||||
*/
|
||||
ops?: EditCommand[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The autopilot (docs/photo-editing-rules.md §4): analyses each photo as it arrives, then once a burst settles
|
||||
* picks its best frames (open eyes, clear face), applies white balance / tone / level / crop only to those picks,
|
||||
* and optionally delivers them. Runs in the worker.
|
||||
*/
|
||||
export class AutopilotService {
|
||||
constructor(
|
||||
@@ -136,8 +141,14 @@ export class AutopilotService {
|
||||
const detections = load ? await (await load).detect(preview) : null;
|
||||
const focusFile = photo.originalStored ? storage.resolve(photo.storageKey) : preview;
|
||||
const focus = focusFromExifJson(photo.exif) ?? (existsSync(focusFile) ? await readFocusPoint(focusFile) : null);
|
||||
// Faces tell a whole figure from a bust. They may not be ready yet; the crop still refuses a slice.
|
||||
const faces = reportage ? (await db.face.findMany({ where: { photoId }, select: { x0: true, y0: true, x1: true, y1: true } })).map((f) => ({ x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1 })) : [];
|
||||
// Faces tell a whole figure from a bust, and block a soft / faceless body in front from being the subject.
|
||||
// They may not be ready yet; the crop still refuses a soft AF point without a face when faces exist.
|
||||
const faces = (await db.face.findMany({ where: { photoId }, select: { x0: true, y0: true, x1: true, y1: true } })).map((f) => ({
|
||||
x0: f.x0,
|
||||
y0: f.y0,
|
||||
x1: f.x1,
|
||||
y1: f.y1,
|
||||
}));
|
||||
const planned = planFrame({
|
||||
detections,
|
||||
width: W,
|
||||
@@ -156,15 +167,9 @@ export class AutopilotService {
|
||||
const context = reportage ? "reportage" : "sport";
|
||||
|
||||
// Someone already edited it (on the desktop app without a network, before it was uploaded): their edit
|
||||
// stands; the autopilot still scores the frame for its burst.
|
||||
// stands; the autopilot still scores the frame for its burst and will not overwrite on pick.
|
||||
const human = await db.photoEdit.count({ where: { photoId, NOT: { clientId: "autopilot" } } });
|
||||
if (human) ops.length = 0;
|
||||
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,
|
||||
people: detections && composition ? peopleIn(detections, composition.subject) : 0,
|
||||
@@ -177,9 +182,11 @@ export class AutopilotService {
|
||||
focus: subjectFocus(detections, composition?.subject ?? null),
|
||||
plans,
|
||||
style: style && (Object.keys(style.offsets).length || style.cropFactor) ? style : null,
|
||||
// Applied later, only if this frame is a burst pick (not every near-duplicate).
|
||||
ops,
|
||||
};
|
||||
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");
|
||||
log.info({ photoId, planned: ops.length, reason: record.reason }, "autopilot: photo analysed");
|
||||
} catch (err) {
|
||||
log.warn({ photoId, err: (err as Error).message }, "autopilot: failed");
|
||||
await db.photo.update({ where: { id: photoId }, data: { autopilotStatus: "FAILED" } }).catch(() => {});
|
||||
@@ -187,8 +194,9 @@ export class AutopilotService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Picks the best frames of each settled burst: flagged PICK (never overriding a flag someone set), applies the
|
||||
* planned develop/crop only to those picks, gives the second one a slightly tighter crop for variety, and
|
||||
* delivers when the event says so.
|
||||
*/
|
||||
async decideBursts(now = new Date()): Promise<number> {
|
||||
const { db, broadcaster, develop, log } = this.deps;
|
||||
@@ -227,9 +235,12 @@ export class AutopilotService {
|
||||
const sharp = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP).length;
|
||||
const asked = reportage ? reportagePickCount(sharp, settings.picksPerBurst) : settings.picksPerBurst;
|
||||
const planKey = [null, "half", "threeQuarter"] as const;
|
||||
// Drop backs / blinks when the burst has a clearer face with open eyes (look weight already crushed).
|
||||
const usable = burst.filter((f) => (look.get(f.id) ?? 1) >= 0.25);
|
||||
const pool = usable.length ? usable : burst;
|
||||
// Extra frames beyond the event's number are only kept when they can carry a different plan.
|
||||
// The plan stays with the frame: dropping one does not hand its crop to the next.
|
||||
const chosen = bestOf(burst, asked)
|
||||
const chosen = bestOf(pool, asked)
|
||||
.map((f, i) => ({ f, key: planKey[i] ?? null }))
|
||||
.filter(({ f, key }, i) => {
|
||||
if (!reportage || i < settings.picksPerBurst) return true;
|
||||
@@ -243,6 +254,21 @@ export class AutopilotService {
|
||||
broadcaster.library(event.organizationId, { type: "photo.updated", ids: toFlag, patch: { flag: "PICK" } });
|
||||
picked += toFlag.length;
|
||||
}
|
||||
// Apply the planned develop/crop only to the picks — never to the rest of the sequence.
|
||||
for (const framePick of best) {
|
||||
const plannedOps = framePick.rec?.ops ?? [];
|
||||
if (!plannedOps.length) continue;
|
||||
const edited = await db.photoEdit.count({ where: { photoId: framePick.id, NOT: { clientId: "autopilot" } } });
|
||||
if (edited) continue;
|
||||
const already = await db.photoEdit.count({ where: { photoId: framePick.id, clientId: "autopilot" } });
|
||||
if (already) continue;
|
||||
await develop
|
||||
.append(framePick.id, framePick.uploaderId ?? event.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
ops: plannedOps.map((command, i) => ({ opId: `autopilot-${framePick.id}-${i}`, command })),
|
||||
})
|
||||
.catch((err: unknown) => log.warn({ err }, "autopilot: pick edit failed"));
|
||||
}
|
||||
if (reportage) {
|
||||
// A sharp sequence may carry a tighter plan (three-quarter; a half that would cut the hands is not made).
|
||||
// The first frame keeps the whole person. A plan that would cut a neck or the hands, or that matches
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
* 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.
|
||||
* - The subject is who is in focus with a visible face, not who is biggest: blurred / faceless players in
|
||||
* the foreground are scenery (even when the AF point landed on them).
|
||||
* - With a ball in play, the ball and the sharp players contesting it come along. Which ball that is
|
||||
* depends on the sport: handball plays it in the hands, football plays it on the ground.
|
||||
* - The crop is usually two thirds of the frame (the same shape), the subject in the middle across, the upper
|
||||
@@ -200,17 +201,30 @@ function forReportage(d: Detections, faces: readonly Box[]): Detections {
|
||||
}
|
||||
|
||||
/** Who the photo is about. Null when there is nobody clear enough (empty pitch, distant crowd). */
|
||||
export function findSubject(d: Detections, focus?: FocusHint | null, opts?: { reportage?: boolean; sport?: string | null }): { box: Box; reason: Composition["reason"]; people: Detection[]; ball?: Box } | null {
|
||||
export function findSubject(
|
||||
d: Detections,
|
||||
focus?: FocusHint | null,
|
||||
opts?: { reportage?: boolean; sport?: string | null; faces?: readonly Box[] },
|
||||
): { box: Box; reason: Composition["reason"]; people: Detection[]; ball?: Box } | null {
|
||||
const people = d.people.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT);
|
||||
if (!people.length) return null;
|
||||
// The main subject: the person the camera focused on, when that point lands on someone. Otherwise in focus
|
||||
// first, then a reasonable size, then whole in the photo. In reportage a whole figure beats a sharper bust.
|
||||
// The main subject: the person the camera focused on, when that point lands on someone who is sharp and
|
||||
// whose face is visible. A soft / faceless body in the foreground (AF on the jump in front) is scenery —
|
||||
// never the crop's subject when a sharp face sits behind. Otherwise: in focus, then size, then whole.
|
||||
const faces = opts?.faces ?? [];
|
||||
const faced = faces.length ? people.filter((p) => faceOf(p, faces)) : people;
|
||||
const candidates = faced.length ? faced : people;
|
||||
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 whole = opts?.reportage ? people.filter((p) => !p.fragment) : people;
|
||||
const pool = whole.length ? whole : people;
|
||||
const aimed = focus ? personAtFocus(pool, focus) : null;
|
||||
const main = aimed ?? pool.reduce((a, b) => (weight(b) > weight(a) ? b : a));
|
||||
if (!aimed && weight(main) < 0.05) return null;
|
||||
const whole = opts?.reportage ? candidates.filter((p) => !p.fragment) : candidates;
|
||||
const pool = whole.length ? whole : candidates;
|
||||
const sharpest = Math.max(1e-6, ...people.map(sharp));
|
||||
const aimed = focus ? personAtFocus(pool, focus) ?? personAtFocus(people, focus) : null;
|
||||
const aimedOk =
|
||||
!!aimed &&
|
||||
sharp(aimed) >= TUNING.inFocus * sharpest &&
|
||||
(!faces.length || faced.length === 0 || !!faceOf(aimed, faces));
|
||||
const main = (aimedOk ? aimed : null) ?? pool.reduce((a, b) => (weight(b) > weight(a) ? b : a));
|
||||
if (!aimedOk && weight(main) < 0.05) return null;
|
||||
// Reportage keeps a conversation together: someone in the shade is still part of it. A match stays stricter.
|
||||
// A body the frame has already cut in half is not part of that conversation, unless it is the subject.
|
||||
const withMain = opts?.reportage ? 0.35 : TUNING.inFocus;
|
||||
@@ -283,7 +297,8 @@ function personAtFocus(people: Detection[], focus: FocusHint): Detection | null
|
||||
*/
|
||||
export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null {
|
||||
const reportage = opts.context === "reportage";
|
||||
const found = findSubject(reportage ? forReportage(d, opts.faces ?? []) : d, opts.focus, { reportage, sport: opts.sport ?? null });
|
||||
const faces = opts.faces ?? [];
|
||||
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
|
||||
if (!found) return null;
|
||||
const { box: s, reason, people: inSubject, ball } = found;
|
||||
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions
|
||||
@@ -515,7 +530,8 @@ function planCut(p: Detection, at: number): number | null {
|
||||
*/
|
||||
export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: number | null = null, opts: ComposeOptions = {}): Box | null {
|
||||
const reportage = opts.context === "reportage";
|
||||
const found = findSubject(reportage ? forReportage(d, opts.faces ?? []) : d, opts.focus, { reportage, sport: opts.sport ?? null });
|
||||
const faces = opts.faces ?? [];
|
||||
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
|
||||
if (!found) return null;
|
||||
const { box: s, reason, people: inSubject } = found;
|
||||
const tallest = Math.max(...inSubject.map(h));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { findSubject, type Detection } from "./compose.js";
|
||||
import { compose, findSubject, type Detection } from "./compose.js";
|
||||
|
||||
const person = (x0: number, y0: number, x1: number, y1: number, score = 0.9): Detection => ({ x0, y0, x1, y1, score, sharpness: 1 });
|
||||
const frame = { width: 6000, height: 4000, balls: [] };
|
||||
@@ -20,4 +20,22 @@ describe("focus point", () => {
|
||||
const missed = findSubject({ ...frame, people: [big, aimed] }, { x: 0.95, y: 0.05 })!;
|
||||
expect(missed.box.x0).toBeLessThan(0.2);
|
||||
});
|
||||
|
||||
it("ignores AF on a soft faceless jumper in front when a sharp face sits behind", () => {
|
||||
const jumper = { ...person(0.35, 0.05, 0.72, 0.95, 0.95), sharpness: 0.2 };
|
||||
const withBall = { ...person(0.28, 0.28, 0.42, 0.72, 0.9), sharpness: 1 };
|
||||
const mate = { ...person(0.18, 0.3, 0.3, 0.7, 0.85), sharpness: 0.95 };
|
||||
const faces = [
|
||||
{ x0: 0.3, y0: 0.28, x1: 0.38, y1: 0.38 },
|
||||
{ x0: 0.2, y0: 0.3, x1: 0.27, y1: 0.39 },
|
||||
];
|
||||
const found = findSubject({ width: 6000, height: 4000, people: [jumper, withBall, mate], balls: [] }, { x: 0.55, y: 0.35 }, { faces })!;
|
||||
expect(found.people.map((p) => p.x0)).toContain(withBall.x0);
|
||||
expect(found.people.map((p) => p.x0)).not.toContain(jumper.x0);
|
||||
const c = compose({ width: 6000, height: 4000, people: [jumper, withBall, mate], balls: [] }, null, {
|
||||
focus: { x: 0.55, y: 0.35 },
|
||||
faces,
|
||||
})!;
|
||||
expect(c.subject.y0).toBeGreaterThan(jumper.y0 + 0.1);
|
||||
});
|
||||
});
|
||||
@@ -3,9 +3,9 @@ import { type Box, type Detections, type FocusHint, compose, minCropWidth, planC
|
||||
import { constrainRotated, tighter } from "./geometry.js";
|
||||
import { type Look, WB_KEYS, TONE_KEYS, detailForCrop, lookValues, toneApplied } from "../autopilot/look.js";
|
||||
|
||||
/** Straightening beyond this is more likely a creative tilt than a crooked horizon. */
|
||||
const MAX_LEVEL = 5;
|
||||
const MIN_LEVEL = 0.3;
|
||||
/** Straightening beyond this is more likely a creative tilt than a crooked horizon (matches the engine's band). */
|
||||
const MAX_LEVEL = 8;
|
||||
const MIN_LEVEL = 0.25;
|
||||
/** A crop this close to the whole frame is not worth making. */
|
||||
const KEEP_WHOLE = 0.92;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type CreatedStamp, toExiftoolArgs, type IptcValues } from "@photoreport/metadata";
|
||||
import { type CreatedStamp, type LibraryMarks, toExiftoolArgs, type IptcValues } from "@photoreport/metadata";
|
||||
import { exiftool } from "exiftool-vendored";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -34,7 +34,7 @@ export interface RenderOptions {
|
||||
* quality, camera EXIF and colour profile kept, IPTC written into both IIM and XMP. A file that is already at
|
||||
* least {@link CROP_FLOOR_PX} and only a little under `longEdge` is enlarged up to it. Anything smaller stays.
|
||||
*/
|
||||
export async function renderDelivery(original: string, iptc: IptcValues, opts: RenderOptions, created?: CreatedStamp, edit?: DeliveryEdit): Promise<Buffer> {
|
||||
export async function renderDelivery(original: string, iptc: IptcValues, opts: RenderOptions, created?: CreatedStamp, edit?: DeliveryEdit, marks?: LibraryMarks): Promise<Buffer> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-render-"));
|
||||
const file = path.join(dir, "out.jpg");
|
||||
const exif = opts.exif !== false;
|
||||
@@ -44,6 +44,7 @@ export async function renderDelivery(original: string, iptc: IptcValues, opts: R
|
||||
return img.jpeg({ quality: opts.quality, chromaSubsampling: "4:4:4", mozjpeg: false }).toBuffer();
|
||||
};
|
||||
const dpi = opts.dpi ? [`-XResolution=${opts.dpi}`, `-YResolution=${opts.dpi}`, "-ResolutionUnit=inches", `-JFIF:XResolution=${opts.dpi}`, `-JFIF:YResolution=${opts.dpi}`, "-JFIF:ResolutionUnit=inches"] : [];
|
||||
const meta = toExiftoolArgs(iptc, created, marks);
|
||||
try {
|
||||
if (edit) {
|
||||
// Edited: the develop engine renders the original (crop and all) straight to the delivered size, in sRGB,
|
||||
@@ -54,13 +55,13 @@ export async function renderDelivery(original: string, iptc: IptcValues, opts: R
|
||||
await writeFile(file, opts.sharpen || opts.quality < 100 ? await finish(sharp(rendered)) : await readFile(rendered));
|
||||
// The camera EXIF is copied back, without the orientation (the pixels are already upright).
|
||||
const copyExif = exif ? ["-TagsFromFile", original, "-EXIF:all", "--Orientation", "--ThumbnailImage", "--PreviewImage", "-Orientation#=1"] : [];
|
||||
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...copyExif, ...dpi, ...toExiftoolArgs(iptc, created)] });
|
||||
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...copyExif, ...dpi, ...meta] });
|
||||
return await readFile(file);
|
||||
}
|
||||
let img = sharp(original).rotate().resize({ width: opts.longEdge, height: opts.longEdge, fit: "inside", withoutEnlargement: true });
|
||||
if (exif) img = img.keepExif();
|
||||
await writeFile(file, await finish(img));
|
||||
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...dpi, ...toExiftoolArgs(iptc, created)] });
|
||||
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...dpi, ...meta] });
|
||||
return await readFile(file);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
@@ -71,12 +72,12 @@ export async function renderDelivery(original: string, iptc: IptcValues, opts: R
|
||||
* The original as it arrived, untouched (no resizing, no recompression, the camera's EXIF and profile as they
|
||||
* are), with the IPTC written into it as Photo Mechanic does on ingest: a copy for one's own backup.
|
||||
*/
|
||||
export async function originalWithMetadata(original: string, iptc: IptcValues, created?: CreatedStamp): Promise<Buffer> {
|
||||
export async function originalWithMetadata(original: string, iptc: IptcValues, created?: CreatedStamp, marks?: LibraryMarks): Promise<Buffer> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-original-"));
|
||||
const file = path.join(dir, `copy${path.extname(original).toLowerCase() || ".jpg"}`);
|
||||
try {
|
||||
await writeFile(file, await readFile(original));
|
||||
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...toExiftoolArgs(iptc, created)] });
|
||||
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...toExiftoolArgs(iptc, created, marks)] });
|
||||
return await readFile(file);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
|
||||
@@ -570,11 +570,13 @@ export class DeliveryService {
|
||||
const fileName = renderFileName(recipe.fileNameTemplate, named, sendOriginals && untouched ? item.photo.originalName : deliveredName(item.photo));
|
||||
const edit = sendOriginals ? undefined : await this.editFor(item.photoId, item.photo.developSeq);
|
||||
const created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined;
|
||||
// Cull marks (pick / reject / stars) go into XMP so Lightroom sees rating + green label on import.
|
||||
const marks = { flag: item.photo.flag, rating: item.photo.rating };
|
||||
const rendered = sendOriginals
|
||||
? untouched
|
||||
? await readFile(source)
|
||||
: await originalWithMetadata(source, iptc?.values ?? {}, created)
|
||||
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: recipe.longEdge, quality: recipe.jpegQuality, sharpen: recipe.sharpen, dpi: recipe.dpi, exif: recipe.keepExif, srgb: recipe.srgb }, created, edit);
|
||||
: await originalWithMetadata(source, iptc?.values ?? {}, created, marks)
|
||||
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: recipe.longEdge, quality: recipe.jpegQuality, sharpen: recipe.sharpen, dpi: recipe.dpi, exif: recipe.keepExif, srgb: recipe.srgb }, created, edit, marks);
|
||||
const data = rendered;
|
||||
if (item.target.kind === "LOCAL") {
|
||||
// Kept here until the computer's desktop app takes it (localClaim → localFile → localResult).
|
||||
|
||||
@@ -49,6 +49,11 @@ describe("bursts", () => {
|
||||
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("groups by ingest time when capture time is missing, so a USB burst is not ten singleton picks", () => {
|
||||
const t = (id: string, ms: number) => ({ id, capturedAt: null, createdAt: new Date(1_800_000_000_000 + ms), camera: "R1", score: 1 });
|
||||
const bursts = groupBursts([t("a", 0), t("b", 200), t("c", 400), t("d", 5000)], 1500);
|
||||
expect(bursts.map((b) => b.map((x) => x.id))).toEqual([["a", "b", "c"], ["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"]);
|
||||
@@ -205,11 +210,15 @@ describe("autopilot", () => {
|
||||
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 or by hand: measured tone, level, a crop around the subject; archive re-imports stay as sent", async () => {
|
||||
it("analyses what arrives, then edits only the burst picks: measured tone, level, a crop; archive re-imports 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, "CLOUD");
|
||||
await runQueue();
|
||||
// Analysis only: develop edits wait until the burst is picked.
|
||||
expect(await ctx.db.photoEdit.count({ where: { photoId: ftp } })).toBe(0);
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: ftp } })).autopilotStatus).toBe("DONE");
|
||||
expect(await autopilot.decideBursts(new Date(Date.now() + 20_000))).toBe(1);
|
||||
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);
|
||||
@@ -223,7 +232,7 @@ describe("autopilot", () => {
|
||||
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 () => {
|
||||
it("picks the sharpest frames of each burst once it has settled, edits only those, 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);
|
||||
@@ -234,9 +243,14 @@ describe("autopilot", () => {
|
||||
await runQueue();
|
||||
// Too soon: the burst may still be arriving.
|
||||
expect(await autopilot.decideBursts(new Date())).toBe(0);
|
||||
expect(await ctx.db.photoEdit.count({ where: { photoId: { in: [a, b, c, d] } } })).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" });
|
||||
// Only the picks got the planned develop/crop; the rest of the sequence stays untouched.
|
||||
expect(await ctx.db.photoEdit.count({ where: { photoId: b, clientId: "autopilot" } })).toBeGreaterThan(0);
|
||||
expect(await ctx.db.photoEdit.count({ where: { photoId: a } })).toBe(0);
|
||||
expect(await ctx.db.photoEdit.count({ where: { photoId: d } })).toBe(0);
|
||||
// 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.
|
||||
@@ -310,6 +324,7 @@ describe("autopilot", () => {
|
||||
const photoId = await shot(orgId, userId, eventId, 0, 300);
|
||||
await develop.append(photoId, userId, { clientId: "offline-queue", ops: [{ opId: "mine-1", command: { command: "develop.set", params: { values: { "light.exposure": -0.5 } } } }] });
|
||||
await runQueue();
|
||||
await autopilot.decideBursts(new Date(Date.now() + 20_000));
|
||||
const edits = await ctx.db.photoEdit.findMany({ where: { photoId } });
|
||||
expect(edits.map((e) => e.clientId)).toEqual(["offline-queue"]);
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).autopilotStatus).toBe("DONE");
|
||||
@@ -321,6 +336,7 @@ describe("autopilot", () => {
|
||||
const id = await shot(orgId, userId, eventId, 0, 300);
|
||||
await ctx.db.photo.update({ where: { id }, data: { iso: 6400 } });
|
||||
await runQueue();
|
||||
await autopilot.decideBursts(new Date(Date.now() + 20_000));
|
||||
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } });
|
||||
const values = (edits[0]!.command as { params: { values: Record<string, number> } }).params.values;
|
||||
// Sharpen starts at 40 and is scaled when the crop does not keep the whole frame (detailForCrop).
|
||||
@@ -340,6 +356,7 @@ describe("autopilot", () => {
|
||||
const photos: string[] = [];
|
||||
for (let i = 0; i < 6; i++) photos.push(await shot(orgId, userId, eventId, i * 10_000, 300));
|
||||
await runQueue();
|
||||
await autopilot.decideBursts(new Date(Date.now() + 20_000));
|
||||
// The photographer lifts the exposure (0.2 -> 0.5) and crops tighter on five of them.
|
||||
for (const id of photos.slice(0, 5)) {
|
||||
const auto = fold((await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } })).map((e) => e.command as never));
|
||||
@@ -358,6 +375,7 @@ describe("autopilot", () => {
|
||||
|
||||
const next = await shot(orgId, userId, eventId, 100_000, 300);
|
||||
await runQueue();
|
||||
await autopilot.decideBursts(new Date(Date.now() + 20_000));
|
||||
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: next }, orderBy: { seq: "asc" } });
|
||||
expect((edits[0]!.command as { params: { values: Record<string, number> } }).params.values).toEqual({ "light.exposure": 0.5, "light.contrast": 10 });
|
||||
const before = fold((await ctx.db.photoEdit.findMany({ where: { photoId: photos[5]! }, orderBy: { seq: "asc" } })).map((e) => e.command as never)).crop!;
|
||||
|
||||
@@ -514,7 +514,7 @@ export const t = {
|
||||
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.",
|
||||
help: "As fotos que chegam por FTP ou pelo ingest da app são analisadas ao chegar; quando a sequência fecha, só as melhores ficam escolhidas e editadas (recorte, nivelar, tom) — na desktop também sem rede. Tudo pode ser desfeito no Revelar. Fotos importadas à mão não são tocadas.",
|
||||
crop: "Recortar",
|
||||
level: "Nivelar",
|
||||
tone: "Tom",
|
||||
@@ -1382,7 +1382,7 @@ export const t = {
|
||||
chegada: {
|
||||
title: "Quando a foto chega",
|
||||
paras: [
|
||||
"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.",
|
||||
"As fotos que chegam por FTP ou pelo ingest da app são analisadas ao chegar; quando a sequência fecha, só as melhores ficam escolhidas e editadas (recorte, nivelar, tom) — na desktop também sem rede. Tudo pode ser desfeito no Revelar. Fotos importadas à mão não são tocadas.",
|
||||
"No teu computador, os nomes das pessoas só ficam guardados quando o evento tem adversário. Num estágio ou numa reportagem, identificar caras fica no servidor.",
|
||||
],
|
||||
},
|
||||
|
||||
@@ -214,7 +214,16 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
const event = events.find((e) => e.id === eventId);
|
||||
// The cloud must not wait for detection. One at a time, or a full card freezes the window.
|
||||
const plan = autopilotChain.current.then(() =>
|
||||
planLocalAutopilot({ api, orgId, event, sha256: info.sha256, preview, width: info.width, height: info.height }).catch(() => {}),
|
||||
planLocalAutopilot({
|
||||
api,
|
||||
orgId,
|
||||
event,
|
||||
sha256: info.sha256,
|
||||
preview,
|
||||
width: info.width,
|
||||
height: info.height,
|
||||
capturedAt,
|
||||
}).catch(() => {}),
|
||||
);
|
||||
autopilotChain.current = plan.then(
|
||||
() => undefined,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { decidePending, type PendingFrame } from "./autopilot.js";
|
||||
|
||||
const BURST_SETTLE_MS = 15_000;
|
||||
|
||||
function frame(sha: string, atMs: number, score: number, createdOffset = 0): PendingFrame {
|
||||
return {
|
||||
sha256: sha,
|
||||
capturedAt: new Date(1_800_000_000_000 + atMs).toISOString(),
|
||||
createdAt: 1_800_000_000_000 + atMs + createdOffset,
|
||||
camera: "R1",
|
||||
score,
|
||||
ops: [{ command: "develop.set", params: { values: { "light.exposure": score } } } as PendingFrame["ops"][number]],
|
||||
};
|
||||
}
|
||||
|
||||
describe("local burst autopilot", () => {
|
||||
it("edits only the best frames of a settled burst, not the whole sequence", () => {
|
||||
const pending = [frame("a", 0, 1), frame("b", 100, 9), frame("c", 200, 5), frame("d", 300, 2)];
|
||||
const now = 1_800_000_000_000 + 300 + BURST_SETTLE_MS + 1;
|
||||
const { picked, updated } = decidePending(pending, 2, 1500, now);
|
||||
expect(picked.map((f) => f.sha256)).toEqual(["b", "c"]);
|
||||
expect(updated.every((f) => f.decided)).toBe(true);
|
||||
});
|
||||
|
||||
it("waits while frames are still arriving", () => {
|
||||
const pending = [frame("a", 0, 1), frame("b", 100, 9)];
|
||||
const now = 1_800_000_000_000 + 100 + 1_000;
|
||||
const { picked, updated } = decidePending(pending, 2, 1500, now);
|
||||
expect(picked).toEqual([]);
|
||||
expect(updated.every((f) => !f.decided)).toBe(true);
|
||||
});
|
||||
|
||||
it("groups by ingest time when capture time is missing", () => {
|
||||
const pending: PendingFrame[] = [
|
||||
{ sha256: "a", capturedAt: null, createdAt: 1_000, camera: "R1", score: 1, ops: [] },
|
||||
{ sha256: "b", capturedAt: null, createdAt: 1_200, camera: "R1", score: 8, ops: [] },
|
||||
{ sha256: "c", capturedAt: null, createdAt: 1_400, camera: "R1", score: 3, ops: [] },
|
||||
];
|
||||
const { picked } = decidePending(pending, 1, 1500, 1_400 + BURST_SETTLE_MS + 1);
|
||||
expect(picked.map((f) => f.sha256)).toEqual(["b"]);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,34 @@
|
||||
import { AutopilotSettings } from "@photoreport/contracts";
|
||||
import { AutopilotSettings, type EditCommand } from "@photoreport/contracts";
|
||||
import type { ApiClient, AutopilotStyle, EventSummary } from "@photoreport/sdk";
|
||||
import { isReportage } from "../../../api/src/composition/compose.js";
|
||||
import { frameScore, isReportage } from "../../../api/src/composition/compose.js";
|
||||
import { levelAngle, measuredValues, planFrame } from "../../../api/src/composition/planFrame.js";
|
||||
import { bestOf, groupBursts } from "../../../api/src/autopilot/bursts.js";
|
||||
import { loadEngine } from "../develop/engine.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { detectPreview } from "./detectLocal.js";
|
||||
import { kv } from "./kv.js";
|
||||
import { localPhotos } from "./local.js";
|
||||
import { localId, offlineQueue } from "./queue.js";
|
||||
|
||||
/** Same settle window as the server: a burst is decided once no new frame has arrived for this long. */
|
||||
const BURST_SETTLE_MS = 15_000;
|
||||
const PENDING_KEY = (orgId: string, eventId: string) => `autopilot:pending:${orgId}:${eventId}`;
|
||||
|
||||
export interface PendingFrame {
|
||||
sha256: string;
|
||||
capturedAt: string | null;
|
||||
createdAt: number;
|
||||
camera: string;
|
||||
score: number;
|
||||
ops: EditCommand[];
|
||||
decided?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same autopilot edit the server would make, on the preview already on this computer, before it is uploaded.
|
||||
* If the model or the engine isn't available, nothing is queued and the server edits the photo as before.
|
||||
* Local autopilot (docs/photo-editing-rules.md §4, AGENTS local-first): analyse every frame on this computer,
|
||||
* wait for the burst to settle, pick the best 1–N, and apply develop/crop/level **only to those picks**.
|
||||
* Works offline once the YOLOX model and style cache are on disk. Web/server remain the sync glue — they do not
|
||||
* gate culling or editing on the desktop.
|
||||
*/
|
||||
export async function planLocalAutopilot(args: {
|
||||
api: ApiClient;
|
||||
@@ -21,8 +39,10 @@ export async function planLocalAutopilot(args: {
|
||||
width: number;
|
||||
height: number;
|
||||
iso?: number | null;
|
||||
capturedAt?: string | null;
|
||||
camera?: string | null;
|
||||
}): Promise<void> {
|
||||
if (!isDesktop() || !args.orgId || !args.event?.autopilot) return;
|
||||
if (!isDesktop() || !args.orgId || !args.event?.autopilot || !args.event.id) return;
|
||||
const settings = AutopilotSettings.parse(args.event.autopilot);
|
||||
if (!settings.enabled) return;
|
||||
const reportage = isReportage(args.event);
|
||||
@@ -31,7 +51,7 @@ export async function planLocalAutopilot(args: {
|
||||
detectPreview(args.api, args.orgId, args.preview),
|
||||
styleFor(args.api, args.orgId, args.event.venue),
|
||||
]);
|
||||
// Both have to be here. A crop without the tone, or the reverse, would stop the server doing the rest.
|
||||
// Model or engine missing (first run with no cache): leave the frame alone; a later pass or the server can still help.
|
||||
if (!measured || !detections) return;
|
||||
const angle = levelAngle(measured.angle, settings.level);
|
||||
const values = measuredValues(measured.values, settings, args.iso ?? null, style?.offsets ?? {});
|
||||
@@ -46,10 +66,92 @@ export async function planLocalAutopilot(args: {
|
||||
sport: args.event.sport,
|
||||
settings,
|
||||
});
|
||||
if (!planned.ops.length) return;
|
||||
const queue = offlineQueue(args.orgId);
|
||||
const photoId = localId(args.sha256);
|
||||
for (const command of planned.ops) queue.enqueueEdit(photoId, command);
|
||||
const score = frameScore(detections, planned.composition);
|
||||
const frame: PendingFrame = {
|
||||
sha256: args.sha256,
|
||||
capturedAt: args.capturedAt ?? null,
|
||||
createdAt: Date.now(),
|
||||
camera: args.camera?.trim() || "local",
|
||||
score,
|
||||
ops: planned.ops,
|
||||
};
|
||||
const pending = await loadPending(args.orgId, args.event.id);
|
||||
const next = [...pending.filter((f) => f.sha256 !== frame.sha256), frame];
|
||||
await savePending(args.orgId, args.event.id, next);
|
||||
scheduleSettle(args.orgId, args.event.id, settings.picksPerBurst, settings.burstGapSec * 1000);
|
||||
}
|
||||
|
||||
const timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
|
||||
function scheduleSettle(orgId: string, eventId: string, picksPerBurst: number, gapMs: number): void {
|
||||
const key = `${orgId}:${eventId}`;
|
||||
const prev = timers.get(key);
|
||||
if (prev) clearTimeout(prev);
|
||||
timers.set(
|
||||
key,
|
||||
setTimeout(() => {
|
||||
timers.delete(key);
|
||||
void settleEvent(orgId, eventId, picksPerBurst, gapMs);
|
||||
}, BURST_SETTLE_MS + 250),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which frames of the pending list become picks once their burst has settled. Pure: no I/O.
|
||||
* Undecided frames in a burst that is still arriving are left alone.
|
||||
*/
|
||||
export function decidePending(pending: readonly PendingFrame[], picksPerBurst: number, gapMs: number, now: number): { updated: PendingFrame[]; picked: PendingFrame[] } {
|
||||
const updated = pending.map((f) => ({ ...f }));
|
||||
const picked: PendingFrame[] = [];
|
||||
const frames = updated.map((f) => ({
|
||||
...f,
|
||||
id: f.sha256,
|
||||
capturedAt: f.capturedAt ? new Date(f.capturedAt) : null,
|
||||
createdAt: new Date(f.createdAt),
|
||||
score: f.score as number | null,
|
||||
}));
|
||||
for (const burst of groupBursts(frames, gapMs)) {
|
||||
if (burst.every((f) => f.decided)) continue;
|
||||
const latest = Math.max(...burst.map((f) => f.createdAt.getTime()));
|
||||
if (latest > now - BURST_SETTLE_MS) continue;
|
||||
const chosen = new Set(bestOf(burst, picksPerBurst).map((f) => f.sha256));
|
||||
for (const frame of burst) {
|
||||
const row = updated.find((u) => u.sha256 === frame.sha256);
|
||||
if (row) row.decided = true;
|
||||
if (chosen.has(frame.sha256) && row) picked.push(row);
|
||||
}
|
||||
}
|
||||
return { updated, picked };
|
||||
}
|
||||
|
||||
/** Picks settled bursts and applies edits only to the chosen frames. */
|
||||
export async function settleEvent(orgId: string, eventId: string, picksPerBurst: number, gapMs: number, now = Date.now()): Promise<string[]> {
|
||||
const pending = await loadPending(orgId, eventId);
|
||||
if (!pending.length) return [];
|
||||
const { updated, picked } = decidePending(pending, picksPerBurst, gapMs, now);
|
||||
for (const frame of picked) applyPick(orgId, frame.sha256, frame.ops);
|
||||
await savePending(orgId, eventId, updated);
|
||||
if (updated.some((f) => !f.decided)) scheduleSettle(orgId, eventId, picksPerBurst, gapMs);
|
||||
return picked.map((f) => f.sha256);
|
||||
}
|
||||
|
||||
function applyPick(orgId: string, sha256: string, ops: EditCommand[]): void {
|
||||
const photoId = localId(sha256);
|
||||
const queue = offlineQueue(orgId);
|
||||
for (const command of ops) queue.enqueueEdit(photoId, command);
|
||||
queue.add({ kind: "patch", ids: [photoId], patch: { flag: "PICK" } });
|
||||
localPhotos.patch(photoId, { flag: "PICK" });
|
||||
}
|
||||
|
||||
async function loadPending(orgId: string, eventId: string): Promise<PendingFrame[]> {
|
||||
const raw = await kv.get<PendingFrame[]>(PENDING_KEY(orgId, eventId));
|
||||
return Array.isArray(raw) ? raw : [];
|
||||
}
|
||||
|
||||
async function savePending(orgId: string, eventId: string, frames: PendingFrame[]): Promise<void> {
|
||||
// Keep recent undecided + a little history; bursts finish within minutes.
|
||||
const trimmed = frames.slice(-400);
|
||||
await kv.set(PENDING_KEY(orgId, eventId), trimmed);
|
||||
}
|
||||
|
||||
async function measure(bytes: ArrayBuffer): Promise<{ values: Record<string, number>; angle: number | null } | null> {
|
||||
@@ -64,7 +166,8 @@ async function measure(bytes: ArrayBuffer): Promise<{ values: Record<string, num
|
||||
if (photo.autoLevelScene) {
|
||||
const scene = JSON.parse(photo.autoLevelScene()) as Record<string, number>;
|
||||
if (typeof scene["crop.angle"] === "number") angle = scene["crop.angle"];
|
||||
} else {
|
||||
}
|
||||
if (angle === null) {
|
||||
const level = JSON.parse(photo.autoLevel(settings)) as Record<string, number>;
|
||||
if (typeof level["crop.angle"] === "number") angle = level["crop.angle"];
|
||||
}
|
||||
|
||||
@@ -165,6 +165,7 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
cam.openRequested = NO;
|
||||
cam.state = @"idle";
|
||||
self.cams[uuid] = cam;
|
||||
[self loadFetchedInto:cam];
|
||||
}
|
||||
cam.device = (ICCameraDevice *)device;
|
||||
cam.name = device.name ?: @"Câmara";
|
||||
@@ -354,19 +355,31 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
if (cam.pendingDownloads == 0) [self closeWhenIdle:cam];
|
||||
}
|
||||
|
||||
- (NSString *)uniqueName:(NSString *)original {
|
||||
NSString *base = original.lastPathComponent ?: @"photo.JPG";
|
||||
NSString *stem = base.stringByDeletingPathExtension;
|
||||
NSString *ext = base.pathExtension;
|
||||
NSString *candidate = base;
|
||||
NSFileManager *fm = [NSFileManager defaultManager];
|
||||
for (int n = 1; n < 1000; n++) {
|
||||
if (![fm fileExistsAtPath:[self.dir stringByAppendingPathComponent:candidate]]) return candidate;
|
||||
candidate = ext.length
|
||||
? [NSString stringWithFormat:@"%@-%d.%@", stem, n, ext]
|
||||
: [NSString stringWithFormat:@"%@-%d", stem, n];
|
||||
- (NSString *)fetchedPath {
|
||||
return self.dir.length ? [self.dir stringByAppendingPathComponent:@".fetched"] : nil;
|
||||
}
|
||||
|
||||
- (void)rememberFetched:(NSString *)name cam:(PRCam *)cam {
|
||||
if (!name.length || !cam) return;
|
||||
[cam.fetched addObject:name];
|
||||
NSString *path = [self fetchedPath];
|
||||
if (!path.length) return;
|
||||
NSMutableSet *all = [NSMutableSet setWithObject:name];
|
||||
NSString *prev = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
|
||||
for (NSString *line in [prev componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
|
||||
if (line.length) [all addObject:line];
|
||||
}
|
||||
NSArray *sorted = [[all allObjects] sortedArrayUsingSelector:@selector(compare:)];
|
||||
[[sorted componentsJoinedByString:@"\n"] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
|
||||
}
|
||||
|
||||
- (void)loadFetchedInto:(PRCam *)cam {
|
||||
NSString *path = [self fetchedPath];
|
||||
if (!path.length || !cam) return;
|
||||
NSString *prev = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
|
||||
for (NSString *line in [prev componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
|
||||
if (line.length) [cam.fetched addObject:line];
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
- (void)download:(ICCameraFile *)file cam:(PRCam *)cam {
|
||||
@@ -374,15 +387,23 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
if ([cam.fetched containsObject:file.name]) return;
|
||||
NSFileManager *fm = [NSFileManager defaultManager];
|
||||
[fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil];
|
||||
NSString *save = [self uniqueName:file.name];
|
||||
// Keep the camera's name. A leftover ingest copy of the same shot must not become PSR1-1.JPG.
|
||||
NSString *existing = [self.dir stringByAppendingPathComponent:file.name];
|
||||
NSDictionary *attrs = [fm attributesOfItemAtPath:existing error:nil];
|
||||
if (attrs && [attrs fileSize] > 0) {
|
||||
[self rememberFetched:file.name cam:cam];
|
||||
emit(@{@"kind": @"file", @"path": existing, @"name": file.name, @"size": @([attrs fileSize])});
|
||||
return;
|
||||
}
|
||||
if (attrs) [fm removeItemAtPath:existing error:nil];
|
||||
NSURL *url = [NSURL fileURLWithPath:self.dir isDirectory:YES];
|
||||
if (!url) return;
|
||||
[cam.fetched addObject:file.name];
|
||||
[self rememberFetched:file.name cam:cam];
|
||||
cam.pendingDownloads++;
|
||||
NSDictionary *options = @{
|
||||
ICDownloadsDirectoryURL: url,
|
||||
ICSaveAsFilename: save,
|
||||
ICOverwrite: @NO,
|
||||
ICSaveAsFilename: file.name,
|
||||
ICOverwrite: @YES,
|
||||
ICDeleteAfterSuccessfulDownload: @NO,
|
||||
};
|
||||
#pragma clang diagnostic push
|
||||
@@ -567,6 +588,15 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
if (error || self.dir.length == 0) {
|
||||
if (cam && file.name) {
|
||||
[cam.fetched removeObject:file.name];
|
||||
NSString *path = [self fetchedPath];
|
||||
if (path.length) {
|
||||
NSMutableArray *keep = [NSMutableArray array];
|
||||
NSString *prev = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
|
||||
for (NSString *line in [prev componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
|
||||
if (line.length && ![line isEqualToString:file.name]) [keep addObject:line];
|
||||
}
|
||||
[[keep componentsJoinedByString:@"\n"] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
|
||||
}
|
||||
[self publishCatalog:cam];
|
||||
}
|
||||
if (cam) [self closeWhenIdle:cam];
|
||||
@@ -614,7 +644,10 @@ void pr_camera_set_dir(const char *dir) {
|
||||
NSString *path = dir ? [NSString stringWithUTF8String:dir] : @"";
|
||||
on_main(^{
|
||||
g_dir = [path copy];
|
||||
g_hub.dir = g_dir;
|
||||
if (g_hub) {
|
||||
g_hub.dir = g_dir;
|
||||
for (NSString *key in g_hub.cams) [g_hub loadFetchedInto:g_hub.cams[key]];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -700,36 +700,37 @@ impl FtpState {
|
||||
.ok_or("bad_path")?
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let (stem, ext) = match name.rsplit_once('.') {
|
||||
Some((s, e)) => (s.to_string(), format!(".{e}")),
|
||||
None => (name.clone(), String::new()),
|
||||
let stem = match name.rsplit_once('.') {
|
||||
Some((s, _)) => s.to_string(),
|
||||
None => name.clone(),
|
||||
};
|
||||
let mut target = dir.join(&name);
|
||||
let mut n = 1;
|
||||
while target.exists() {
|
||||
target = dir.join(format!("{stem}-{n}{ext}"));
|
||||
n += 1;
|
||||
}
|
||||
let target = dir.join(&name);
|
||||
let sidecars = if is_photo(&p) {
|
||||
raw_sidecars(&p)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let paired = target
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| stem.clone());
|
||||
// Same camera name already in the work folder (USB re-import / server duplicate): drop the
|
||||
// ingest copy — never invent PSR1-1.JPG, PSR1-2.JPG beside the first filing.
|
||||
if target.exists() {
|
||||
let _ = std::fs::remove_file(&p);
|
||||
for raw in &sidecars {
|
||||
let _ = std::fs::remove_file(raw);
|
||||
}
|
||||
self.taken.lock().unwrap().remove(path);
|
||||
return Ok(target.to_string_lossy().into_owned());
|
||||
}
|
||||
let paired = stem.clone();
|
||||
move_file(&p, &target).map_err(|e| e.to_string())?;
|
||||
for raw in sidecars {
|
||||
let raw_ext = raw
|
||||
.extension()
|
||||
.map(|e| e.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let mut raw_target = dir.join(format!("{paired}.{raw_ext}"));
|
||||
let mut k = 1;
|
||||
while raw_target.exists() {
|
||||
raw_target = dir.join(format!("{paired}-{k}.{raw_ext}"));
|
||||
k += 1;
|
||||
let raw_target = dir.join(format!("{paired}.{raw_ext}"));
|
||||
if raw_target.exists() {
|
||||
let _ = std::fs::remove_file(&raw);
|
||||
continue;
|
||||
}
|
||||
let _ = move_file(&raw, &raw_target);
|
||||
}
|
||||
@@ -1092,6 +1093,22 @@ mod tests {
|
||||
assert!(moved.with_extension("CR3").is_file());
|
||||
assert!(!jpeg.exists());
|
||||
assert!(!ingest.join("IMG_0001.CR3").exists());
|
||||
// A second send of the same camera name (USB re-pull / server duplicate) must not invent -1 copies.
|
||||
std::fs::write(ingest.join("IMG_0001.JPG"), [0xFFu8, 0xD8, 0xFF, 0xD9]).unwrap();
|
||||
let again = state
|
||||
.sent(
|
||||
ingest.join("IMG_0001.JPG").to_str().unwrap(),
|
||||
"POR x SUI",
|
||||
"2026-11-04",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(PathBuf::from(&again), moved);
|
||||
assert!(!ingest.join("IMG_0001.JPG").exists());
|
||||
assert!(!moved
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("IMG_0001-1.JPG")
|
||||
.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ This file is the in-repo summary agents work from. Decisions dated 2026-10-11.
|
||||
## Decisions
|
||||
|
||||
- One monorepo, one API, one PostgreSQL database, one account system, one UI for web and desktop.
|
||||
- **Local-first:** every photographer-facing feature must work on the desktop without the network; the web/API
|
||||
are the sync and multi-user glue. Offline work syncs when a link returns. Do not require uploading every frame
|
||||
for decisions that can run on the machine (AGENTS.md §12). Prefer Rust (`engine/`) for heavy local work (§13).
|
||||
- Built greenfield on new containers and the `next` environment; old projects keep running until cutover.
|
||||
Final domain: `app.photoreport.pt`. Data (accounts, galleries, sales, squads) is imported, not restarted.
|
||||
- Desktop = Tauri around the same React SPA (replaces the Flutter Studio).
|
||||
@@ -424,6 +427,11 @@ Each target also has Photo Mechanic's uploader output options: fit-in-box size,
|
||||
sharpening, ppi, keep or drop the camera EXIF, and conversion to sRGB. Targets can be duplicated (same server and
|
||||
credentials, another name and folder).
|
||||
|
||||
**Cull marks on delivery.** A pick (⚑), reject (✕) and star rating are written into the delivered JPEG
|
||||
(`XMP-xmp:Rating`, colour label Green for picks, digiKam `PickLabel`, IPTC Urgency). Lightroom's Flagged
|
||||
filter is catalog-only and will not show third-party picks; filter by **rating** or **green label** after
|
||||
import. Photo Mechanic reads Urgency / PickLabel.
|
||||
|
||||
**Photo Mechanic compatibility (templates and IPTC).** Every template (IPTC pad, folders, file names, rename on
|
||||
arrival) takes every variable of Photo Mechanic's list, under its names and short names, in any case
|
||||
(`packages/metadata/src/pmvars.ts`), and its modifiers: substrings `{var:index,count}` (negative index from the
|
||||
|
||||
+31
-19
@@ -20,10 +20,11 @@ Following the AP and NPPA codes:
|
||||
## 2. Crop
|
||||
|
||||
- **Who:** the subject is the person the camera focused on, when the file has a focus point (EXIF SubjectArea:
|
||||
the autofocus point, shown by Photo Mechanic). That person wins even if someone else is larger. With no point,
|
||||
or a point on nobody, the subject is the person in focus, not the biggest one. With a ball in play, the ball and
|
||||
everyone contesting it come along. Without one, the subject and the sharp people with them (a duel, a
|
||||
celebration, a line-up).
|
||||
the autofocus point, shown by Photo Mechanic) **and that person is sharp with a fully visible face**. A soft or
|
||||
faceless body in the foreground (AF landed on the jump in front) is scenery — never the crop — when a sharp
|
||||
face sits behind. With no usable point, the subject is the sharp person with a face, not the biggest one. With
|
||||
a ball in play, the ball and everyone contesting it come along. Without one, the subject and the sharp people
|
||||
with them (a duel, a celebration, a line-up). Non-person photos (empty pitch, kit detail) are unchanged.
|
||||
- **Who is not the subject:** they are in whole, or they are out. A person the photo has already cut in half
|
||||
stays out when the crop can move into the clean space around the subject. When leaving them out would cut the
|
||||
subject or the ball, the crop does the best it can. The subject themselves may stand at the frame edge.
|
||||
@@ -85,10 +86,12 @@ A camera at 10–30 frames per second sends several photos of the same moment.
|
||||
- **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).
|
||||
- **Facing and eyes:** inside one burst, a frame of a player from behind loses to a frame where the face is
|
||||
visible, and shut eyes lose to open ones, when the photos are far enough apart to tell. If every frame is a
|
||||
back, or the eyes cannot be told apart, the sharpest frame stays. A back is not dropped from the match when it
|
||||
is the only picture of that moment. In reportage a shut eye loses harder: sharpness does not rescue a blink
|
||||
when another frame of the same moment has the eyes open. One closed face in a group is enough.
|
||||
visible, and shut eyes lose to open ones. Open eyes always win when the burst has both — including a shot or a
|
||||
grimace: if another frame of the same moment has the eyes open, that one is kept. If every frame is a back, or
|
||||
the eyes cannot be told apart, the sharpest frame stays. A back is not dropped from the match when it is the
|
||||
only picture of that moment. One closed face in a group is enough to lose the frame in reportage.
|
||||
- **No usable face:** do not pick a frame whose subject has no clear face when the same burst has one that does.
|
||||
A photo that is not of a person (empty pitch, kit detail) is unchanged.
|
||||
- **Keep:** the best 1–2 frames per burst (configurable), flagged as picks. The rest stay unflagged (never
|
||||
rejected or deleted automatically).
|
||||
- **Reportage sequences:** when three or more frames of one moment are sharp, keep up to three (even if the
|
||||
@@ -103,16 +106,21 @@ A camera at 10–30 frames per second sends several photos of the same moment.
|
||||
|
||||
## 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:
|
||||
Per event (and an organisation default), off unless switched on. The same pipeline runs on the **desktop**
|
||||
(`apps/app/src/offline/autopilot.ts`) and on the **server** worker; the desktop must not wait for upload to
|
||||
cull or edit. 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,
|
||||
and the finishing look.
|
||||
The level reads the advertising boards, stands, posts and railings, never the pitch markings (lines on grass),
|
||||
which perspective tilts; when those lines disagree the photo is left as it is;
|
||||
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.
|
||||
1. analysed (people, ball, focus, eyes when faces are known) and scored — **not** developed yet;
|
||||
2. scored within its burst; when the burst ends, its best frames (clear face, open eyes preferred) are flagged
|
||||
as picks;
|
||||
3. **only the picks** are edited: white balance, tone, level (horizon or verticals, at most a few degrees), crop,
|
||||
and the finishing look. The rest of the sequence stays as shot (and need not be uploaded for that decision).
|
||||
The level reads the advertising boards, stands, posts and railings first, never the pitch markings (lines on
|
||||
grass), which perspective tilts; when those disagree it falls back to a general Level; when nothing agrees
|
||||
the photo is left as it is;
|
||||
4. optionally delivered (rendered with the edits, IPTC from the event) to the event's delivery target. When the
|
||||
desktop already edited a pick offline, those edits sync with the photo; the server does not overwrite them.
|
||||
|
||||
**Look** (per event, `apps/api/src/autopilot/look.ts`): fixed values on top of the measured tone, the same for
|
||||
every photo of a match. They never go over a measured control.
|
||||
@@ -151,8 +159,12 @@ The autopilot's panel in the app shows what it has learnt and has "Esquecer". Th
|
||||
## 5. Only the best
|
||||
|
||||
Some clients (ZeroZero) want a short gallery of the match, not every usable frame. With "Só as melhores do
|
||||
jogo" the autopilot still flags each burst's picks for the photographer, but delivers only a curated set of
|
||||
about the gallery size asked (`apps/api/src/autopilot/curate.ts`):
|
||||
jogo" / "Melhores…" the autopilot still flags each burst's picks for the photographer, but delivers a curated
|
||||
set. The number the photographer (or the event) asked for is a **hard target**: fill up to that count from the
|
||||
best remaining frames when the time windows alone fall short (`apps/api/src/autopilot/best.ts` `fillToCount`).
|
||||
Never stop around a hundred when they asked for two or three hundred and usable frames remain.
|
||||
|
||||
With autopilot "only the best", windows still shape the first pass (`apps/api/src/autopilot/curate.ts`):
|
||||
|
||||
- the match (from kick-off, its typical length by sport: football 115 min with the break, handball 80) is cut
|
||||
into 5-minute windows; each window may add its share of the gallery, and a share it did not use (the break,
|
||||
|
||||
@@ -246,12 +246,41 @@ export interface CreatedStamp {
|
||||
iso: string; // YYYY-MM-DDTHH:MM:SS+hh:mm (XMP)
|
||||
}
|
||||
|
||||
/** Library cull (⚑ / ✕ / stars) written into the delivered file so Lightroom and Photo Mechanic see it on import. */
|
||||
export interface LibraryMarks {
|
||||
flag?: "NONE" | "PICK" | "REJECT" | string | null;
|
||||
rating?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stars, pick and reject as XMP/EXIF/IPTC.
|
||||
*
|
||||
* Lightroom's **Flagged** filter is catalog-only — Adobe does not read a third-party pick flag from XMP. What does
|
||||
* import: star rating (`XMP-xmp:Rating`) and colour label (`XMP-xmp:Label`). A PhotoReport pick with no stars is
|
||||
* written as rating 1 + green label; a reject as rating −1. digiKam `PickLabel` and IPTC Urgency help Photo Mechanic.
|
||||
*/
|
||||
export function marksToExiftoolArgs(marks: LibraryMarks): string[] {
|
||||
const flag = marks.flag ?? "NONE";
|
||||
const rating = Math.max(0, Math.min(5, Math.round(Number(marks.rating) || 0)));
|
||||
if (flag !== "PICK" && flag !== "REJECT" && rating === 0) return [];
|
||||
if (flag === "REJECT") {
|
||||
return ["-XMP-xmp:Rating=-1", "-Rating=-1", "-XMP-xmp:Label=", "-XMP-digiKam:PickLabel=1", "-IPTC:Urgency=", "-XMP-photoshop:Urgency="];
|
||||
}
|
||||
const stars = rating > 0 ? rating : flag === "PICK" ? 1 : 0;
|
||||
const args: string[] = [];
|
||||
if (stars > 0) args.push(`-XMP-xmp:Rating=${stars}`, `-Rating=${stars}`);
|
||||
if (flag === "PICK") {
|
||||
args.push("-XMP-xmp:Label=Green", "-XMP-digiKam:PickLabel=3", "-IPTC:Urgency=1", "-XMP-photoshop:Urgency=1");
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExifTool arguments (`-TAG=value`) for the given values; list fields repeat the tag once per item.
|
||||
* IIM is written as UTF-8 and flagged as such (CodedCharacterSet), so accents survive in every reader; files
|
||||
* from Lightroom today carry no flag and show "Pavilh‹o" in some tools. `-m` keeps long values whole.
|
||||
*/
|
||||
export function toExiftoolArgs(values: IptcValues, created?: CreatedStamp): string[] {
|
||||
export function toExiftoolArgs(values: IptcValues, created?: CreatedStamp, marks?: LibraryMarks): string[] {
|
||||
const args = ["-m", "-charset", "iptc=UTF8", "-codedcharacterset=utf8"];
|
||||
if (created) {
|
||||
args.push(`-IPTC:DateCreated=${created.date}`, `-IPTC:TimeCreated=${created.time}`, `-XMP-photoshop:DateCreated=${created.iso}`);
|
||||
@@ -268,5 +297,6 @@ export function toExiftoolArgs(values: IptcValues, created?: CreatedStamp): stri
|
||||
}
|
||||
}
|
||||
}
|
||||
if (marks) args.push(...marksToExiftoolArgs(marks));
|
||||
return args;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
renderFileName,
|
||||
renderFolder,
|
||||
seasonOf,
|
||||
marksToExiftoolArgs,
|
||||
toExiftoolArgs,
|
||||
variablesIn,
|
||||
} from "./index.js";
|
||||
@@ -119,6 +120,28 @@ describe("IPTC template", () => {
|
||||
"-XMP-dc:Subject+=ABC",
|
||||
]);
|
||||
});
|
||||
|
||||
it("writes pick/reject/stars so Lightroom and Photo Mechanic see the cull on import", () => {
|
||||
expect(marksToExiftoolArgs({ flag: "NONE", rating: 0 })).toEqual([]);
|
||||
expect(marksToExiftoolArgs({ flag: "PICK", rating: 0 })).toEqual([
|
||||
"-XMP-xmp:Rating=1",
|
||||
"-Rating=1",
|
||||
"-XMP-xmp:Label=Green",
|
||||
"-XMP-digiKam:PickLabel=3",
|
||||
"-IPTC:Urgency=1",
|
||||
"-XMP-photoshop:Urgency=1",
|
||||
]);
|
||||
expect(marksToExiftoolArgs({ flag: "PICK", rating: 4 })).toContain("-XMP-xmp:Rating=4");
|
||||
expect(marksToExiftoolArgs({ flag: "REJECT", rating: 3 })).toEqual([
|
||||
"-XMP-xmp:Rating=-1",
|
||||
"-Rating=-1",
|
||||
"-XMP-xmp:Label=",
|
||||
"-XMP-digiKam:PickLabel=1",
|
||||
"-IPTC:Urgency=",
|
||||
"-XMP-photoshop:Urgency=",
|
||||
]);
|
||||
expect(toExiftoolArgs({ title: "A" }, undefined, { flag: "PICK", rating: 0 })).toContain("-XMP-xmp:Label=Green");
|
||||
});
|
||||
});
|
||||
|
||||
describe("vars", () => {
|
||||
|
||||
@@ -89,7 +89,10 @@ fn auto(job: &AutoJob) -> Result<(serde_json::Value, Option<f64>), String> {
|
||||
values.insert((*k).to_string(), serde_json::json!(v));
|
||||
}
|
||||
// Stadium photos: the pitch markings must not decide the level (see photoreport_engine::level).
|
||||
let angle = source.auto_level_scene();
|
||||
// When boards/stands/posts do not agree (tight indoor crops, empty seats), fall back to LightCraft's Level.
|
||||
let angle = source
|
||||
.auto_level_scene()
|
||||
.or_else(|| source.auto_level(&settings));
|
||||
Ok((serde_json::Value::Object(values), angle))
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user