fix(desktop): local burst autopilot culls and edits only picks (BIT-171) #171
No files matched your search
@@ -22,6 +22,12 @@ 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.** Everything a photographer does in the field must work on the desktop
|
||||
without the network (cull, edit, autopilot picks, export of what is already on disk), except genuinely
|
||||
heavy shared jobs (e.g. org-wide face clustering). 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.
|
||||
|
||||
## Porting from the old projects
|
||||
|
||||
|
||||
@@ -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,17 +1,192 @@
|
||||
import { AutopilotSettings, type EditCommand } from "@photoreport/contracts";
|
||||
import type { ApiClient, AutopilotStyle, EventSummary } from "@photoreport/sdk";
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Local analysis only. The server picks the best frames of each burst and applies the develop/crop edits there
|
||||
* (docs/photo-editing-rules.md §4): editing every frame of a sequence on the desktop flooded the library with
|
||||
* near-duplicates. Kept as a no-op so callers and the old import path stay wired; the server owns the edit.
|
||||
* 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: {
|
||||
export async function planLocalAutopilot(args: {
|
||||
api: ApiClient;
|
||||
orgId: string;
|
||||
event: EventSummary | undefined;
|
||||
sha256: string;
|
||||
preview: ArrayBuffer;
|
||||
width: number;
|
||||
height: number;
|
||||
iso?: number | null;
|
||||
// Call sites still pass api/event; ignored until a local burst picker exists.
|
||||
[key: string]: unknown;
|
||||
capturedAt?: string | null;
|
||||
camera?: string | null;
|
||||
}): Promise<void> {
|
||||
// Edits are deferred until the burst is decided on the server.
|
||||
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);
|
||||
const [measured, detections, style] = await Promise.all([
|
||||
measure(args.preview),
|
||||
detectPreview(args.api, args.orgId, args.preview),
|
||||
styleFor(args.api, args.orgId, args.event.venue),
|
||||
]);
|
||||
// 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 ?? {});
|
||||
const planned = planFrame({
|
||||
detections,
|
||||
width: args.width,
|
||||
height: args.height,
|
||||
reportage,
|
||||
values,
|
||||
angle,
|
||||
cropFactor: style?.cropFactor ?? null,
|
||||
sport: args.event.sport,
|
||||
settings,
|
||||
});
|
||||
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> {
|
||||
try {
|
||||
const engine = await loadEngine();
|
||||
const photo = new engine.Photo(new Uint8Array(bytes), 1024);
|
||||
try {
|
||||
const wb = JSON.parse(photo.autoWb()) as Record<string, number>;
|
||||
const settings = engine.apply(engine.defaultSettings(), JSON.stringify({ command: "develop.set", params: { values: wb } }));
|
||||
const tone = JSON.parse(photo.autoTone(settings)) as Record<string, number>;
|
||||
let angle: number | null = null;
|
||||
if (photo.autoLevelScene) {
|
||||
const scene = JSON.parse(photo.autoLevelScene()) as Record<string, number>;
|
||||
if (typeof scene["crop.angle"] === "number") angle = scene["crop.angle"];
|
||||
}
|
||||
if (angle === null) {
|
||||
const level = JSON.parse(photo.autoLevel(settings)) as Record<string, number>;
|
||||
if (typeof level["crop.angle"] === "number") angle = level["crop.angle"];
|
||||
}
|
||||
return { values: { ...wb, ...tone }, angle };
|
||||
} finally {
|
||||
photo.free();
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function styleFor(api: ApiClient, orgId: string, venue: string | null): Promise<AutopilotStyle | null> {
|
||||
const key = `style:${orgId}:${venue ?? ""}`;
|
||||
try {
|
||||
const res = await api.autopilotStyle(orgId, venue);
|
||||
await kv.set(key, res.style);
|
||||
return res.style;
|
||||
} catch {
|
||||
return (await kv.get<AutopilotStyle | null>(key)) ?? null;
|
||||
}
|
||||
}
|
||||
@@ -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:** the desktop must cull, edit and run autopilot 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 (see AGENTS.md §12).
|
||||
- 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).
|
||||
|
||||
@@ -106,18 +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, eyes) and scored — **not** developed yet;
|
||||
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 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.
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user