Send leftover picks to the rest client during a live gallery #318
No files matched your search
@@ -82,6 +82,41 @@ const median = (xs: number[]) => {
|
||||
return s[Math.floor(s.length / 2)]!;
|
||||
};
|
||||
|
||||
/** A gallery window. Warm-up (more than one window before kick-off) is −1 and is never sent. */
|
||||
export const BEST_WINDOW_MS = 5 * 60_000;
|
||||
|
||||
/** Window index from kick-off. The five minutes just before the start still belong to the first window. */
|
||||
export function bestWindow(at: number, start: number, windowMs = BEST_WINDOW_MS): number {
|
||||
if (at < start - windowMs) return -1;
|
||||
const index = Math.floor((at - start) / windowMs);
|
||||
if (index < 0) return 0;
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows that still have a frame being analysed. A live match keeps receiving photos, so a closed
|
||||
* window must be allowed to send while a later one is still open.
|
||||
*/
|
||||
export function windowsStillArriving(start: number, inflightAt: readonly number[], windowMs = BEST_WINDOW_MS): Set<number> {
|
||||
const blocked = new Set<number>();
|
||||
for (const at of inflightAt) {
|
||||
const window = bestWindow(at, start, windowMs);
|
||||
if (window < 0) continue;
|
||||
blocked.add(window);
|
||||
}
|
||||
return blocked;
|
||||
}
|
||||
|
||||
/** True when another frame of this same moment is still being analysed, so the burst is not complete. */
|
||||
export function burstStillArriving(from: number, to: number, inflightAt: readonly number[], gapMs: number): boolean {
|
||||
for (const at of inflightAt) {
|
||||
if (at < from - gapMs) continue;
|
||||
if (at > to + gapMs) continue;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* How many frames a gallery may reach. The asked size is the target: about 15% more when the match is rich,
|
||||
* at least 2 and never more than 25 past it, so a short gallery stays close and a long one can breathe.
|
||||
@@ -96,7 +131,7 @@ export function galleryCeiling(count: number): number {
|
||||
* (chosen or not), so earlier choices count against the gallery size.
|
||||
*/
|
||||
export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean; at?: number }[], opts: CurateOptions): WindowDecision[] {
|
||||
const windowMs = opts.windowMs ?? 5 * 60_000;
|
||||
const windowMs = opts.windowMs ?? BEST_WINDOW_MS;
|
||||
const minGapMs = opts.minGapMs ?? 5_000;
|
||||
const sequenceGapMs = opts.sequenceGapMs ?? SEQUENCE_PICK_GAP_MS;
|
||||
const sequenceCap = opts.sequenceCap ?? SEQUENCE_PICK_CAP;
|
||||
@@ -119,8 +154,8 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b
|
||||
const byWindow = new Map<number, typeof scored>();
|
||||
for (const x of scored) {
|
||||
if (done.has(x.c.id)) continue;
|
||||
// Warm-up and line-ups (more than 5 minutes before kick-off) are not game moments.
|
||||
const w = x.c.at < opts.start - 5 * 60_000 ? -1 : Math.max(0, Math.floor((x.c.at - opts.start) / windowMs));
|
||||
// Warm-up and line-ups (more than one window before kick-off) are not game moments.
|
||||
const w = bestWindow(x.c.at, opts.start, windowMs);
|
||||
byWindow.set(w, [...(byWindow.get(w) ?? []), x]);
|
||||
}
|
||||
const out: WindowDecision[] = [];
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BEST_WINDOW_MS, bestWindow, burstStillArriving, windowsStillArriving } from "./curate.js";
|
||||
|
||||
const start = Date.parse("2026-11-29T17:00:00Z");
|
||||
|
||||
describe("best windows while a match is still being analysed", () => {
|
||||
it("keeps the five minutes before kick-off in the first window and the warm-up out", () => {
|
||||
expect(bestWindow(start - BEST_WINDOW_MS - 1, start)).toBe(-1);
|
||||
expect(bestWindow(start - 60_000, start)).toBe(0);
|
||||
expect(bestWindow(start + BEST_WINDOW_MS, start)).toBe(1);
|
||||
});
|
||||
|
||||
it("blocks only the window that still has a frame in analysis", () => {
|
||||
const later = start + 10 * BEST_WINDOW_MS + 30_000;
|
||||
const blocked = windowsStillArriving(start, [later]);
|
||||
expect(blocked.has(0)).toBe(false);
|
||||
expect(blocked.has(10)).toBe(true);
|
||||
});
|
||||
|
||||
it("holds a burst when another frame of the same moment is still in analysis", () => {
|
||||
const from = start + 1_000;
|
||||
const to = start + 1_400;
|
||||
expect(burstStillArriving(from, to, [to + 500], 1_000)).toBe(true);
|
||||
expect(burstStillArriving(from, to, [to + 5_000], 1_000)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { homeRestDecision, type FaceHint } from "./home-rest.js";
|
||||
|
||||
const start = Date.parse("2026-12-02T20:15:00Z");
|
||||
const leadMin = 10;
|
||||
const homeNames = new Set(["joao silva"]);
|
||||
const homeClubs = new Set(["u. leiria"]);
|
||||
|
||||
function decide(extra: {
|
||||
at: number;
|
||||
facesStatus?: string;
|
||||
playerNames?: string[];
|
||||
faces?: FaceHint[];
|
||||
homeTeamId?: string | null;
|
||||
}) {
|
||||
return homeRestDecision({
|
||||
at: extra.at,
|
||||
start,
|
||||
leadMin,
|
||||
facesStatus: extra.facesStatus ?? "DONE",
|
||||
playerNames: extra.playerNames ?? [],
|
||||
faces: extra.faces ?? [],
|
||||
homeTeamId: extra.homeTeamId ?? "home",
|
||||
homeNames,
|
||||
homeClubs,
|
||||
});
|
||||
}
|
||||
|
||||
describe("leftover picks before and during a match", () => {
|
||||
it("sends every leftover pick until ten minutes before kick-off", () => {
|
||||
expect(decide({ at: start - 10 * 60_000 })).toBe("send");
|
||||
expect(decide({ at: start - 10 * 60_000 - 1, facesStatus: "PENDING" })).toBe("send");
|
||||
});
|
||||
|
||||
it("sends a home player after the cutoff and holds a frame whose faces are still open", () => {
|
||||
const after = start - 10 * 60_000 + 1;
|
||||
expect(decide({ at: after, playerNames: ["João Silva"] })).toBe("send");
|
||||
expect(
|
||||
decide({
|
||||
at: after,
|
||||
faces: [{ teamId: "home", name: "Outro", club: null, open: false }],
|
||||
}),
|
||||
).toBe("send");
|
||||
expect(
|
||||
decide({
|
||||
at: after,
|
||||
facesStatus: "DONE",
|
||||
faces: [{ teamId: null, name: null, club: null, open: true }],
|
||||
}),
|
||||
).toBe("wait");
|
||||
expect(decide({ at: after, facesStatus: "PENDING" })).toBe("wait");
|
||||
});
|
||||
|
||||
it("does not send an away player once the faces are settled", () => {
|
||||
const after = start + 30_000;
|
||||
expect(
|
||||
decide({
|
||||
at: after,
|
||||
faces: [{ teamId: "away", name: "Costa", club: "Sporting CP B", open: false }],
|
||||
}),
|
||||
).toBe("skip");
|
||||
expect(decide({ at: after, facesStatus: "FAILED" })).toBe("skip");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/** Same bar the face worker uses before it trusts a suggestion (faces/service.ts). */
|
||||
export const STRONG_FACE = 0.85;
|
||||
|
||||
export interface FaceHint {
|
||||
teamId: string | null;
|
||||
name: string | null;
|
||||
club: string | null;
|
||||
/** A face is in the frame and nobody confident has been named yet. */
|
||||
open: boolean;
|
||||
}
|
||||
|
||||
export interface NamedPerson {
|
||||
name: string;
|
||||
club: string | null;
|
||||
teamId: string | null;
|
||||
}
|
||||
|
||||
/** One face group, reduced to whether we can already tell the team. Ignored groups are not people. */
|
||||
export function hintFromGroup(
|
||||
group: {
|
||||
personId: string | null;
|
||||
suggestedPersonId: string | null;
|
||||
suggestionScore: number | null;
|
||||
ignored: boolean;
|
||||
} | null,
|
||||
person: NamedPerson | null,
|
||||
suggested: NamedPerson | null,
|
||||
): FaceHint | null {
|
||||
if (!group || group.ignored) return null;
|
||||
if (group.personId) {
|
||||
if (!person) return { teamId: null, name: null, club: null, open: true };
|
||||
return { teamId: person.teamId, name: person.name, club: person.club, open: false };
|
||||
}
|
||||
const score = group.suggestionScore ?? 0;
|
||||
if (group.suggestedPersonId && score >= STRONG_FACE) {
|
||||
if (!suggested) return { teamId: null, name: null, club: null, open: true };
|
||||
return { teamId: suggested.teamId, name: suggested.name, club: suggested.club, open: false };
|
||||
}
|
||||
return { teamId: null, name: null, club: null, open: true };
|
||||
}
|
||||
|
||||
export function foldName(value: string | null | undefined): string {
|
||||
if (!value) return "";
|
||||
return value
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function namedHome(
|
||||
name: string | null,
|
||||
club: string | null,
|
||||
homeNames: ReadonlySet<string>,
|
||||
homeClubs: ReadonlySet<string>,
|
||||
): boolean {
|
||||
const foldedName = foldName(name);
|
||||
if (foldedName && homeNames.has(foldedName)) return true;
|
||||
const foldedClub = foldName(club);
|
||||
if (foldedClub && homeClubs.has(foldedClub)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** True when this frame shows someone from the home squad. */
|
||||
export function isHomePlayer(input: {
|
||||
playerNames: readonly string[];
|
||||
faces: readonly FaceHint[];
|
||||
homeTeamId: string | null;
|
||||
homeNames: ReadonlySet<string>;
|
||||
homeClubs: ReadonlySet<string>;
|
||||
}): boolean {
|
||||
for (const name of input.playerNames) {
|
||||
if (namedHome(name, null, input.homeNames, input.homeClubs)) return true;
|
||||
}
|
||||
for (const face of input.faces) {
|
||||
if (face.open) continue;
|
||||
if (input.homeTeamId && face.teamId === input.homeTeamId) return true;
|
||||
if (namedHome(face.name, face.club, input.homeNames, input.homeClubs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Leftover picks for the rest destination.
|
||||
* Up to `leadMin` before kick-off, every leftover pick goes.
|
||||
* After that, only a home-team player. Faces still being read stay queued (`wait`).
|
||||
*/
|
||||
export function homeRestDecision(input: {
|
||||
at: number;
|
||||
start: number;
|
||||
leadMin: number;
|
||||
facesStatus: string;
|
||||
playerNames: readonly string[];
|
||||
faces: readonly FaceHint[];
|
||||
homeTeamId: string | null;
|
||||
homeNames: ReadonlySet<string>;
|
||||
homeClubs: ReadonlySet<string>;
|
||||
}): "send" | "skip" | "wait" {
|
||||
const cutoff = input.start - input.leadMin * 60_000;
|
||||
if (input.at <= cutoff) return "send";
|
||||
if (isHomePlayer(input)) return "send";
|
||||
if (input.facesStatus === "PENDING" || input.facesStatus === "RUNNING") return "wait";
|
||||
for (const face of input.faces) {
|
||||
if (face.open) return "wait";
|
||||
}
|
||||
return "skip";
|
||||
}
|
||||
@@ -26,7 +26,8 @@ import {
|
||||
sequenceIndex,
|
||||
sequenceSendRoom,
|
||||
} from "./bursts.js";
|
||||
import { curate, matchMinutes } from "./curate.js";
|
||||
import { bestWindow, burstStillArriving, curate, matchMinutes, windowsStillArriving } from "./curate.js";
|
||||
import { foldName, hintFromGroup, homeRestDecision, type FaceHint, type NamedPerson } from "./home-rest.js";
|
||||
import { type LearntStyle, learntStyle } from "./learning.js";
|
||||
import { detailForCrop, lookValues } from "./look.js";
|
||||
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js";
|
||||
@@ -46,6 +47,20 @@ function takenHere(ids: readonly string[], when: ReadonlyMap<string, Date | null
|
||||
return ids.filter((id) => takenDuring(when.get(id), event));
|
||||
}
|
||||
|
||||
/** Capture time of photos this event is still analysing. A live match uses this so closed windows are not held back. */
|
||||
async function inflightCaptureTimes(db: Db, eventId: string): Promise<number[]> {
|
||||
const rows = await db.photo.findMany({
|
||||
where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } },
|
||||
select: { capturedAt: true, createdAt: true },
|
||||
});
|
||||
const times: number[] = [];
|
||||
for (const row of rows) {
|
||||
const at = row.capturedAt ?? row.createdAt;
|
||||
times.push(at.getTime());
|
||||
}
|
||||
return times;
|
||||
}
|
||||
|
||||
export interface AutopilotRecord {
|
||||
score: number;
|
||||
reason: string | null;
|
||||
@@ -78,6 +93,10 @@ export interface AutopilotRecord {
|
||||
hold?: "ball";
|
||||
/** Per destination gallery: true when this frame was picked for it, false when its window decided against it. */
|
||||
gallery?: Record<string, boolean>;
|
||||
/** Leftover pick already queued for the rest destination. */
|
||||
restSent?: boolean;
|
||||
/** Leftover pick that is not a home player, so it stays out of the rest destination. */
|
||||
restSkip?: boolean;
|
||||
/**
|
||||
* Planned develop/crop ops from analysis. Applied only when this frame is picked for the burst — never on the
|
||||
* near-duplicates left unflagged.
|
||||
@@ -104,6 +123,9 @@ export class AutopilotService {
|
||||
},
|
||||
) {}
|
||||
|
||||
/** Leftover picks are retried on a slow cadence: face names arrive after the window has closed. */
|
||||
private restFlushAt = 0;
|
||||
|
||||
/** The upright preview, so a sequence can compare eyes. Null when it was never rendered. */
|
||||
private previewFile(photo: { organizationId: string; sha256: string }): string | null {
|
||||
const file = this.deps.storage.resolve(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "preview"));
|
||||
@@ -263,8 +285,8 @@ export class AutopilotService {
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, organizationId: true, autopilot: true, createdById: true, away: true, fixtureId: true, ingestFrom: true, ingestUntil: true } });
|
||||
if (!event) continue;
|
||||
const settings = AutopilotSettings.parse(event.autopilot ?? {});
|
||||
const busy = await db.photo.count({ where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } } });
|
||||
if (busy) continue;
|
||||
// A live match always has photos still being analysed. That must not hold the windows that already closed.
|
||||
const inflightAt = await inflightCaptureTimes(db, eventId);
|
||||
const photos = await db.photo.findMany({
|
||||
where: { eventId, autopilotStatus: "DONE" },
|
||||
select: { id: true, capturedAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, createdAt: true, flag: true, autopilot: true, width: true, height: true, sha256: true, facesStatus: true, iso: true },
|
||||
@@ -295,8 +317,11 @@ export class AutopilotService {
|
||||
for (let burstIndex = 0; burstIndex < orderedBursts.length; burstIndex++) {
|
||||
const burst = orderedBursts[burstIndex]!;
|
||||
if (burst.every((f) => f.rec?.decided)) continue;
|
||||
// Still arriving: wait until the burst has settled.
|
||||
// Still arriving: wait until the burst has settled, and until a frame of the same moment finishes analysis.
|
||||
if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue;
|
||||
const burstFrom = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
|
||||
const burstTo = Math.max(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
|
||||
if (burstStillArriving(burstFrom, burstTo, inflightAt, settings.burstGapSec * 1000)) continue;
|
||||
const reportage = reportageEvent;
|
||||
const sharp = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP).length;
|
||||
const need = picksNeeded(settings);
|
||||
@@ -315,7 +340,7 @@ export class AutopilotService {
|
||||
const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst;
|
||||
take = Math.min(asked, Math.max(0, cap));
|
||||
}
|
||||
const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
|
||||
const start = burstFrom;
|
||||
const sameCamera = frames
|
||||
.filter((f) => f.camera === burst[0]!.camera && !burst.some((b) => b.id === f.id))
|
||||
.map((f) => ({
|
||||
@@ -475,6 +500,10 @@ export class AutopilotService {
|
||||
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
|
||||
if (settings.selection === "best") picked += await this.curateEvent(eventId, settings, now);
|
||||
}
|
||||
if (now.getTime() - this.restFlushAt >= 20_000) {
|
||||
this.restFlushAt = now.getTime();
|
||||
await this.flushHomeRest();
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
@@ -505,6 +534,13 @@ export class AutopilotService {
|
||||
// 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");
|
||||
// A window that still has a frame in analysis stays open. The ones already complete can leave now.
|
||||
const blockedWindows = windowsStillArriving(event.startsAt.getTime(), await inflightCaptureTimes(db, eventId));
|
||||
const ready = candidates.filter((candidate) => {
|
||||
const window = bestWindow(candidate.at, event.startsAt.getTime());
|
||||
if (blockedWindows.has(window)) return false;
|
||||
return true;
|
||||
});
|
||||
const curateOpts = {
|
||||
start: event.startsAt.getTime(),
|
||||
durationMs: matchMinutes(event.sport) * 60_000,
|
||||
@@ -512,7 +548,7 @@ export class AutopilotService {
|
||||
minGapMs: MELHORES_GAP_MS,
|
||||
sequenceCap: settings.picksPerBurst,
|
||||
};
|
||||
const decisions = curate(candidates, decided, {
|
||||
const decisions = curate(ready, decided, {
|
||||
count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount,
|
||||
...curateOpts,
|
||||
});
|
||||
@@ -533,7 +569,7 @@ export class AutopilotService {
|
||||
const flag = (p.autopilot as unknown as AutopilotRecord | null)?.gallery?.[g.targetId];
|
||||
return flag === undefined ? [] : [{ id: p.id, chosen: flag, at: p.capturedAt?.getTime() ?? 0 }];
|
||||
});
|
||||
const parts = curate(candidates, earlier, { count: g.count, ...curateOpts });
|
||||
const parts = curate(ready, 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)));
|
||||
}
|
||||
@@ -625,8 +661,257 @@ export class AutopilotService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof settings.restHomeFromMin === "number" && settings.restTargetId && galleries.length) {
|
||||
await this.sendGalleryRest(eventId, settings);
|
||||
}
|
||||
return chosenCount;
|
||||
}
|
||||
|
||||
/** Events whose leftover picks are still waiting on a face name. */
|
||||
private async flushHomeRest(): Promise<void> {
|
||||
const { db, log } = this.deps;
|
||||
const rows = await db.$queryRaw<{ event_id: string }[]>`
|
||||
SELECT DISTINCT p.event_id
|
||||
FROM photos p
|
||||
JOIN events e ON e.id = p.event_id
|
||||
WHERE p.flag = 'PICK'
|
||||
AND p.autopilot_status = 'DONE'
|
||||
AND p.created_at > now() - interval '2 days'
|
||||
AND (p.autopilot->>'curated') = 'true'
|
||||
AND (p.autopilot->>'restSent') IS DISTINCT FROM 'true'
|
||||
AND (p.autopilot->>'restSkip') IS DISTINCT FROM 'true'
|
||||
AND jsonb_typeof(e.autopilot->'restHomeFromMin') = 'number'
|
||||
AND e.autopilot->>'restTargetId' IS NOT NULL
|
||||
AND jsonb_typeof(e.autopilot->'galleries') = 'array'
|
||||
AND jsonb_array_length(e.autopilot->'galleries') > 0
|
||||
`;
|
||||
for (const row of rows) {
|
||||
const event = await db.event.findUnique({ where: { id: row.event_id }, select: { autopilot: true } });
|
||||
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
|
||||
await this.sendGalleryRest(row.event_id, settings).catch((err: unknown) => {
|
||||
log.warn({ err, eventId: row.event_id }, "autopilot: leftover delivery not queued");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks that did not make a gallery. Until `restHomeFromMin` before kick-off they all go to the rest
|
||||
* destination. From then on, only a home-team player does, and a frame whose faces are still open waits.
|
||||
*/
|
||||
private async sendGalleryRest(eventId: string, settings: AutopilotSettings): Promise<number> {
|
||||
const leadMin = settings.restHomeFromMin;
|
||||
const restTargetId = settings.restTargetId;
|
||||
const galleries = settings.galleries ?? [];
|
||||
if (typeof leadMin !== "number" || !restTargetId || !galleries.length) return 0;
|
||||
if (!this.deps.deliveries) return 0;
|
||||
const { db, log } = this.deps;
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
select: {
|
||||
organizationId: true,
|
||||
startsAt: true,
|
||||
createdById: true,
|
||||
ingestFrom: true,
|
||||
ingestUntil: true,
|
||||
home: true,
|
||||
homeShort: true,
|
||||
homeTeamId: true,
|
||||
fixture: { select: { season: true } },
|
||||
homeTeam: { select: { name: true, abbreviation: true } },
|
||||
},
|
||||
});
|
||||
if (!event?.createdById) return 0;
|
||||
const photos = await db.photo.findMany({
|
||||
where: { eventId, flag: "PICK", autopilotStatus: "DONE" },
|
||||
select: { id: true, capturedAt: true, createdAt: true, players: true, facesStatus: true, autopilot: true },
|
||||
});
|
||||
const cutoff = event.startsAt.getTime() - leadMin * 60_000;
|
||||
const pending: typeof photos = [];
|
||||
for (const photo of photos) {
|
||||
const rec = photo.autopilot as AutopilotRecord | null;
|
||||
if (!rec?.curated) continue;
|
||||
if (rec.restSent || rec.restSkip) continue;
|
||||
if (rec.hold === "ball" || rec.chosen) continue;
|
||||
if (!takenDuring(photo.capturedAt, event)) continue;
|
||||
let inGallery = false;
|
||||
for (const gallery of galleries) {
|
||||
if (rec.gallery?.[gallery.targetId] === true) inGallery = true;
|
||||
}
|
||||
if (inGallery) continue;
|
||||
pending.push(photo);
|
||||
}
|
||||
if (!pending.length) return 0;
|
||||
|
||||
const homeNames = new Set<string>();
|
||||
const homeClubs = new Set<string>();
|
||||
for (const label of [event.home, event.homeShort, event.homeTeam?.name, event.homeTeam?.abbreviation]) {
|
||||
const folded = foldName(label);
|
||||
if (folded) homeClubs.add(folded);
|
||||
}
|
||||
if (event.homeTeamId) {
|
||||
const season = event.fixture?.season ?? null;
|
||||
let squad: { name: string; fullName: string | null }[] = [];
|
||||
if (season) {
|
||||
squad = await db.sportsPlayer.findMany({
|
||||
where: { teamId: event.homeTeamId, goneAt: null, season },
|
||||
select: { name: true, fullName: true },
|
||||
});
|
||||
}
|
||||
if (!squad.length) {
|
||||
squad = await db.sportsPlayer.findMany({
|
||||
where: { teamId: event.homeTeamId, goneAt: null },
|
||||
select: { name: true, fullName: true },
|
||||
});
|
||||
}
|
||||
for (const player of squad) {
|
||||
const name = foldName(player.name);
|
||||
const fullName = foldName(player.fullName);
|
||||
if (name) homeNames.add(name);
|
||||
if (fullName) homeNames.add(fullName);
|
||||
}
|
||||
}
|
||||
|
||||
const faceIds: string[] = [];
|
||||
for (const photo of pending) {
|
||||
const at = photo.capturedAt?.getTime() ?? photo.createdAt.getTime();
|
||||
if (at > cutoff) faceIds.push(photo.id);
|
||||
}
|
||||
const hints = new Map<string, FaceHint[]>();
|
||||
if (faceIds.length) {
|
||||
const faces = await db.face.findMany({
|
||||
where: { photoId: { in: faceIds } },
|
||||
select: {
|
||||
photoId: true,
|
||||
group: {
|
||||
select: {
|
||||
personId: true,
|
||||
suggestedPersonId: true,
|
||||
suggestionScore: true,
|
||||
ignoredAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const personIds: string[] = [];
|
||||
for (const face of faces) {
|
||||
if (face.group?.personId) personIds.push(face.group.personId);
|
||||
if (face.group?.suggestedPersonId) personIds.push(face.group.suggestedPersonId);
|
||||
}
|
||||
let people: { id: string; name: string; club: string | null; sportsPlayerId: string | null }[] = [];
|
||||
if (personIds.length > 0) {
|
||||
people = await db.person.findMany({
|
||||
where: { id: { in: [...new Set(personIds)] } },
|
||||
select: { id: true, name: true, club: true, sportsPlayerId: true },
|
||||
});
|
||||
}
|
||||
const sportsIds: string[] = [];
|
||||
for (const person of people) {
|
||||
if (person.sportsPlayerId) sportsIds.push(person.sportsPlayerId);
|
||||
}
|
||||
let sports: { id: string; teamId: string }[] = [];
|
||||
if (sportsIds.length > 0) {
|
||||
sports = await db.sportsPlayer.findMany({
|
||||
where: { id: { in: sportsIds } },
|
||||
select: { id: true, teamId: true },
|
||||
});
|
||||
}
|
||||
const teamOf = new Map(sports.map((player) => [player.id, player.teamId]));
|
||||
const named = new Map<string, NamedPerson>();
|
||||
for (const person of people) {
|
||||
let teamId: string | null = null;
|
||||
if (person.sportsPlayerId) {
|
||||
const found = teamOf.get(person.sportsPlayerId);
|
||||
if (found) teamId = found;
|
||||
}
|
||||
named.set(person.id, { name: person.name, club: person.club, teamId });
|
||||
}
|
||||
for (const face of faces) {
|
||||
let group: {
|
||||
personId: string | null;
|
||||
suggestedPersonId: string | null;
|
||||
suggestionScore: number | null;
|
||||
ignored: boolean;
|
||||
} | null = null;
|
||||
if (face.group) {
|
||||
group = {
|
||||
personId: face.group.personId,
|
||||
suggestedPersonId: face.group.suggestedPersonId,
|
||||
suggestionScore: face.group.suggestionScore,
|
||||
ignored: face.group.ignoredAt !== null,
|
||||
};
|
||||
}
|
||||
let person: NamedPerson | null = null;
|
||||
if (face.group?.personId) {
|
||||
person = named.get(face.group.personId) ?? null;
|
||||
}
|
||||
let suggested: NamedPerson | null = null;
|
||||
if (face.group?.suggestedPersonId) {
|
||||
suggested = named.get(face.group.suggestedPersonId) ?? null;
|
||||
}
|
||||
const hint = hintFromGroup(group, person, suggested);
|
||||
if (!hint) continue;
|
||||
const list = hints.get(face.photoId) ?? [];
|
||||
list.push(hint);
|
||||
hints.set(face.photoId, list);
|
||||
}
|
||||
}
|
||||
|
||||
const send: typeof photos = [];
|
||||
for (const photo of pending) {
|
||||
const at = photo.capturedAt?.getTime() ?? photo.createdAt.getTime();
|
||||
const decision = homeRestDecision({
|
||||
at,
|
||||
start: event.startsAt.getTime(),
|
||||
leadMin,
|
||||
facesStatus: photo.facesStatus,
|
||||
playerNames: photo.players,
|
||||
faces: hints.get(photo.id) ?? [],
|
||||
homeTeamId: event.homeTeamId,
|
||||
homeNames,
|
||||
homeClubs,
|
||||
});
|
||||
if (decision === "wait") continue;
|
||||
if (decision === "skip") {
|
||||
await this.markRest(photo, "restSkip");
|
||||
continue;
|
||||
}
|
||||
send.push(photo);
|
||||
}
|
||||
if (!send.length) return 0;
|
||||
|
||||
let queued = 0;
|
||||
const chunk = 40;
|
||||
for (let index = 0; index < send.length; index += chunk) {
|
||||
const slice = send.slice(index, index + chunk);
|
||||
const result = await this.deps.deliveries.enqueue({
|
||||
organizationId: event.organizationId,
|
||||
targetId: restTargetId,
|
||||
photoIds: slice.map((photo) => photo.id),
|
||||
again: false,
|
||||
requestedById: event.createdById,
|
||||
});
|
||||
const done = new Set(result.queued.map((item) => item.photoId));
|
||||
for (const skipped of result.skipped) {
|
||||
if (skipped.reason === "already_delivered") done.add(skipped.photoId);
|
||||
}
|
||||
for (const photo of slice) {
|
||||
if (!done.has(photo.id)) continue;
|
||||
await this.markRest(photo, "restSent");
|
||||
queued += 1;
|
||||
}
|
||||
}
|
||||
if (queued) log.info({ eventId, queued, restTargetId }, "autopilot: leftover picks queued");
|
||||
return queued;
|
||||
}
|
||||
|
||||
private async markRest(photo: { id: string; autopilot: unknown }, key: "restSent" | "restSkip"): Promise<void> {
|
||||
const rec = photo.autopilot;
|
||||
if (!rec || typeof rec !== "object" || Array.isArray(rec)) return;
|
||||
await this.deps.db.photo.update({
|
||||
where: { id: photo.id },
|
||||
data: { autopilot: { ...rec, [key]: true } as object },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Gallery flags for a frame whose window was decided this pass. Unmentioned destinations stay as they were. */
|
||||
|
||||
@@ -151,7 +151,7 @@ function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra:
|
||||
matchNumber: "1",
|
||||
startsAt,
|
||||
},
|
||||
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
|
||||
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1, fileName: "IMG_0001.JPG" },
|
||||
"Fotógrafo",
|
||||
);
|
||||
const fileSample = { ...built, ...extra };
|
||||
|
||||
@@ -16,14 +16,24 @@ 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. */
|
||||
/**
|
||||
* An older app does not send `galleries` or `restHomeFromMin`. Keep what is already stored instead of clearing it.
|
||||
*/
|
||||
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 prev = current as {
|
||||
galleries?: AutopilotSettings["galleries"];
|
||||
restHomeFromMin?: number | null;
|
||||
};
|
||||
let out = next;
|
||||
if (next.galleries === undefined && Array.isArray(prev.galleries) && prev.galleries.length > 0) {
|
||||
out = { ...out, galleries: prev.galleries };
|
||||
}
|
||||
if (next.restHomeFromMin === undefined && typeof prev.restHomeFromMin === "number") {
|
||||
out = { ...out, restHomeFromMin: prev.restHomeFromMin };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
const EventParams = z.object({ eventId: z.uuid() });
|
||||
|
||||
@@ -104,6 +104,12 @@ export const AutopilotSettings = z.object({
|
||||
* to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`.
|
||||
*/
|
||||
restTargetId: z.string().uuid().nullable().default(null),
|
||||
/**
|
||||
* With galleries and `restTargetId`: leftover picks go to the rest destination until this many minutes
|
||||
* before kick-off. After that, only a leftover pick of a home-team player does. Omitted: galleries do not
|
||||
* send leftovers (an older app leaves this out; the stored value is kept).
|
||||
*/
|
||||
restHomeFromMin: z.number().int().min(0).max(180).nullable().optional(),
|
||||
});
|
||||
export type AutopilotSettings = z.infer<typeof AutopilotSettings>;
|
||||
|
||||
|
||||
Reference in new issue
Block a user