The recorded cut is refused so the player stays whole, and the scale is what still narrows the frame. The gallery tests get a longer budget now that each frame is actually planned. Paperclip-Issue: BIT-33293
501 lines
30 KiB
TypeScript
501 lines
30 KiB
TypeScript
import { copyFile, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import sharp from "sharp";
|
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
|
import { AutopilotService } from "../src/autopilot/service.js";
|
|
import { bestOf, groupBursts, reportagePickCount } from "../src/autopilot/bursts.js";
|
|
import { type Candidate, actionScore, curate, galleryCeiling } from "../src/autopilot/curate.js";
|
|
import { correctionOf, fold, learntStyle, recordCorrection, styleOf } from "../src/autopilot/learning.js";
|
|
import type { Detections } from "../src/composition/compose.js";
|
|
import type { SubjectDetector } from "../src/composition/detect.js";
|
|
import type { RenderEngine, RenderJob, Settings } from "../src/develop/engine.js";
|
|
import { DevelopService } from "../src/develop/service.js";
|
|
import type { DeliveryService } from "../src/delivery/service.js";
|
|
import { IngestService } from "../src/ingest/service.js";
|
|
import { MemoryBroadcaster } from "../src/realtime.js";
|
|
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
|
|
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
|
|
|
const quiet = { info() {}, warn() {}, error() {} };
|
|
|
|
class FakeEngine implements RenderEngine {
|
|
async replay(base: Settings | null, commands: unknown[]) {
|
|
return { settings: { ...(base ?? {}), n: commands.length }, skipped: [], unedited: false };
|
|
}
|
|
async render(job: RenderJob) {
|
|
await copyFile(job.input, job.output);
|
|
return { width: 600, height: 400 };
|
|
}
|
|
async auto() {
|
|
return { values: { "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.4, "light.contrast": 20 }, angle: 1.5 };
|
|
}
|
|
async close() {}
|
|
}
|
|
|
|
/** A player in the middle; `focus` per photo (keyed by the sha in the preview's file name). */
|
|
class FakeDetector {
|
|
readonly focus = new Map<string, number>();
|
|
async detect(file: string): Promise<Detections> {
|
|
const sha = path.basename(file).split(".")[0]!;
|
|
const focus = this.focus.get(sha) ?? 100;
|
|
return { width: 600, height: 400, people: [{ x0: 0.42, y0: 0.2, x1: 0.58, y1: 0.85, score: 0.9, sharpness: 1, focus }], balls: [] };
|
|
}
|
|
}
|
|
|
|
describe("bursts", () => {
|
|
const f = (id: string, ms: number | null, camera = "R1", score: number | null = 1) => ({ id, capturedAt: ms === null ? null : new Date(1_800_000_000_000 + ms), camera, score });
|
|
it("groups frames of one camera closer than the gap, never across cameras", () => {
|
|
const bursts = groupBursts([f("a", 0), f("b", 200), f("c", 400), f("d", 5000), f("e", 300, "Z9"), f("x", null)], 1500);
|
|
expect(bursts.map((b) => b.map((x) => x.id))).toEqual([["x"], ["a", "b", "c"], ["e"], ["d"]]);
|
|
});
|
|
it("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 highest score, not the first frame when the scores are close", () => {
|
|
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(["c"]);
|
|
expect(bestOf(burst, 2).map((x) => x.id)).toEqual(["b", "c"]);
|
|
expect(bestOf(burst, 0)).toEqual([]);
|
|
// A few percent apart used to collapse to capture order (the first frames).
|
|
const close = [f("e", 0, "R1", 10), f("f", 100, "R1", 10.2), f("g", 200, "R1", 10.4)];
|
|
expect(bestOf(close, 1).map((x) => x.id)).toEqual(["g"]);
|
|
});
|
|
it("keeps up to three frames of a sharp reportage sequence, and the event's number otherwise", () => {
|
|
expect(reportagePickCount(4, 2)).toBe(3);
|
|
expect(reportagePickCount(3, 1)).toBe(3);
|
|
expect(reportagePickCount(2, 2)).toBe(2);
|
|
expect(reportagePickCount(6, 5)).toBe(3);
|
|
expect(reportagePickCount(8, 0)).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe("only the best", () => {
|
|
const start = 1_800_000_000_000;
|
|
const min = 60_000;
|
|
let k = 0;
|
|
const c = (at: number, score: number, extra: Partial<Candidate> = {}): Candidate => ({ id: `c${k++}`, at: start + at, burst: k, score, reason: "person", people: 1, subjectHeight: 0.5, rating: 0, rejected: false, ...extra });
|
|
|
|
it("prefers the ball, duels and big sharp subjects; never a rejected frame or an empty pitch", () => {
|
|
const base = c(0, 2);
|
|
expect(actionScore({ ...base, reason: "ball", people: 2 })).toBeGreaterThan(actionScore({ ...base, reason: "group", people: 2 }));
|
|
expect(actionScore({ ...base, reason: "group", people: 2 })).toBeGreaterThan(actionScore(base));
|
|
expect(actionScore({ ...base, subjectHeight: 0.1 })).toBeLessThan(actionScore(base));
|
|
expect(actionScore({ ...base, rating: 4 })).toBeGreaterThan(actionScore({ ...base, reason: "ball" }));
|
|
expect(actionScore({ ...base, rejected: true })).toBe(0);
|
|
expect(actionScore({ ...base, reason: null })).toBe(0);
|
|
});
|
|
|
|
it("spreads a gallery of the asked size over the match, carrying half-time forward, without twins", () => {
|
|
// 90 minutes of play with a 15 minute break; a frame every 30 s, better ones now and then.
|
|
const frames: Candidate[] = [];
|
|
for (let t = -20 * min; t < 105 * min; t += 30_000) {
|
|
if (t >= 45 * min && t < 60 * min) continue;
|
|
frames.push(c(t, 1 + ((t / 30_000) % 7) / 3, t % (4 * min) === 0 ? { reason: "ball", people: 2 } : {}));
|
|
}
|
|
// A twin of a great frame, two seconds later in another burst.
|
|
const great = c(20 * min, 9, { reason: "ball", people: 2 });
|
|
const twin = c(20 * min + 2_000, 8.9, { reason: "ball", people: 2 });
|
|
const rejected = c(30 * min, 20, { reason: "ball", rejected: true });
|
|
frames.push(great, twin, rejected);
|
|
const opts = { count: 30, start, durationMs: 105 * min, now: start + 200 * min };
|
|
const all = curate(frames, [], opts).flatMap((d) => d.chosen);
|
|
expect(all.length).toBeGreaterThanOrEqual(28);
|
|
expect(all.length).toBeLessThanOrEqual(galleryCeiling(30));
|
|
expect(galleryCeiling(30)).toBe(35);
|
|
expect(galleryCeiling(100)).toBe(115);
|
|
expect(galleryCeiling(300)).toBe(325);
|
|
expect(all).toContain(great.id);
|
|
expect(all).not.toContain(twin.id);
|
|
expect(all).not.toContain(rejected.id);
|
|
const at = new Map(frames.map((f) => [f.id, f.at - start]));
|
|
// Nothing from the warm-up; both halves well represented.
|
|
expect(all.every((id) => at.get(id)! >= -5 * min)).toBe(true);
|
|
expect(all.filter((id) => at.get(id)! < 45 * min).length).toBeGreaterThanOrEqual(11);
|
|
expect(all.filter((id) => at.get(id)! >= 60 * min).length).toBeGreaterThanOrEqual(11);
|
|
|
|
// Live, window by window, it comes to the same gallery size.
|
|
const decided: { id: string; chosen: boolean }[] = [];
|
|
for (let now = start - 20 * min; now <= start + 200 * min; now += min) {
|
|
const seen = frames.filter((f) => f.at <= now);
|
|
for (const d of curate(seen, decided, { ...opts, now })) for (const id of d.ids) decided.push({ id, chosen: d.chosen.includes(id) });
|
|
}
|
|
const live = decided.filter((d) => d.chosen).length;
|
|
expect(Math.abs(live - all.length)).toBeLessThanOrEqual(2);
|
|
});
|
|
|
|
it("still fills an earlier window when a later frame was already sent", () => {
|
|
const early = [0, 1, 2, 3].map((i) => c(i * 30_000, 5));
|
|
const late = c(10 * min, 5);
|
|
const opts = { count: 30, start, durationMs: 105 * min, now: start + 20 * min };
|
|
const opened = curate([...early, late], [{ id: late.id, chosen: true, at: late.at }], opts);
|
|
expect(opened.find((d) => d.window === 0)?.chosen.length).toBeGreaterThan(0);
|
|
});
|
|
|
|
it("keeps two frames of a slow sequence, not every shot a second apart", () => {
|
|
const seq = Array.from({ length: 10 }, (_, i) => c(i * 2_000, 8 - i * 0.1, { reason: "person" }));
|
|
const opts = { count: 150, start, durationMs: 115 * min, now: start + 10 * min };
|
|
const chosen = curate(seq, [], opts).flatMap((d) => d.chosen);
|
|
expect(chosen.length).toBe(2);
|
|
expect(chosen).toContain(seq[0]!.id);
|
|
});
|
|
|
|
it("sends up to four when the same sequence changes picture, not one of every frame", () => {
|
|
const standing = { x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.95 };
|
|
const tight = { x0: 0.35, y0: 0.05, x1: 0.7, y1: 0.45 };
|
|
const group = { x0: 0.05, y0: 0.3, x1: 0.95, y1: 0.85 };
|
|
const boxes = [standing, tight, group, standing, tight, group, standing, tight];
|
|
const seq = boxes.map((subject, i) =>
|
|
c(i * 6_000, 8 - i * 0.05, {
|
|
reason: subject === group ? "group" : "person",
|
|
people: subject === group ? 3 : 1,
|
|
subject,
|
|
}),
|
|
);
|
|
const opts = { count: 150, start, durationMs: 115 * min, now: start + 10 * min, sequenceCap: 2 };
|
|
const chosen = curate(seq, [], opts).flatMap((d) => d.chosen);
|
|
expect(chosen.length).toBe(4);
|
|
});
|
|
});
|
|
|
|
describe("learning from corrections", () => {
|
|
const set = (values: Record<string, number>) => ({ command: "develop.set" as const, params: { values } });
|
|
const crop = (x0: number, x1: number) => ({ command: "crop.set" as const, params: { rect: { x0, y0: 0, x1, y1: 1 }, angle: 0, aspect: null } });
|
|
|
|
it("folds edits and measures what the person changed", () => {
|
|
const auto = fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), crop(0.1, 0.9)]);
|
|
const final = fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), crop(0.1, 0.9), set({ "light.exposure": 0.55, "wb.temp": 5500, "light.shadows": 12 }), crop(0.2, 0.8)]);
|
|
const c = correctionOf(auto, final);
|
|
expect(c?.deltas["light.exposure"]).toBe(0.35);
|
|
expect(c?.deltas["light.shadows"]).toBe(12);
|
|
expect(c?.deltas["wb.temp"]).toBe(300);
|
|
// Scale is linear (cropBias.ts): the crop only narrows in x here, so it is the geometric mean of the two axes.
|
|
expect(c?.cropScale).toBeCloseTo(0.866, 2);
|
|
expect(c?.cropBias?.scale).toBeCloseTo(0.866, 2);
|
|
// A reset is "less of everything the autopilot did" for tone; white balance says nothing then.
|
|
expect(correctionOf(auto, fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), { command: "develop.reset" }]))).toEqual({
|
|
deltas: { "light.exposure": -0.2 },
|
|
cropScale: null,
|
|
cropBias: null,
|
|
});
|
|
// Creative extremes are not corrections.
|
|
expect(correctionOf(fold([set({ "light.contrast": 10 })]), fold([set({ "light.contrast": 90 })]))).toBeNull();
|
|
});
|
|
|
|
it("keeps only what most corrections agree on, including a looser crop", () => {
|
|
const rows = [0.3, 0.25, 0.35, 0.3, -0.1].map((e, i) => ({ deltas: { "light.exposure": e, "light.contrast": i % 2 ? 8 : -8 }, cropScale: 0.7 }));
|
|
const style = styleOf(rows, null);
|
|
expect(style.offsets).toEqual({ "light.exposure": 0.3 });
|
|
// 0.7 is below the 0.75 floor (never suggest tighter than that), so it saturates there.
|
|
expect(style.cropFactor).toBeCloseTo(0.75, 2);
|
|
expect(styleOf(rows.slice(0, 4), null).offsets).toEqual({});
|
|
const open = [1.1, 1.12, 1.08, 1.15, 1.09].map((s) => ({
|
|
deltas: { "__crop.scale": s, "__crop.dx": 0.02, "__crop.dy": -0.03, "__crop.dAngle": 0 },
|
|
cropScale: s,
|
|
}));
|
|
const openStyle = styleOf(open, null);
|
|
expect(openStyle.cropFactor).toBeGreaterThan(1);
|
|
expect(openStyle.cropBias?.dx).toBeCloseTo(0.02, 2);
|
|
});
|
|
|
|
it("learns where the crop cuts the person, not only the ratio", () => {
|
|
const subject = { x0: 0.3, y0: 0.15, x1: 0.7, y1: 0.95 };
|
|
const auto = fold([crop(0.1, 0.9)]);
|
|
// Bottom at the waist: (0.55 - 0.15) / 0.8 = 0.5. Sides eat into the body.
|
|
const final = fold([{ command: "crop.set", params: { rect: { x0: 0.38, y0: 0.12, x1: 0.62, y1: 0.55 }, angle: 0, aspect: null } }]);
|
|
const c = correctionOf(auto, final, "person", subject);
|
|
expect(c?.cropBias?.cut).toBeCloseTo(0.5, 2);
|
|
expect(c?.cropBias?.sides).toBeGreaterThan(0.08);
|
|
const rows = [0.5, 0.52, 0.48, 0.51, 0.49].map((cut) => ({
|
|
deltas: { "__crop.scale": 0.8, "__crop.dx": 0, "__crop.dy": 0, "__crop.dAngle": 0, "__crop.cut": cut, "__crop.head": 0.04, "__crop.sides": 0.12 },
|
|
cropScale: 0.8,
|
|
}));
|
|
const style = styleOf(rows, null);
|
|
expect(style.cropBias?.cut).toBeCloseTo(0.5, 2);
|
|
expect(style.cropBias?.sides).toBeCloseTo(0.12, 2);
|
|
});
|
|
});
|
|
|
|
/** The JPEG stays 600 px so the suite does not time out. The planner reads this size, which clears the 2400 px floor. */
|
|
const PHOTO_W = 6000;
|
|
const PHOTO_H = 4000;
|
|
|
|
describe("autopilot", () => {
|
|
let ctx: TestContext;
|
|
let dir: string;
|
|
let ingest: IngestService;
|
|
let develop: DevelopService;
|
|
let autopilot: AutopilotService;
|
|
let detector: FakeDetector;
|
|
const broadcaster = new MemoryBroadcaster();
|
|
|
|
beforeAll(async () => {
|
|
dir = await mkdtemp(path.join(tmpdir(), "pr-autopilot-"));
|
|
const ingestRoot = path.join(dir, "ingest");
|
|
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }, broadcaster);
|
|
const storage = new LocalStorage(ctx.config.STORAGE_ROOT);
|
|
const signer = new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC);
|
|
const engine = new FakeEngine();
|
|
detector = new FakeDetector();
|
|
ingest = new IngestService({ db: ctx.db, storage, signer, broadcaster, ingestRoot, log: quiet });
|
|
develop = new DevelopService({ db: ctx.db, storage, signer, broadcaster, log: quiet, engine });
|
|
autopilot = new AutopilotService({ db: ctx.db, storage, broadcaster, log: quiet, develop, engine, detector: () => Promise.resolve(detector as unknown as SubjectDetector) });
|
|
});
|
|
afterAll(async () => {
|
|
await ctx.app.close();
|
|
await ctx.db.$disconnect();
|
|
await rm(dir, { recursive: true, force: true });
|
|
});
|
|
beforeEach(async () => {
|
|
await resetDb(ctx.db);
|
|
broadcaster.sent.length = 0;
|
|
});
|
|
|
|
let n = 0;
|
|
async function shot(orgId: string, userId: string, eventId: string, at: number, focus: number, source: "FTP" | "UPLOAD" | "CLOUD" = "FTP") {
|
|
n++;
|
|
const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: (n * 31) % 256, g: 90, b: 120 } } }).jpeg().toBuffer();
|
|
const { createHash } = await import("node:crypto");
|
|
detector.focus.set(createHash("sha256").update(data).digest("hex"), focus);
|
|
const file = path.join(dir, `IMG_${n}.JPG`);
|
|
await writeFile(file, data);
|
|
const out = await ingest.ingest(file, { organizationId: orgId, userId, source, originalName: `IMG_${n}.JPG`, eventId });
|
|
await ctx.db.photo.update({ where: { id: out.photoId }, data: { capturedAt: new Date(1_800_000_000_000 + at), cameraSerial: "R1-001", width: PHOTO_W, height: PHOTO_H } });
|
|
return out.photoId;
|
|
}
|
|
|
|
async function setup(autopilotOn = true) {
|
|
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "EDITOR" });
|
|
const event = await ctx.db.event.create({
|
|
data: {
|
|
organizationId: org!.id,
|
|
home: "ABC",
|
|
away: "CDE",
|
|
startsAt: new Date("2026-10-11T14:00:00Z"),
|
|
ingestFrom: new Date("2026-10-11T12:00:00Z"),
|
|
ingestUntil: new Date("2026-10-11T18:00:00Z"),
|
|
iptcTemplate: {},
|
|
// The original settings (half tone, white balance as shot, no look, whole bodies); the agency defaults have a test of their own.
|
|
...(autopilotOn && { autopilot: { enabled: true, picksPerBurst: 2, toneStrength: 0.5, whiteBalance: false, look: "none", framing: "full" } }),
|
|
},
|
|
});
|
|
return { orgId: org!.id, userId: user.id, eventId: event.id };
|
|
}
|
|
|
|
async function runQueue() {
|
|
for (let ids = await autopilot.claim(10); ids.length; ids = await autopilot.claim(10)) for (const id of ids) await autopilot.process(id);
|
|
}
|
|
|
|
it("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);
|
|
// White balance stays as shot (off by default); tone at half strength.
|
|
expect((edits[0]!.command as { params: { values: Record<string, number> } }).params.values).toEqual({ "light.exposure": 0.2, "light.contrast": 10 });
|
|
const crop = (edits[1]!.command as { params: { rect: { x0: number; x1: number }; angle: number } }).params;
|
|
expect(crop.angle).toBe(1.5);
|
|
expect(crop.rect.x0).toBeLessThan(0.42);
|
|
expect(crop.rect.x1).toBeGreaterThan(0.58);
|
|
expect(await ctx.db.photoEdit.count({ where: { photoId: hand } })).toBe(0);
|
|
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: hand } })).autopilotStatus).toBe("NONE");
|
|
});
|
|
|
|
it("picks the sharpest frames of each burst once it has settled, 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);
|
|
const c = await shot(orgId, userId, eventId, 200, 500);
|
|
const d = await shot(orgId, userId, eventId, 300, 50);
|
|
const lone = await shot(orgId, userId, eventId, 10_000, 200);
|
|
await ctx.db.photo.update({ where: { id: lone }, data: { flag: "REJECT" } });
|
|
await runQueue();
|
|
// Too soon: the burst may still be arriving.
|
|
expect(await autopilot.decideBursts(new Date())).toBe(0);
|
|
expect(await 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.
|
|
expect(await autopilot.decideBursts(new Date(Date.now() + 40_000))).toBe(0);
|
|
});
|
|
|
|
it("only the best: chooses each window's game moments once the window has closed", async () => {
|
|
const { eventId, orgId, userId } = await setup();
|
|
const start = new Date(1_800_000_000_000);
|
|
// A gallery of 23 over 115 minutes: one photo per 5-minute window, unused ones carried forward.
|
|
await ctx.db.event.update({ where: { id: eventId }, data: { startsAt: start, sport: "futebol", autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 23 } } });
|
|
const w0a = await shot(orgId, userId, eventId, 60_000, 900);
|
|
const w0b = await shot(orgId, userId, eventId, 120_000, 300);
|
|
const w2a = await shot(orgId, userId, eventId, 11 * 60_000, 800);
|
|
const w2b = await shot(orgId, userId, eventId, 12 * 60_000, 700);
|
|
const w2c = await shot(orgId, userId, eventId, 13 * 60_000, 100);
|
|
await runQueue();
|
|
// Window 0 has closed (and settled), window 2 not yet.
|
|
await autopilot.decideBursts(new Date(start.getTime() + 7 * 60_000));
|
|
const chosen = async () => Object.fromEntries((await ctx.db.photo.findMany({ where: { eventId } })).map((p) => [p.id, (p.autopilot as { curated?: boolean; chosen?: boolean }).curated ? !!(p.autopilot as { chosen?: boolean }).chosen : null]));
|
|
expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: null, [w2b]: null, [w2c]: null });
|
|
// Window 2 also takes the share window 1 (no photos) did not use.
|
|
await autopilot.decideBursts(new Date(start.getTime() + 17 * 60_000));
|
|
expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: true, [w2b]: true, [w2c]: false });
|
|
// The burst picks are still flagged for the photographer.
|
|
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: w2c } })).flag).toBe("PICK");
|
|
}, 60_000);
|
|
|
|
it("two clients: gallery gets the best moments; rest gets seconds and every other pick (warm-up included)", async () => {
|
|
const { eventId, orgId, userId } = await setup();
|
|
const start = new Date(1_800_000_000_000);
|
|
const record = "11111111-1111-4111-8111-111111111111";
|
|
const fap = "22222222-2222-4222-8222-222222222222";
|
|
await ctx.db.event.update({
|
|
where: { id: eventId },
|
|
data: {
|
|
startsAt: start,
|
|
ingestFrom: new Date(start.getTime() - 2 * 60 * 60 * 1000),
|
|
ingestUntil: new Date(start.getTime() + 4 * 60 * 60 * 1000),
|
|
sport: "andebol",
|
|
createdById: userId,
|
|
autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 16, deliverTargetId: record, restTargetId: fap },
|
|
},
|
|
});
|
|
const sent: { targetId: string; photoIds: string[] }[] = [];
|
|
const deliveries = { enqueue: async (r: { targetId: string; photoIds: string[] }) => void sent.push({ targetId: r.targetId, photoIds: [...r.photoIds] }) };
|
|
const service = new AutopilotService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), broadcaster, log: quiet, develop, engine: new FakeEngine(), detector: () => Promise.resolve(detector as unknown as SubjectDetector), deliveries: deliveries as unknown as DeliveryService });
|
|
// Warm-up (ads / line-up): never a gallery moment, but still a pick for the rest client.
|
|
const warm = await shot(orgId, userId, eventId, -20 * 60_000, 400);
|
|
// Window 0: a strong burst and a weaker one.
|
|
const a1 = await shot(orgId, userId, eventId, 60_000, 900);
|
|
const a2 = await shot(orgId, userId, eventId, 60_100, 600);
|
|
const b1 = await shot(orgId, userId, eventId, 120_000, 300);
|
|
const b2 = await shot(orgId, userId, eventId, 120_100, 200);
|
|
// Taken before this event's ingest window, still filed here: not this client's folder.
|
|
const later = await shot(orgId, userId, eventId, -3 * 60 * 60 * 1000, 950);
|
|
for (let ids = await service.claim(10); ids.length; ids = await service.claim(10)) for (const id of ids) await service.process(id);
|
|
await service.decideBursts(new Date(start.getTime() + 7 * 60_000));
|
|
const to = (target: string) => sent.filter((x) => x.targetId === target).flatMap((x) => x.photoIds);
|
|
// Gallery: best of the chosen moment only. Rest: second of that sequence, the other picks, and warm-up.
|
|
expect(to(record)).toEqual([a1]);
|
|
expect(to(fap).sort()).toEqual([warm, a2, b1, b2].sort());
|
|
expect(to(record).filter((id) => to(fap).includes(id))).toEqual([]);
|
|
expect([...to(record), ...to(fap)]).not.toContain(later);
|
|
// Decided once: nothing is sent again.
|
|
await service.decideBursts(new Date(start.getTime() + 8 * 60_000));
|
|
expect(to(record)).toEqual([a1]);
|
|
expect(to(fap).sort()).toEqual([warm, a2, b1, b2].sort());
|
|
}, 60_000);
|
|
|
|
it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => {
|
|
const { orgId, userId, eventId } = await setup();
|
|
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");
|
|
});
|
|
|
|
it("defaults to look none: white balance and tone only, no finishing look", async () => {
|
|
const { orgId, userId, eventId } = await setup();
|
|
await ctx.db.event.update({ where: { id: eventId }, data: { autopilot: { enabled: true } } });
|
|
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;
|
|
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15 });
|
|
expect(values["color.vibrance"]).toBeUndefined();
|
|
expect(values["detail.sharpenAmount"]).toBeUndefined();
|
|
expect(Object.keys(values).some((k) => k.startsWith("vignette."))).toBe(false);
|
|
});
|
|
|
|
it("applies the agency finishing look when asked", async () => {
|
|
const { orgId, userId, eventId } = await setup();
|
|
await ctx.db.event.update({ where: { id: eventId }, data: { autopilot: { enabled: true, look: "agency" } } });
|
|
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;
|
|
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 31, "detail.nrLuminance": 22 });
|
|
});
|
|
|
|
it("leaves events without autopilot alone", async () => {
|
|
const { orgId, userId, eventId } = await setup(false);
|
|
await shot(orgId, userId, eventId, 0, 100);
|
|
expect(await autopilot.claim(10)).toEqual([]);
|
|
});
|
|
|
|
it("learns from a photographer's corrections and edits the next photos that way", async () => {
|
|
const { orgId, userId, eventId } = await setup();
|
|
await ctx.db.event.update({ where: { id: eventId }, data: { venue: "Pavilhão Flávio Sá Leite" } });
|
|
const photos: string[] = [];
|
|
// Farther apart than one sequence, so each frame is edited. A sequence only crops its picks.
|
|
for (let i = 0; i < 6; i++) photos.push(await shot(orgId, userId, eventId, i * 20_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));
|
|
const r = auto.crop!.rect;
|
|
const shrink = (a: number, b: number) => [a + (b - a) * 0.08, b - (b - a) * 0.08] as const;
|
|
const [x0, x1] = shrink(r.x0, r.x1);
|
|
const [y0, y1] = shrink(r.y0, r.y1);
|
|
await develop.append(id, userId, { clientId: "web-1", ops: [{ opId: `h-${id}-1`, command: { command: "develop.set", params: { values: { "light.exposure": 0.5 } } } }, { opId: `h-${id}-2`, command: { command: "crop.set", params: { rect: { x0, y0, x1, y1 }, angle: 1.5, aspect: [PHOTO_W, PHOTO_H] } } }] });
|
|
expect(await recordCorrection(ctx.db, id)).toBe(true);
|
|
}
|
|
// Untouched photos and the autopilot's own edits teach nothing.
|
|
expect(await recordCorrection(ctx.db, photos[5]!)).toBe(false);
|
|
const style = await learntStyle(ctx.db, orgId, userId, "pavilhão flávio sá leite ");
|
|
expect(style).toMatchObject({ samples: 5, venue: "pavilhão flávio sá leite", offsets: { "light.exposure": 0.3 } });
|
|
expect(style!.cropFactor).toBeCloseTo(0.84, 1);
|
|
|
|
const next = await shot(orgId, userId, eventId, 200_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!.rect;
|
|
const after = fold(edits.map((e) => e.command as never)).crop!.rect;
|
|
expect(after.x1 - after.x0).toBeLessThan(before.x1 - before.x0);
|
|
expect(((await ctx.db.photo.findUniqueOrThrow({ where: { id: next } })).autopilot as { style: { samples: number } }).style.samples).toBe(5);
|
|
|
|
// The photographer sees it in the app, and can make it forget.
|
|
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
|
const seen = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/autopilot/style?venue=${encodeURIComponent("Pavilhão Flávio Sá Leite")}`, headers: bearer(token) });
|
|
expect(seen.json()).toMatchObject({ photographerId: userId, style: { samples: 5, offsets: { "light.exposure": 0.3 } } });
|
|
const gone = await ctx.app.inject({ method: "DELETE", url: `/v1/orgs/${orgId}/autopilot/style`, headers: bearer(token) });
|
|
expect(gone.json()).toEqual({ forgotten: 5 });
|
|
expect(await learntStyle(ctx.db, orgId, userId)).toBeNull();
|
|
}, 60_000);
|
|
|
|
it("tells the learner when a person (not the autopilot) edits", async () => {
|
|
const { orgId, userId, eventId } = await setup();
|
|
const id = await shot(orgId, userId, eventId, 0, 300);
|
|
const seen: string[] = [];
|
|
const storage = new LocalStorage(ctx.config.STORAGE_ROOT);
|
|
const d = new DevelopService({ db: ctx.db, storage, signer: new UrlSigner(ctx.config.JWT_SECRET, 60), broadcaster, log: quiet, onHumanEdit: (p) => seen.push(p) });
|
|
await d.append(id, userId, { clientId: "autopilot", ops: [{ opId: "a1", command: { command: "develop.set", params: { values: { "light.exposure": 0.1 } } } }] });
|
|
await d.append(id, userId, { clientId: "web-1", ops: [{ opId: "h1", command: { command: "develop.set", params: { values: { "light.exposure": 0.3 } } } }] });
|
|
await d.append(id, userId, { clientId: "web-1", ops: [{ opId: "h1", command: { command: "develop.set", params: { values: { "light.exposure": 0.3 } } } }] }); // retry: nothing new
|
|
expect(seen).toEqual([id]);
|
|
});
|
|
});
|