Compare commits

..
Author SHA1 Message Date
spark a41d30881a feat(autopilot): give each destination its own gallery size
ci / rust (pull_request) Successful in 8m19s
ci / typescript (pull_request) Successful in 13m27s
A short gallery and a larger one can leave the same match. Frames in the short gallery also go to the larger one.
2026-11-07 14:56:33 +00:00
spark e4a61d3127 fix(delivery): send ZeroZero the full author line (#242)
ci / rust (push) Successful in 7m1s
ci / typescript (push) Successful in 10m19s
fix(delivery): send ZeroZero the full author line
2026-11-07 14:46:31 +00:00
5 changed files with 152 additions and 7 deletions

No files matched your search

+80 -5
View File
@@ -20,7 +20,7 @@ import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.j
import { curate, matchMinutes } from "./curate.js";
import { type LearntStyle, learntStyle } from "./learning.js";
import { detailForCrop, lookValues } from "./look.js";
import { exportTargets, MELHORES_GAP_MS, picksNeeded } from "./targets.js";
import { exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type GalleryExport } from "./targets.js";
const STALE_RUNNING_MS = 10 * 60_000;
/** A burst is decided once no new frame of it has arrived for this long. */
@@ -63,6 +63,8 @@ export interface AutopilotRecord {
chosen?: boolean;
/** "ball": the picture cuts the ball, so it is not delivered. */
hold?: "ball";
/** Per destination gallery: true when this frame was picked for it, false when its window decided against it. */
gallery?: Record<string, boolean>;
/**
* Planned develop/crop ops from analysis. Applied only when this frame is picked for the burst — never on the
* near-duplicates left unflagged.
@@ -374,15 +376,42 @@ export class AutopilotService {
.filter((p) => (p.autopilot as unknown as AutopilotRecord | null)?.curated)
.map((p) => ({ id: p.id, chosen: !!(p.autopilot as unknown as AutopilotRecord).chosen }));
const targets = exportTargets(settings);
const galleries = settings.galleries ?? [];
// With 2+ exports, curate on the best frame; delivery below assigns best/2nd/… to each target.
// Separate gallery sizes curate to the largest, and each smaller one keeps its own spread.
const candidates = candidatesOf(ranked, settings.burstGapSec * 1000, true, "best");
const decisions = curate(candidates, decided, {
count: settings.bestCount,
const curateOpts = {
start: event.startsAt.getTime(),
durationMs: matchMinutes(event.sport) * 60_000,
now: now.getTime(),
minGapMs: MELHORES_GAP_MS,
};
const decisions = curate(candidates, decided, {
count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount,
...curateOpts,
});
const chosenBy = new Map<string, Set<string>>();
const seenBy = new Map<string, Set<string>>();
if (galleries.length) {
const max = Math.max(...galleries.map((g) => g.count));
const bigChosen = new Set(decisions.flatMap((d) => d.chosen));
const bigSeen = new Set(decisions.flatMap((d) => d.ids));
for (const g of galleries) {
if (g.count !== max) continue;
chosenBy.set(g.targetId, bigChosen);
seenBy.set(g.targetId, bigSeen);
}
for (const g of galleries) {
if (g.count === max) continue;
const earlier = photos.flatMap((p) => {
const flag = (p.autopilot as unknown as AutopilotRecord | null)?.gallery?.[g.targetId];
return flag === undefined ? [] : [{ id: p.id, chosen: flag }];
});
const parts = curate(candidates, earlier, { count: g.count, ...curateOpts });
chosenBy.set(g.targetId, new Set(parts.flatMap((d) => d.chosen)));
seenBy.set(g.targetId, new Set(parts.flatMap((d) => d.ids)));
}
}
const records = new Map(photos.map((p) => [p.id, p.autopilot as unknown as AutopilotRecord | null]));
// Frames that were not their burst's candidate are decided with it.
const burstOf = new Map<string, string[]>();
@@ -400,12 +429,13 @@ export class AutopilotService {
for (const id of ids) {
const rec = records.get(id);
if (!rec || rec.curated) continue;
await db.photo.update({ where: { id }, data: { autopilot: { ...rec, curated: true, chosen: chosen.has(id) } as object } });
const gallery = galleryMarks(id, galleries, chosenBy, seenBy, rec.gallery);
await db.photo.update({ where: { id }, data: { autopilot: { ...rec, curated: true, chosen: chosen.has(id), ...(gallery ? { gallery } : {}) } as object } });
nowCurated.push(id);
}
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
chosenCount += chosen.size;
if (targets.length && this.deps.deliveries && event.createdById) {
if (!galleries.length && targets.length && this.deps.deliveries && event.createdById) {
// Per chosen moment (burst): rank i → export i. Same photo never to two destinations.
for (const momentId of chosen) {
const burstIds = burstOf.get(momentId) ?? [momentId];
@@ -427,6 +457,33 @@ export class AutopilotService {
}
if (d.window >= 0) log.info({ eventId, window: d.window, candidates: d.ids.length, chosen: chosen.size }, "autopilot: best of the window");
}
if (galleries.length && this.deps.deliveries && event.createdById) {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
const moments = new Set<string>();
for (const [targetId, picked] of chosenBy) {
const seen = seenBy.get(targetId);
for (const id of picked) if (seen?.has(id)) moments.add(id);
}
for (const momentId of moments) {
if (!takenHere([momentId], when, event).length) continue;
for (const targetId of galleryReceivers(momentId, galleries, chosenBy)) {
await this.deps.deliveries
.enqueue({ organizationId: event.organizationId, targetId, photoIds: [momentId], again: false, requestedById: event.createdById })
.catch((err: unknown) => log.warn({ err, targetId }, "autopilot: delivery not queued"));
}
}
// Windows already closed before these galleries existed still need their decision recorded.
for (const [targetId, seen] of seenBy) {
for (const id of seen) {
const rec = records.get(id);
if (!rec?.curated || rec.gallery?.[targetId] !== undefined) continue;
const gallery = galleryMarks(id, galleries, chosenBy, seenBy, rec.gallery);
if (!gallery) continue;
rec.gallery = gallery;
await db.photo.update({ where: { id }, data: { autopilot: { ...rec, gallery } as object } });
}
}
}
return chosenCount;
}
}
@@ -435,6 +492,24 @@ export class AutopilotService {
* The photos of a decided window that go to the second client: the picked ones (by the autopilot or a person) the
* gallery did not take. Never a chosen one, so no photo reaches both clients.
*/
/** Gallery flags for a frame whose window was decided this pass. Unmentioned destinations stay as they were. */
function galleryMarks(
id: string,
galleries: readonly GalleryExport[],
chosenBy: ReadonlyMap<string, ReadonlySet<string>>,
seenBy: ReadonlyMap<string, ReadonlySet<string>>,
previous: Record<string, boolean> | undefined,
): Record<string, boolean> | undefined {
const flags: Record<string, boolean> = { ...previous };
let touched = false;
for (const g of galleries) {
if (!seenBy.get(g.targetId)?.has(id)) continue;
flags[g.targetId] = chosenBy.get(g.targetId)?.has(id) ?? false;
touched = true;
}
return touched ? flags : undefined;
}
export function restOf(ids: readonly string[], chosen: ReadonlySet<string>, flags: ReadonlyMap<string, string>): string[] {
return ids.filter((id) => !chosen.has(id) && flags.get(id) === "PICK");
}
+20
View File
@@ -31,3 +31,23 @@ export function picksNeeded(settings: AutopilotSettings): number {
/** Melhores spacing between two sends to the same destination (ms). */
export const MELHORES_GAP_MS = 5_000;
export interface GalleryExport {
targetId: string;
count: number;
}
/**
* Destinations that receive this frame. A frame picked for a smaller gallery also goes to every larger one,
* so the short gallery is part of the long one. A frame only the long gallery picked stays out of the short one.
*/
export function galleryReceivers(momentId: string, galleries: readonly GalleryExport[], chosen: ReadonlyMap<string, ReadonlySet<string>>): string[] {
if (!galleries.length) return [];
const max = Math.max(...galleries.map((g) => g.count));
const hit = galleries.filter((g) => chosen.get(g.targetId)?.has(momentId));
const ids = new Set(hit.map((g) => g.targetId));
if (hit.some((g) => g.count < max)) {
for (const g of galleries) if (g.count === max) ids.add(g.targetId);
}
return [...ids];
}
+11 -1
View File
@@ -15,6 +15,16 @@ import { splitStoredPlace } from "../sports/providers.js";
import { claimInbox } from "./adopt.js";
const HOUR = 3600_000;
/** An older app does not send `galleries`. Keep the sizes already stored instead of clearing them. */
function keptGalleries(next: AutopilotSettings | null, current: Prisma.JsonValue): AutopilotSettings | typeof Prisma.DbNull {
if (!next) return Prisma.DbNull;
if (next.galleries !== undefined) return next;
if (!current || typeof current !== "object" || Array.isArray(current)) return next;
const kept = (current as { galleries?: AutopilotSettings["galleries"] }).galleries;
if (!Array.isArray(kept) || kept.length === 0) return next;
return { ...next, galleries: kept };
}
const OrgParams = z.object({ orgId: z.uuid() });
const EventParams = z.object({ eventId: z.uuid() });
@@ -242,7 +252,7 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
...(startsAt && { startsAt }),
...window,
...(iptcTemplate && { iptcTemplate }),
...(autopilot !== undefined && { autopilot: autopilot ?? Prisma.DbNull }),
...(autopilot !== undefined && { autopilot: keptGalleries(autopilot, current.autopilot) }),
...(archived !== undefined && { archivedAt: archived ? (current.archivedAt ?? new Date()) : null }),
},
include,
+27 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { AutopilotSettings } from "@photoreport/contracts";
import { exportTargets, picksNeeded } from "../src/autopilot/targets.js";
import { exportTargets, galleryReceivers, picksNeeded } from "../src/autopilot/targets.js";
const a = "11111111-1111-4111-8111-111111111111";
const b = "22222222-2222-4222-8222-222222222222";
@@ -27,3 +27,29 @@ describe("picksNeeded", () => {
expect(picksNeeded(AutopilotSettings.parse({ enabled: true, picksPerBurst: 2 }))).toBe(2);
});
});
describe("galleryReceivers", () => {
const zz = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const liga = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const galleries = [
{ targetId: zz, count: 30 },
{ targetId: liga, count: 100 },
];
it("sends a short-gallery frame to the short client and to the larger one", () => {
const chosen = new Map<string, Set<string>>([
[zz, new Set(["p1"])],
[liga, new Set(["p1", "p2"])],
]);
expect(galleryReceivers("p1", galleries, chosen).sort()).toEqual([liga, zz].sort());
expect(galleryReceivers("p2", galleries, chosen)).toEqual([liga]);
});
it("puts a frame only the short gallery picked into the larger gallery too", () => {
const chosen = new Map<string, Set<string>>([
[zz, new Set(["p1"])],
[liga, new Set()],
]);
expect(galleryReceivers("p1", galleries, chosen).sort()).toEqual([liga, zz].sort());
});
});
+14
View File
@@ -69,6 +69,20 @@ export const AutopilotSettings = z.object({
*/
selection: z.enum(["bursts", "best"]).default("bursts"),
bestCount: z.number().int().min(5).max(300).default(30),
/**
* One gallery size per destination ("only the best"). The match is spread to the largest count; a smaller
* gallery receives its own spread, and those frames also go to every larger gallery. Empty: every destination
* shares `bestCount`, one frame of each burst each.
*/
galleries: z
.array(
z.object({
targetId: z.string().uuid(),
count: z.number().int().min(5).max(300),
}),
)
.max(10)
.optional(),
/**
* Legacy second export. With two destinations, each burst's best goes to `deliverTargetId` and the second best
* to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`.