Keep the picture the photographer framed, including the ball and the players.
ci / rust (pull_request) Successful in 4m18s
ci / typescript (pull_request) Failing after 9m17s

A tight crop was dropping a ball held out to the side and a second player, and a learnt cut could chop a body the frame had kept. Reportage stays open, open eyes win a sequence, and a Canon file that still has the camera level uses that roll. The library menu, sort, and event-day folder go out with the same change.
This commit is contained in:
spark committed 2026-11-21 19:50:51 +00:00
1 parent 8fe822e6cb
commit 784a872e52
55 files changed
+2331 -272

No files matched your search

+4 -2
View File
@@ -1,7 +1,7 @@
import type { Db } from "../db.js";
import { bestOf, groupBursts } from "./bursts.js";
import { type Candidate, type WindowDecision, actionScore, curate, matchMinutes } from "./curate.js";
import { sequenceWeights } from "./sequence.js";
import { rankForPick, sequenceWeights } from "./sequence.js";
import type { AutopilotRecord } from "./service.js";
interface PhotoRow {
@@ -48,7 +48,8 @@ export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided
const out: Candidate[] = [];
groupBursts(frames, burstGapMs).forEach((burst, i) => {
if (onlyDecided && !burst.every((f) => f.rec?.decided)) return;
const [first, second] = bestOf(burst, 2);
const pool = rankForPick(burst, burst.map((f) => f.look ?? 1), () => true);
const [first, second] = bestOf(pool, 2);
const best = frame === "second" && second && second.flag !== "REJECT" ? second : first;
if (!best) return;
const rec = best.rec;
@@ -62,6 +63,7 @@ export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided
reason: rec?.reason ?? (best.score || marked ? "person" : null),
people: rec?.people ?? null,
subjectHeight: rec?.subject ? rec.subject.y1 - rec.subject.y0 : null,
subject: rec?.subject ?? null,
rating: best.rating,
rejected: best.flag === "REJECT",
});
+31 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { bestOf } from "./bursts.js";
import { bestOf, looksDifferent, othersInSequence, SEQUENCE_PICK_GAP_MS, sequenceSendRoom } from "./bursts.js";
describe("bestOf", () => {
const f = (id: string, score: number) => ({ id, capturedAt: new Date(score), camera: "R1", score });
@@ -10,3 +10,33 @@ describe("bestOf", () => {
expect(bestOf(burst, 2).map((x) => x.id)).toEqual(["middle", "last"]);
});
});
describe("othersInSequence", () => {
it("counts a chain of frames a second apart and stops at a real gap", () => {
const times = [0, 2_000, 4_000, 6_000, 30_000];
expect(othersInSequence(times, 8_000, SEQUENCE_PICK_GAP_MS)).toBe(4);
expect(othersInSequence(times, 30_000, SEQUENCE_PICK_GAP_MS)).toBe(0);
});
});
describe("sequenceSendRoom", () => {
const standing = {
subject: { x0: 0.4, y0: 0.2, x1: 0.6, y1: 0.9 },
people: 1,
reason: "person",
};
const wide = {
subject: { x0: 0.1, y0: 0.35, x1: 0.9, y1: 0.7 },
people: 3,
reason: "group",
};
it("stops on repeats of the same picture and allows a different one", () => {
expect(looksDifferent(standing, standing)).toBe(false);
expect(looksDifferent(standing, wide)).toBe(true);
expect(sequenceSendRoom(1, [standing], standing)).toBe(0);
expect(sequenceSendRoom(1, [standing], wide)).toBe(1);
expect(sequenceSendRoom(2, [standing], standing)).toBe(1);
expect(sequenceSendRoom(2, [standing, standing, wide, wide], standing)).toBe(0);
});
});
+132
View File
@@ -54,6 +54,138 @@ export function groupBursts<F extends Frame>(frames: F[], gapMs: number): F[][]
/** A good reportage sequence can yield several plans. More than this of one moment is too many. */
export const REPORTAGE_SEQUENCE_CAP = 3;
/**
* A match gallery keeps at most this many frames of one sequence. The motor-drive gap splits a slow
* sequence (a coach on the touchline, a second between frames) into many bursts; those still count as one.
*/
export const SEQUENCE_PICK_CAP = 2;
/** Frames this close, on the same camera, are still the same sequence. */
export const SEQUENCE_PICK_GAP_MS = 12_000;
/**
* How many picks already sit in the sequence that `atMs` belongs to. Times further than `gapMs` from the
* nearest frame of that chain are another moment.
*/
export function othersInSequence(timesMs: readonly number[], atMs: number, gapMs: number): number {
const before: number[] = [];
const after: number[] = [];
for (const t of timesMs) {
if (t < atMs) before.push(t);
else if (t > atMs) after.push(t);
}
before.sort((a, b) => a - b);
after.sort((a, b) => a - b);
let count = 0;
let cursor = atMs;
for (let i = before.length - 1; i >= 0; i -= 1) {
const t = before[i]!;
if (cursor - t > gapMs) break;
count += 1;
cursor = t;
}
cursor = atMs;
for (const t of after) {
if (t - cursor > gapMs) break;
count += 1;
cursor = t;
}
return count;
}
/** A subject box in frame units (0–1). */
export interface LookBox {
x0: number;
y0: number;
x1: number;
y1: number;
}
/** What a frame shows, enough to tell a repeat of the same picture from a different one. */
export interface FrameLook {
subject: LookBox | null;
people: number | null;
reason: string | null;
}
/**
* Same moment, different picture: the action changed, a single figure became a group, the framing jumped
* from a close-up to a wide shot, or the subject moved to another part of the frame.
*/
export function looksDifferent(a: FrameLook, b: FrameLook): boolean {
if (a.reason && b.reason && a.reason !== b.reason) return true;
const aPeople = a.people ?? 0;
const bPeople = b.people ?? 0;
if (aPeople >= 2 && bPeople < 2) return true;
if (bPeople >= 2 && aPeople < 2) return true;
if (!a.subject || !b.subject) return false;
const aHeight = a.subject.y1 - a.subject.y0;
const bHeight = b.subject.y1 - b.subject.y0;
if (aHeight > 0 && bHeight > 0) {
const ratio = aHeight > bHeight ? aHeight / bHeight : bHeight / aHeight;
if (ratio >= 1.45) return true;
}
const aCenterX = (a.subject.x0 + a.subject.x1) / 2;
const aCenterY = (a.subject.y0 + a.subject.y1) / 2;
const bCenterX = (b.subject.x0 + b.subject.x1) / 2;
const bCenterY = (b.subject.y0 + b.subject.y1) / 2;
const moved = Math.hypot(aCenterX - bCenterX, aCenterY - bCenterY);
return moved >= 0.22;
}
/**
* Which sequence `atMs` belongs to. A gap larger than `gapMs` in the frames that were actually shot starts a
* new sequence, so a frame we did not pick still keeps the run together.
*/
export function sequenceIndex(timesMs: readonly number[], atMs: number, gapMs: number): number {
const sorted = [...timesMs].sort((a, b) => a - b);
let index = 0;
let prev = sorted[0];
if (prev === undefined) return 0;
for (const t of sorted) {
if (t - prev > gapMs) index += 1;
if (t === atMs) return index;
prev = t;
}
return index;
}
/** Frames of `frames` that belong to the same sequence as `atMs`. */
export function framesInSequence<T extends { atMs: number }>(frames: readonly T[], atMs: number, gapMs: number): T[] {
const sorted = [...frames].sort((a, b) => a.atMs - b.atMs);
const before = sorted.filter((frame) => frame.atMs < atMs);
const after = sorted.filter((frame) => frame.atMs > atMs);
const out: T[] = [];
let cursor = atMs;
for (let i = before.length - 1; i >= 0; i -= 1) {
const frame = before[i]!;
if (cursor - frame.atMs > gapMs) break;
out.push(frame);
cursor = frame.atMs;
}
cursor = atMs;
for (const frame of after) {
if (frame.atMs - cursor > gapMs) break;
out.push(frame);
cursor = frame.atMs;
}
return out;
}
/**
* Whether one more frame of this sequence may go to the destination. Repeats of a picture stop at the
* configured number. A frame that looks different may still go, up to four from the whole sequence.
*/
export const SEQUENCE_SEND_MAX = 4;
export function sequenceSendRoom(configured: number, already: readonly FrameLook[], next: FrameLook): number {
if (configured <= 0) return 0;
const same = already.filter((frame) => !looksDifferent(frame, next));
if (same.length >= configured) return 0;
const ceiling = Math.max(SEQUENCE_SEND_MAX, configured);
if (already.length >= ceiling) return 0;
return 1;
}
/**
* Variance of the Laplacian at 1024 px above this is a sharp frame. A sequence needs three such frames before
* it is worth more picks than the event asked for.
+39 -2
View File
@@ -1,10 +1,20 @@
import {
SEQUENCE_PICK_CAP,
SEQUENCE_PICK_GAP_MS,
sequenceIndex,
sequenceSendRoom,
type FrameLook,
} from "./bursts.js";
/**
* "Only the best" (docs/photo-editing-rules.md §5): for clients that want a short gallery of the match, not every
* usable frame. The match is cut into short windows, and each window may add its share of the gallery size, with
* the share it did not use carried forward (half-time adds nothing, a busy spell may take a little more).
* The asked size is a target: a rich match may pass it by about 15% (never more than 25 frames); a thin one stays under. Within a
* window the frames with the most action win: the ball in play, a duel or a celebration, a subject big in the
* frame and sharp; one frame per burst, and not two from the same few seconds. Anything well below the match's
* frame and sharp; one frame per burst, and not two from the same few seconds. A longer sequence (the same
* moment, frames a second apart) sends the configured number when the pictures look the same, and up to four
* when a frame is actually different. Anything well below the match's
* typical frame is left out even when the window has room.
*/
@@ -22,6 +32,8 @@ export interface Candidate {
people: number | null;
/** Height of the subject (0-1 of the frame). */
subjectHeight: number | null;
/** Subject box, when the analysis stored one. Used to tell a repeat from a different picture. */
subject?: FrameLook["subject"];
/** The photographer's stars (0-5); a rejected frame is never chosen. */
rating: number;
rejected: boolean;
@@ -48,6 +60,10 @@ export interface CurateOptions {
windowMs?: number;
/** Frames this close in time are the same moment. */
minGapMs?: number;
/** Frames this close are one sequence and share `sequenceCap`. */
sequenceGapMs?: number;
/** How many frames one sequence may contribute. */
sequenceCap?: number;
/** A window is decided once it ended this long ago. */
settleMs?: number;
now: number;
@@ -82,6 +98,8 @@ export function galleryCeiling(count: number): number {
export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean; at?: number }[], opts: CurateOptions): WindowDecision[] {
const windowMs = opts.windowMs ?? 5 * 60_000;
const minGapMs = opts.minGapMs ?? 5_000;
const sequenceGapMs = opts.sequenceGapMs ?? SEQUENCE_PICK_GAP_MS;
const sequenceCap = opts.sequenceCap ?? SEQUENCE_PICK_CAP;
const settleMs = opts.settleMs ?? 60_000;
const done = new Map(decided.map((d) => [d.id, d.chosen]));
// Choices already made. When each one carries its capture time, it only fills the windows up to its own,
@@ -120,7 +138,26 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b
const room = Math.max(0, Math.min(target - chosenSoFar, Math.ceil(3 * perWindow), opts.count - chosenSoFar));
const ranked = list.filter((x) => x.s > 0 && x.s >= floor).sort((a, b) => b.s - a.s);
const chosen: Candidate[] = [];
const fits = (c: Candidate) => !chosen.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < minGapMs);
const priorLooks = priorChosen.flatMap((d) =>
d.at === undefined ? [] : [{ at: d.at, look: { subject: null, people: null, reason: null } }],
);
const shotAt = [...list.map((x) => x.c.at), ...priorLooks.map((frame) => frame.at)];
const fits = (c: Candidate) => {
if (chosen.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < minGapMs)) return false;
const key = sequenceIndex(shotAt, c.at, sequenceGapMs);
const near = [
...priorLooks.filter((frame) => sequenceIndex(shotAt, frame.at, sequenceGapMs) === key),
...chosen
.filter((o) => sequenceIndex(shotAt, o.at, sequenceGapMs) === key)
.map((o) => ({ look: { subject: o.subject ?? null, people: o.people, reason: o.reason } })),
];
const room = sequenceSendRoom(
sequenceCap,
near.map((frame) => frame.look),
{ subject: c.subject ?? null, people: c.people, reason: c.reason },
);
return room > 0;
};
for (const { c } of ranked) {
if (chosen.length >= room) break;
if (!fits(c)) continue;
+27 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { sequenceWeight } from "./sequence.js";
import { rankForPick, sequenceWeight } from "./sequence.js";
describe("sequence choice", () => {
it("prefers a face to a back, and open eyes to shut ones, only when there is a choice", () => {
@@ -35,4 +35,30 @@ describe("sequence choice", () => {
expect(weights[0]!).toBeLessThan(weights[1]!);
expect(weights[0]!).toBeLessThan(weights[2]!);
});
it("keeps the open eyes even when that frame is the softer one", () => {
const frames = [
{ id: "blink", score: 9 },
{ id: "open", score: 4 },
];
const weights = sequenceWeight([
{ facing: 1, eyes: 0.2 },
{ facing: 1, eyes: 0.8 },
]);
const pool = rankForPick(frames, weights, (frame) => frame.score >= 8);
expect(pool.map((frame) => frame.id)).toEqual(["open"]);
});
it("keeps the sharpest frame when the eyes cannot be told apart", () => {
const frames = [
{ id: "a", score: 3 },
{ id: "b", score: 9 },
];
const weights = sequenceWeight([
{ facing: 1, eyes: null },
{ facing: 1, eyes: null },
]);
const pool = rankForPick(frames, weights, (frame) => frame.score >= 8);
expect(pool.map((frame) => frame.id)).toEqual(["b"]);
});
});
+3 -40
View File
@@ -2,47 +2,10 @@ import { MIN_SHARPNESS } from "../faces/math.js";
import type { Db } from "../db.js";
import { eyeOpennessAt } from "../composition/eyes.js";
import { groupBursts } from "./bursts.js";
import { sequenceWeight, type SequenceLook } from "./sequenceScore.js";
/**
* Which frame of a sequence to keep (docs/photo-editing-rules.md §3). A player from behind loses to a frame
* where the face is visible, and shut eyes lose to open ones, when the difference is clear. If every frame is
* a back, or the eyes cannot be told apart, nothing changes.
*
* Open eyes always beat shut ones when both are measured in the same burst — even on a shot or a grimace.
* A clear face always beats a back when the burst has both.
*/
export interface SequenceLook {
/** 1: a face on the subject. 0: the subject was seen and has no face (a back). null: not analysed yet. */
facing: 0 | 1 | null;
/** Higher means the eyes look more open. null: not measured. */
eyes: number | null;
}
/** Below this, eyes count as shut when another frame in the burst is clearly more open. */
const EYES_SHUT = 0.45;
/** At or above this, eyes count as open enough to prefer over a blink. */
const EYES_OPEN = 0.55;
/** Minimum gap between best and this frame before a blink penalty applies. */
const EYES_GAP = 0.08;
export function sequenceWeight(frames: readonly SequenceLook[], reportage = false): number[] {
const front = frames.some((f) => f.facing === 1);
const known = frames.map((f) => f.eyes).filter((v): v is number => v !== null);
const best = known.length ? Math.max(...known) : 0;
const hasOpen = known.some((v) => v >= EYES_OPEN);
// A blink loses hard whenever the burst has a clearer open-eye frame. Match and reportage both refuse it.
const shut = reportage ? 0.05 : 0.08;
return frames.map((f) => {
let w = 1;
if (front && f.facing === 0) w *= 0.05;
if (f.eyes === null || !known.length) return w;
const gap = best - f.eyes;
const clearlyShut = hasOpen && f.eyes < EYES_SHUT && gap >= EYES_GAP;
const relativelyShut = gap >= EYES_GAP && f.eyes < best * 0.85;
if (clearlyShut || relativelyShut) w *= shut;
return w;
});
}
export { rankForPick, sequenceWeight } from "./sequenceScore.js";
export type { SequenceLook } from "./sequenceScore.js";
interface Box {
x0: number;
+57
View File
@@ -0,0 +1,57 @@
/**
* Which frame of a sequence to keep when the eyes can be compared (docs/photo-editing-rules.md §3).
* Pure: the desktop and the server both call this. Shut eyes lose when the burst has an open pair.
*/
export interface SequenceLook {
/** 1: a face on the subject. 0: the subject was seen and has no face (a back). null: not analysed yet. */
facing: 0 | 1 | null;
/** Higher means the eyes look more open. null: not measured. */
eyes: number | null;
}
/** Below this, eyes count as shut when another frame in the burst is clearly more open. */
const EYES_SHUT = 0.45;
/** At or above this, eyes count as open enough to prefer over a blink. */
const EYES_OPEN = 0.55;
/** Minimum gap between best and this frame before a blink penalty applies. */
const EYES_GAP = 0.08;
/** A frame under this is not a pick when the burst still has a frame at or above it. */
export const LOOK_KEEP = 0.25;
export function sequenceWeight(frames: readonly SequenceLook[], reportage = false): number[] {
const front = frames.some((f) => f.facing === 1);
const known = frames.map((f) => f.eyes).filter((v): v is number => v !== null);
const best = known.length ? Math.max(...known) : 0;
const hasOpen = known.some((v) => v >= EYES_OPEN);
// A blink loses hard whenever the burst has a clearer open-eye frame. Match and reportage both refuse it.
const shut = reportage ? 0.05 : 0.08;
return frames.map((f) => {
let w = 1;
if (front && f.facing === 0) w *= 0.05;
if (f.eyes === null || !known.length) return w;
const gap = best - f.eyes;
const clearlyShut = hasOpen && f.eyes < EYES_SHUT && gap >= EYES_GAP;
const relativelyShut = gap >= EYES_GAP && f.eyes < best * 0.85;
if (clearlyShut || relativelyShut) w *= shut;
return w;
});
}
/**
* The frames a sequence may keep. A blink (or a back) drops out whenever another frame of the same burst
* is usable, even if the blink is sharper. Sharpness then ranks what remains. When the eyes were not
* measured, every frame stays and sharpness decides.
*/
export function rankForPick<T>(frames: readonly T[], weights: readonly number[], sharp: (frame: T) => boolean): T[] {
const kept: T[] = [];
for (let i = 0; i < frames.length; i++) {
const weight = weights[i] ?? 1;
if (weight >= LOOK_KEEP) kept.push(frames[i]!);
}
let base = [...frames];
if (kept.length > 0 && kept.length < frames.length) base = kept;
const sharpOnes = base.filter((frame) => sharp(frame));
if (sharpOnes.length > 0) return sharpOnes;
return base;
}
+68 -12
View File
@@ -1,11 +1,12 @@
import { existsSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { AutopilotSettings, type EditCommand } from "@photoreport/contracts";
import type { Db } from "../db.js";
import type { DeliveryService } from "../delivery/service.js";
import type { RenderEngine } from "../develop/engine.js";
import type { DevelopService } from "../develop/service.js";
import { type Box, frameScore, isReportage, peopleIn, sendBlockedByBall } from "../composition/compose.js";
import { type Box, frameScore, isReportage, lensHintFromExif, peopleIn, sendBlockedByBall } from "../composition/compose.js";
import type { SubjectDetector } from "../composition/detect.js";
import { cameraLevelAngle } from "../composition/cameraLevel.js";
import { planFrame, levelAngle, measuredValues } from "../composition/planFrame.js";
import { constrainRotated } from "../composition/geometry.js";
import type { IngestLogger } from "../ingest/service.js";
@@ -15,8 +16,16 @@ import type { LocalStorage } from "../storage/storage.js";
import { focusFromExifJson } from "../ingest/focus.js";
import { readFocusPoint } from "../ingest/exif.js";
import { assignBestRestExports, CANDIDATE_SELECT, candidatesOf } from "./best.js";
import { sequenceWeights } from "./sequence.js";
import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.js";
import { rankForPick, sequenceWeights } from "./sequence.js";
import {
bestOf,
FOCUS_SHARP,
groupBursts,
reportagePickCount,
SEQUENCE_PICK_GAP_MS,
sequenceIndex,
sequenceSendRoom,
} from "./bursts.js";
import { curate, matchMinutes } from "./curate.js";
import { type LearntStyle, learntStyle } from "./learning.js";
import { detailForCrop, lookValues } from "./look.js";
@@ -141,7 +150,16 @@ export class AutopilotService {
rawAngle = auto.angle;
values = measuredValues(auto.values, settings, photo.iso, style?.offsets ?? {});
}
const angle = levelAngle(rawAngle, settings.level);
// The sensor's roll beats the lines in the picture (a brick wall is not a horizon).
let cameraAngle: number | null = null;
if (settings.level) {
try {
cameraAngle = cameraLevelAngle(readFileSync(preview));
} catch {
cameraAngle = null;
}
}
const angle = cameraAngle !== null ? levelAngle(cameraAngle, true) : levelAngle(rawAngle, settings.level);
const load = this.deps.detector();
const detections = load ? await (await load).detect(preview) : null;
const focusFile = photo.originalStored ? storage.resolve(photo.storageKey) : preview;
@@ -166,6 +184,7 @@ export class AutopilotService {
cropFactor: style?.cropFactor ?? null,
cropBias: style?.cropBias ?? null,
sport: photo.event?.sport ?? null,
lens: lensHintFromExif(photo.exif, photo.focalLength, photo.lens),
settings,
});
const ops = planned.ops;
@@ -243,15 +262,48 @@ export class AutopilotService {
const need = picksNeeded(settings);
const asked = reportage ? reportagePickCount(sharp, need) : need;
const planKey = [null, "half", "threeQuarter"] as const;
// Drop backs / blinks when the burst has a clearer face with open eyes (look weight already crushed).
// Soft frames lose when the burst has a sharp sibling (FOCUS_SHARP).
const sharpEnough = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP);
const lookOk = (sharpEnough.length ? sharpEnough : burst).filter((f) => (look.get(f.id) ?? 1) >= 0.25);
const usable = lookOk.length ? lookOk : sharpEnough.length ? sharpEnough : burst;
const pool = usable;
// Open eyes win whenever the burst has a frame where they can be seen. A sharper blink does not.
// Among the frames that remain, a sharp one beats a soft one.
const weights = burst.map((f) => look.get(f.id) ?? 1);
const pool = rankForPick(burst, weights, (f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP);
// Extra frames beyond the event's number are only kept when they can carry a different plan.
// The plan stays with the frame: dropping one does not hand its crop to the next.
const chosen = bestOf(pool, asked)
// The panel number is how many similar pictures of one sequence are chosen. A slow run (a second
// between frames) is still that sequence. A frame that looks different may add another, up to four.
let take = asked;
if (!reportage) {
take = Math.min(asked, Math.max(0, settings.picksPerBurst));
}
const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
const sameCamera = frames
.filter((f) => f.camera === burst[0]!.camera && !burst.some((b) => b.id === f.id))
.map((f) => ({
atMs: (f.capturedAt ?? f.createdAt).getTime(),
picked: f.flag === "PICK",
look: {
subject: f.rec?.subject ?? null,
people: f.rec?.people ?? null,
reason: f.rec?.reason ?? null,
},
}));
const shotAt = [...sameCamera.map((frame) => frame.atMs), start];
const key = sequenceIndex(shotAt, start, SEQUENCE_PICK_GAP_MS);
const already = sameCamera.filter((frame) => {
if (!frame.picked) return false;
return sequenceIndex(shotAt, frame.atMs, SEQUENCE_PICK_GAP_MS) === key;
});
if (already.length > 0) {
const next = bestOf(pool, 1)[0];
const room = next
? sequenceSendRoom(settings.picksPerBurst, already.map((frame) => frame.look), {
subject: next.rec?.subject ?? null,
people: next.rec?.people ?? null,
reason: next.rec?.reason ?? null,
})
: 0;
take = Math.min(take, room);
}
const chosen = bestOf(pool, take)
.map((f, i) => ({ f, key: planKey[i] ?? null }))
.filter(({ f, key }, i) => {
if (!reportage || i < need) return true;
@@ -263,6 +315,9 @@ export class AutopilotService {
if (toFlag.length) {
await db.photo.updateMany({ where: { id: { in: toFlag } }, data: { flag: "PICK" } });
broadcaster.library(event.organizationId, { type: "photo.updated", ids: toFlag, patch: { flag: "PICK" } });
for (const frame of best) {
if (toFlag.includes(frame.id)) frame.flag = "PICK";
}
picked += toFlag.length;
}
// Apply the planned develop/crop only to the picks — never to the rest of the sequence.
@@ -385,6 +440,7 @@ export class AutopilotService {
durationMs: matchMinutes(event.sport) * 60_000,
now: now.getTime(),
minGapMs: MELHORES_GAP_MS,
sequenceCap: settings.picksPerBurst,
};
const decisions = curate(candidates, decided, {
count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount,
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { cameraLevelAngle } from "./cameraLevel.js";
/**
* A tiny JPEG laid out like a Canon file: IFD0 points at the Exif IFD, and that IFD
* holds the maker note. LevelInfo says the camera rolled clockwise by `clockwise` degrees.
*/
function jpegWithRoll(clockwise: number): ArrayBuffer {
const raw = Math.round(-clockwise * 10);
const tiff = new Uint8Array(94);
const view = new DataView(tiff.buffer);
view.setUint16(0, 0x4949, true);
view.setUint16(2, 42, true);
view.setUint32(4, 8, true);
view.setUint16(8, 1, true);
view.setUint16(10, 0x8769, true);
view.setUint16(12, 4, true);
view.setUint32(14, 1, true);
view.setUint32(18, 26, true);
view.setUint16(26, 1, true);
view.setUint16(28, 0x927c, true);
view.setUint16(30, 7, true);
view.setUint32(32, 50, true);
view.setUint32(36, 44, true);
view.setUint16(44, 1, true);
view.setUint16(46, 0x4059, true);
view.setUint16(48, 7, true);
view.setUint32(50, 32, true);
view.setUint32(54, 62, true);
view.setInt32(62 + 12, raw, true);
view.setInt32(62 + 16, 0, true);
const app = new Uint8Array(2 + 2 + 6 + tiff.length);
const out = new DataView(app.buffer);
out.setUint16(0, 0xffe1);
out.setUint16(2, app.length - 2);
app.set([0x45, 0x78, 0x69, 0x66, 0, 0], 4);
app.set(tiff, 10);
const jpeg = new Uint8Array(2 + app.length + 2);
jpeg[0] = 0xff;
jpeg[1] = 0xd8;
jpeg.set(app, 2);
jpeg[jpeg.length - 2] = 0xff;
jpeg[jpeg.length - 1] = 0xd9;
return jpeg.buffer;
}
describe("camera level", () => {
it("turns a clockwise Canon roll into the crop angle that cancels it", () => {
expect(cameraLevelAngle(jpegWithRoll(1.5))).toBe(-1.5);
});
it("keeps a level camera level, so a wall cannot tilt the frame", () => {
expect(cameraLevelAngle(jpegWithRoll(0))).toBe(0);
});
it("ignores a portrait roll and a file with no level", () => {
expect(cameraLevelAngle(jpegWithRoll(90))).toBeNull();
expect(cameraLevelAngle(new Uint8Array([0xff, 0xd8, 0xff, 0xd9]).buffer)).toBeNull();
});
});
+106
View File
@@ -0,0 +1,106 @@
/**
* The camera's own level, when the file still has it.
* Some Canon bodies (EOS R5 from firmware 1.5, and others) write LevelInfo in the maker note:
* roll and pitch from the sensor, the same numbers as the electronic level in the viewfinder.
* The maker note sits in the Exif IFD, not in IFD0. The EOS R1 JPEG does not write this tag,
* and Nikon keeps its roll inside an encrypted block, so those stay with the line-based level.
*
* The returned number is the crop angle (LightCraft's sign): it cancels a clockwise roll.
* 0 means the camera was level. Null means the file has no usable roll.
*/
const MAX_ROLL = 8;
export function cameraLevelAngle(bytes: ArrayBuffer | ArrayBufferView): number | null {
const view = bytes instanceof ArrayBuffer ? new DataView(bytes) : new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (view.byteLength < 4 || view.getUint16(0) !== 0xffd8) return null;
let off = 2;
while (off + 4 <= view.byteLength) {
const marker = view.getUint16(off);
const size = view.getUint16(off + 2);
if (marker === 0xffe1 && off + 10 <= view.byteLength && view.getUint32(off + 4) === 0x45786966) {
return canonRoll(view, off + 10, off + 2 + size);
}
if ((marker & 0xff00) !== 0xff00 || marker === 0xffda) return null;
off += 2 + size;
}
return null;
}
function canonRoll(view: DataView, tiff: number, end: number): number | null {
if (tiff + 8 > end) return null;
const little = view.getUint16(tiff) === 0x4949;
const ifd0 = view.getUint32(tiff + 4, little);
const maker = makerNote(view, tiff, end, little, ifd0);
if (!maker) return null;
let note = tiff + maker.offset;
if (note + 8 > end) return null;
const head = String.fromCharCode(
view.getUint8(note),
view.getUint8(note + 1),
view.getUint8(note + 2),
view.getUint8(note + 3),
view.getUint8(note + 4),
);
if (head === "Canon") note += 8;
const level = entryValue(view, tiff, end, little, note - tiff, 0x4059);
if (!level || level.count < 20) return null;
let blob = tiff + level.offset;
if (blob + 20 > end) blob = note + level.offset;
if (blob + 20 > end) return null;
// Entry 4 is roll, entry 5 is pitch. The table counts from 1.
const rollRaw = view.getInt32(blob + 3 * 4, little);
const pitchRaw = view.getInt32(blob + 4 * 4, little);
const pitch = canonDegrees(pitchRaw, false);
const clockwise = canonDegrees(rollRaw, true);
if (pitch === null || clockwise === null) return null;
if (Math.abs(pitch) > 90) return null;
if (Math.abs(clockwise) > MAX_ROLL) return null;
return Math.round(-clockwise * 100) / 100;
}
function canonDegrees(raw: number, negate: boolean): number | null {
let v = raw;
if (v > 1800) v -= 3600;
if (v < -1800) v += 3600;
const degrees = (negate ? -v : v) / 10;
if (!Number.isFinite(degrees) || Math.abs(degrees) > 180) return null;
return degrees;
}
/** MakerNote is usually inside the Exif IFD (tag 0x8769). A few files put it straight on IFD0. */
function makerNote(
view: DataView,
tiff: number,
end: number,
little: boolean,
ifd0: number,
): { offset: number; count: number } | null {
const direct = entryValue(view, tiff, end, little, ifd0, 0x927c);
if (direct) return direct;
const exif = entryValue(view, tiff, end, little, ifd0, 0x8769);
if (!exif) return null;
return entryValue(view, tiff, end, little, exif.offset, 0x927c);
}
function entryValue(
view: DataView,
tiff: number,
end: number,
little: boolean,
ifd: number,
tag: number,
): { offset: number; count: number } | null {
if (ifd <= 0 || tiff + ifd + 2 > end) return null;
const n = view.getUint16(tiff + ifd, little);
if (n > 80) return null;
for (let i = 0; i < n; i++) {
const e = ifd + 2 + i * 12;
if (tiff + e + 12 > end) return null;
if (view.getUint16(tiff + e, little) !== tag) continue;
const count = view.getUint32(tiff + e + 4, little);
const value = view.getUint32(tiff + e + 8, little);
return { offset: value, count };
}
return null;
}
+203 -17
View File
@@ -14,10 +14,12 @@
* stays whole when that person stays in the crop. A crop that slices a ball is not a crop.
* - An open frame with a team in it stays open: the row is the subject, and the crop does not drop people out of it.
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
* - A generic event, and any photo with no ball, is reportage: a whole hand and a whole foot stay in. When the
* foot already leaves the photo, the crop ends mid-shin or mid-thigh, never on the sock. A person the frame
* has already cut in half stays out. A stray hand or foot of someone else is cropped out. A head in a window
* or a torso does not beat a whole figure, and a crop never slices someone who is in it.
* - A generic event is reportage. The crop reads the shot the way a picture editor does, and trusts the
* framing: a long shot is the place, a full-length or a group whose bodies are whole stays as it was made,
* and a frame the camera already closed is only finished (mid-limb, a person already cut off at the edge
* left out). It is not zoomed to a sports fill. The space left around someone was left on purpose.
* A prime of 100mm or longer may step one notch closer on a single full-length, because it cannot zoom.
* A long shot and a group stay. That step stays centred on the photograph.
* - "tight" is the agencies' handball look, and only with a ball in play: the subject fills the height, cut
* mid-shin or mid-thigh when the foot is already out. "full" keeps whole bodies when they fit.
*
@@ -126,6 +128,23 @@ const HAND_PAD = 0.12;
/** How many similar people, across how much of the frame, make an open plan rather than one player's photo. */
const OPEN_PEOPLE = 4;
const OPEN_SPAN = 0.45;
/**
* A person under half the picture is a long shot: the place is what was photographed.
* The same line picture editors draw between a long shot and a full-length.
*/
const LONG_SHOT = 0.5;
/**
* A prime at least this long cannot zoom. On one full-length the crop may come in to PRIME_STEP,
* the zoom the lens could not make. Shorter primes and zooms stay with the frame as shot.
*/
const LONG_PRIME_MM = 100;
/** One step in from the photograph. Not the sports fill: the same picture, a little closer. */
const PRIME_STEP = 0.85;
/**
* Among reportage crops of the same size, a slight pull toward the subject.
* Smaller than one step of the size search (0.025), so it never closes a frame to centre it.
*/
const FRAME_TIE = 0.02;
/** Tight framing: the subject's tallest body about this many crop heights (a little cut at the bottom). */
export const TIGHT = { fillAt: 1.05, wFill: 2.2, chestAt: 0.34, headMax: 0.2 };
@@ -149,6 +168,52 @@ export interface ComposeOptions {
* the photo. A sport that plays the ball on the ground (football) keeps the ball at the feet.
*/
sport?: string | null;
/**
* The lens that made the frame. A long prime may step closer on a single full-length.
* A zoom, or an unknown lens, does not: the photographer could have zoomed, so the space is the picture.
*/
lens?: LensHint | null;
}
/** What the file says about the lens. `range` equal at both ends is a prime. */
export interface LensHint {
focalLength?: number | null;
range?: readonly [number, number] | null;
name?: string | null;
}
/** Focal length, lens name and the EXIF lens range stored on a photo. */
export function lensHintFromExif(exif: unknown, focalLength: number | null, name: string | null): LensHint {
let range: [number, number] | null = null;
if (exif && typeof exif === "object" && "lensRange" in exif) {
const raw = (exif as { lensRange?: unknown }).lensRange;
if (Array.isArray(raw) && raw.length >= 2) {
const min = raw[0];
const max = raw[1];
if (typeof min === "number" && typeof max === "number" && Number.isFinite(min) && Number.isFinite(max)) {
range = [min, max];
}
}
}
return { focalLength, range, name };
}
/**
* A prime of 100mm or more. The photographer could not zoom in. A 70-200 at 135mm is not this:
* that lens still had room. Unknown lens: not this either.
*/
export function isLongPrime(lens: LensHint | null | undefined): boolean {
if (!lens) return false;
const focal = lens.focalLength;
if (focal == null || !Number.isFinite(focal) || focal < LONG_PRIME_MM) return false;
const range = lens.range;
if (range && range[0] > 0 && range[1] > 0) {
return Math.abs(range[0] - range[1]) < 1;
}
const name = lens.name ?? "";
if (/\d+\s*-\s*\d+/.test(name)) return false;
if (/\d+\s*mm/i.test(name)) return true;
return false;
}
/** A generic event: no opponent and no fixture. The crop is a person, not a match. */
@@ -179,6 +244,49 @@ const sharp = (p: Detection) => p.sharpness ?? 1;
/** A hand at the frame edge, not a person standing in the row. */
const sliver = (p: Detection) => h(p) < 0.12 || (atEdge(p) && w(p) < 0.07);
/** What the photograph already is. The photographer framed it; the size of the person is the plan. */
export type ShotIntent = "scene" | "figure" | "group" | "closed";
/**
* The plan a picture editor would name from the frame alone.
* A long shot is the place. A full-length or a group is finished when the bodies are whole.
* Closed means the camera already cut the body: the feet leave the picture and the person is large.
*/
export function shotIntent(subject: readonly Detection[]): ShotIntent | null {
const usable = subject.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT && !p.fragment && !sliver(p));
if (usable.length === 0) return null;
const tallestPerson = usable.reduce((a, b) => (h(b) > h(a) ? b : a));
if (h(tallestPerson) < LONG_SHOT) return "scene";
const feetCut = usable.some((p) => p.y1 >= FEET_IN_FRAME);
if (feetCut) return "closed";
if (usable.length >= 2) return "group";
return "figure";
}
/** Someone the camera already left out: cut by the frame edge, and not a stray hand or foot. */
function edgeAccident(p: Detection, tallest: number): boolean {
if (!atEdge(p)) return false;
if (sliver(p)) return false;
if (strayLimb(p, tallest)) return false;
return true;
}
/**
* Reportage: the frame is the photograph. True when closing it would throw away a plan the camera finished.
* A person already cut off at the edge of a full-length is the exception: they are not the picture.
*/
function framedOnPurpose(inSubject: Detection[], others: Detection[]): boolean {
const intent = shotIntent(inSubject);
if (!intent) return false;
if (intent === "closed") return false;
if (intent === "scene") return true;
const tallest = Math.max(...inSubject.map(h));
for (const p of others) {
if (edgeAccident(p, tallest)) return false;
}
return true;
}
/**
* The hands of a narrow standing figure sit outside the torso box. A wide box already has the arms in it
* (someone leaning), so it is left alone.
@@ -308,7 +416,9 @@ export function findSubject(
// middle. A sport that plays the ball on the ground keeps the one on the person, then the nearest.
const handball = isHandball(opts?.sport);
const balls = d.balls.filter((b) => b.score >= MIN_BALL && w(b) < 0.6 * h(main) && w(b) > 0.02 * h(main));
const near = balls.filter((b) => Math.abs(cx(b) - cx(main)) <= w(main) / 2 + 0.5 * h(main) && cy(b) > main.y0 - 0.4 * h(main) && cy(b) < main.y1 + 0.1 * h(main));
// An outstretched arm holds the ball well outside the torso box. Half a body is not enough.
const arm = handball ? 0.9 * h(main) : 0.5 * h(main);
const near = balls.filter((b) => Math.abs(cx(b) - cx(main)) <= w(main) / 2 + arm && cy(b) > main.y0 - 0.4 * h(main) && cy(b) < main.y1 + 0.1 * h(main));
const onTheFloor = (x: Box) => (cy(x) - main.y0) / Math.max(h(main), 1e-6) >= 0.74;
const playing = handball ? near.filter((b) => !onTheFloor(b)) : near;
const ball = playing.sort((a, b) => {
@@ -369,12 +479,17 @@ function personAtFocus(people: Detection[], focus: FocusHint): Detection | null
export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null {
const reportage = opts.context === "reportage";
const faces = opts.faces ?? [];
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
const detected = reportage ? forReportage(d, faces) : d;
const found = findSubject(detected, opts.focus, { reportage, sport: opts.sport ?? null, faces });
if (!found) return null;
const { box: s, reason, people: inSubject, ball } = found;
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions
const tallest = Math.max(...inSubject.map(h));
const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
const others = detected.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
// A long shot, a full-length, or a group the camera already finished. The margins are the picture.
// A long prime is the exception on one full-length: the lens could not zoom, so one step closer is allowed.
const primeFigure = reportage && isLongPrime(opts.lens) && shotIntent(inSubject) === "figure";
if (reportage && framedOnPurpose(inSubject, others) && !primeFigure) return null;
const headroom = 0.04 * tallest;
const minWidth = opts.minWidth ?? 0;
const balls = d.balls.filter((b) => b.score >= MIN_BALL);
@@ -398,11 +513,12 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
if (opts.framing === "tight" && !personStory) {
// Feet that are whole in the photo stay in. Cutting the leg is not how a tight frame is made.
if (feetIn) {
// Headroom gives way before a complete foot does.
// Headroom gives way before a complete foot does. If the players do not fit in a tighter frame, the
// photograph stays: cutting the legs is not the way out.
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, true, false, false, balls)
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls)
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls);
if (whole) return finish(whole);
return finish(whole);
}
// The foot already leaves the photo: end mid-shin or mid-thigh, not on the sock.
const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, true, false, ball, balls);
@@ -415,9 +531,9 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
if (cut) return finish(cut);
}
// Whole bodies, feet included. A little headroom gives way before a complete foot does.
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls)
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls)
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls);
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure)
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure)
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure);
if (whole || feetIn) return finish(whole);
return finish(frame(s, ratio, s.y0 + MID_THIGH * tallest, headroom, tallest, others, inSubject, reason, minWidth, false, true, reportage, balls));
}
@@ -457,7 +573,7 @@ export function minCropWidth(width: number, height: number, minLongEdge = 2400):
return Math.min(1, Math.max(floor, minLongEdge / long) * (width >= height ? 1 : height / width));
}
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false, pinBottom = false, reportage = false, balls: readonly Box[] = []): (Composition & { cost: number }) | null {
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false, pinBottom = false, reportage = false, balls: readonly Box[] = [], closer = false): (Composition & { cost: number }) | null {
const mainSharp = Math.max(...inSubject.map(sharp));
const keep = requiredBox(s, inSubject);
let best: { rect: Box; cost: number } | null = null;
@@ -493,7 +609,12 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
// Reportage: a person who is in the crop is in whole. A plan may end at the waist; it may not take the head
// off, and it may not cut someone down the side. The primary crop keeps their feet too.
if (reportage && slicesOther(r, others, mainSharp, tallest, pinBottom)) continue;
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight) + jointCost(r, inSubject, others, mainSharp);
if (reportage && overlapsStray(r, others, tallest)) continue;
if (reportage && overlapsEdgeCut(r, others, tallest)) continue;
// A player the photographer left in the picture stays in it. Cutting them out, or through the body,
// is not a crop. A sliver, a blurred figure and someone the frame already cut off may still go.
if (dropsPlayer(r, others, mainSharp, tallest)) continue;
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight, reportage, closer) + jointCost(r, inSubject, others, mainSharp);
if (!best || c < best.cost) best = { rect: r, cost: c };
}
}
@@ -502,7 +623,7 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
return { rect: best.rect, subject: s, reason, people: inSubject.length, cost: best.cost };
}
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[], tight = false): number {
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[], tight = false, trustFrame = false, closer = false): number {
let c = 0;
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
for (const p of others) {
@@ -519,6 +640,18 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
const size = Math.min(1, h(p) / tallest);
c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f));
}
if (trustFrame) {
// The photograph as shot. A long prime may take one step in, still centred on the same picture.
const scale = Math.max(ch, w(r) / ratio);
let target = 1;
if (closer) target = PRIME_STEP;
c += Math.abs(scale - target);
let anchor = cx(s);
if (closer) anchor = 0.5;
const offCentre = Math.abs(anchor - cx(r)) / Math.max(w(r), 1e-6);
c += FRAME_TIE * offCentre;
return c;
}
if (tight) {
// The agencies' framing: the subject as tall as the crop (or a little taller, legs cut mid-limb).
c += TIGHT.wFill * Math.abs(tallest / ch - TIGHT.fillAt);
@@ -635,6 +768,40 @@ function cutsHead(r: Box, people: Detection[], tallest: number): boolean {
* Someone the crop keeps a piece of, but not as a photograph would. In, or out: never a slice through the body,
* never the body without the head. A deliberate half or three-quarter (allowLegs) may end at the waist.
*/
/**
* A player who is clearly in the photograph: large in the frame, or nearly as tall as the subject.
* Not a distant figure, not a hand at the edge.
*/
function prominentPlayer(p: Detection, tallest: number): boolean {
if (sliver(p) || strayLimb(p, tallest)) return false;
if (h(p) >= 0.42) return true;
if (h(p) >= 0.28 && h(p) >= 0.72 * tallest) return true;
return false;
}
/**
* The crop throws a player out or cuts through them. A prominent player has to stay whole.
* A smaller one may be left out, but not sliced.
*/
function dropsPlayer(r: Box, others: Detection[], mainSharp: number, tallest: number): boolean {
for (const p of others) {
if (sliver(p) || strayLimb(p, tallest)) continue;
if (sharp(p) < 0.45 * mainSharp) continue;
if (edgeAccident(p, tallest)) continue;
const share = overlap(r, p) / Math.max(area(p), 1e-9);
const widthIn = Math.max(0, Math.min(r.x1, p.x1) - Math.max(r.x0, p.x0)) / Math.max(w(p), 1e-9);
if (prominentPlayer(p, tallest)) {
if (share < 0.9) return true;
if (r.y0 > p.y0 + 0.04 * h(p)) return true;
if (p.y1 < FEET_IN_FRAME && r.y1 < p.y1 - 0.05 * h(p)) return true;
continue;
}
if (share > 0.08 && share < 0.9) return true;
if (widthIn > 0.15 && widthIn < 0.88) return true;
}
return false;
}
function slicesOther(r: Box, others: Detection[], mainSharp: number, subjectTallest: number, allowLegs: boolean): boolean {
const tallest = Math.max(subjectTallest, 0, ...others.map(h));
for (const p of others) {
@@ -654,6 +821,24 @@ function strayLimb(p: Detection, tallest: number): boolean {
return p.x0 < 0.02 || p.x1 > 0.98 || p.y0 < 0.02 || p.y1 > 0.98;
}
function overlapsStray(r: Box, others: Detection[], tallest: number): boolean {
for (const p of others) {
if (!strayLimb(p, tallest)) continue;
const share = overlap(r, p) / Math.max(area(p), 1e-9);
if (share > 0.02) return true;
}
return false;
}
function overlapsEdgeCut(r: Box, others: Detection[], tallest: number): boolean {
for (const p of others) {
if (!edgeAccident(p, tallest)) continue;
const share = overlap(r, p) / Math.max(area(p), 1e-9);
if (share > 0.05) return true;
}
return false;
}
/**
* Where a sequence plan may end on this person, measured on their own box. A line taken from the top of the
* group lands on the neck of whoever stands lower. The hands stay: at the hip on a standing figure, and at the
@@ -677,7 +862,8 @@ function planCut(p: Detection, at: number): number | null {
export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: number | null = null, opts: ComposeOptions = {}): Box | null {
const reportage = opts.context === "reportage";
const faces = opts.faces ?? [];
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
const detected = reportage ? forReportage(d, faces) : d;
const found = findSubject(detected, opts.focus, { reportage, sport: opts.sport ?? null, faces });
if (!found) return null;
const { box: s, reason, people: inSubject } = found;
// A lineup is one photograph. A half or a three-quarter of it would cut the row.
@@ -689,7 +875,7 @@ export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: numbe
if (lines.some((line) => line === null)) return null;
const bottom = Math.max(...(lines as number[]));
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width);
const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
const others = detected.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
const balls = d.balls.filter((b) => b.score >= MIN_BALL);
const made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true, reportage, balls);
if (!made) return null;
+34
View File
@@ -0,0 +1,34 @@
/**
* How open the eyes look in a greyscale crop of a face (0 shut, higher open). A shut eye is a horizontal lid:
* the grey changes down the crop and barely across it. An open eye has a round pupil, so it changes both ways.
* Only useful compared with the other frames of the same sequence. No image library: the desktop can run this.
*/
export function eyeOpenness(grey: Uint8Array, width: number, height: number): number | null {
if (width < 12 || height < 8) return null;
const left = region(grey, width, height, 0.12, 0.42);
const right = region(grey, width, height, 0.58, 0.88);
const scores = [left, right].filter((s): s is number => s !== null);
if (!scores.length) return null;
return scores.reduce((a, b) => a + b, 0) / scores.length;
}
function region(grey: Uint8Array, width: number, height: number, x0f: number, x1f: number): number | null {
const x0 = Math.max(1, Math.floor(width * x0f));
const x1 = Math.min(width - 1, Math.ceil(width * x1f));
const y0 = Math.max(1, Math.floor(height * 0.15));
const y1 = Math.min(height - 1, Math.ceil(height * 0.85));
if (x1 - x0 < 4 || y1 - y0 < 4) return null;
let across = 0;
let down = 0;
let n = 0;
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
const i = y * width + x;
across += Math.abs((grey[i + 1] ?? 0) - (grey[i - 1] ?? 0));
down += Math.abs((grey[i + width] ?? 0) - (grey[i - width] ?? 0));
n++;
}
}
if (!n || down < 1) return null;
return across / down;
}
+2 -34
View File
@@ -1,39 +1,7 @@
import sharp from "sharp";
import { eyeOpenness } from "./eyeScore.js";
/**
* How open the eyes look in a greyscale crop of a face (0 shut, higher open). A shut eye is a horizontal lid:
* the grey changes down the crop and barely across it. An open eye has a round pupil, so it changes both ways.
* Only useful compared with the other frames of the same sequence.
*/
export function eyeOpenness(grey: Uint8Array, width: number, height: number): number | null {
if (width < 12 || height < 8) return null;
const left = region(grey, width, height, 0.12, 0.42);
const right = region(grey, width, height, 0.58, 0.88);
const scores = [left, right].filter((s): s is number => s !== null);
if (!scores.length) return null;
return scores.reduce((a, b) => a + b, 0) / scores.length;
}
function region(grey: Uint8Array, width: number, height: number, x0f: number, x1f: number): number | null {
const x0 = Math.max(1, Math.floor(width * x0f));
const x1 = Math.min(width - 1, Math.ceil(width * x1f));
const y0 = Math.max(1, Math.floor(height * 0.15));
const y1 = Math.min(height - 1, Math.ceil(height * 0.85));
if (x1 - x0 < 4 || y1 - y0 < 4) return null;
let across = 0;
let down = 0;
let n = 0;
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
const i = y * width + x;
across += Math.abs((grey[i + 1] ?? 0) - (grey[i - 1] ?? 0));
down += Math.abs((grey[i + width] ?? 0) - (grey[i - width] ?? 0));
n++;
}
}
if (!n || down < 1) return null;
return across / down;
}
export { eyeOpenness } from "./eyeScore.js";
/** The upper part of one face, from the upright preview, reduced to a small grey crop. */
export async function eyeOpennessAt(file: string, face: { x0: number; y0: number; x1: number; y1: number }): Promise<number | null> {
@@ -46,4 +46,65 @@ describe("planFrame", () => {
expect(ratio).toBeCloseTo(6000 / 4000, 2);
expect(crop.params.aspect).toEqual([6000, 4000]);
});
it("does not close a reportage frame the camera left open, even when matches are cropped tight", () => {
const planned = planFrame({
detections: {
width: 6000,
height: 4000,
people: [{ x0: 0.35, y0: 0.28, x1: 0.52, y1: 0.72, score: 0.9, sharpness: 1 }],
balls: [],
},
width: 6000,
height: 4000,
reportage: true,
values: null,
angle: 0,
cropBias: { dx: 0, dy: 0, scale: 0.8, dAngle: 0, cut: 0.5, head: 0.02, sides: 0.1 },
settings,
});
expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false);
});
it("does not apply a learnt cut that chops a player the crop had kept", () => {
const planned = planFrame({
detections: {
width: 6000,
height: 4000,
people: [{ x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.9, score: 0.9, sharpness: 1 }],
balls: [],
},
width: 6000,
height: 4000,
reportage: false,
values: null,
angle: 0,
cropBias: { dx: 0, dy: 0, scale: 0.8, dAngle: 0, cut: 0.45, head: 0.02, sides: 0.15 },
settings,
});
const crop = planned.ops.find((op) => op.command === "crop.set");
if (!crop || crop.command !== "crop.set") return;
expect(crop.params.rect.y1).toBeGreaterThan(0.88);
expect(crop.params.rect.y0).toBeLessThanOrEqual(0.16);
expect(crop.params.rect.x0).toBeLessThanOrEqual(0.4);
expect(crop.params.rect.x1).toBeGreaterThanOrEqual(0.62);
});
it("does not close a reportage full-length the camera already composed", () => {
const planned = planFrame({
detections: {
width: 6000,
height: 4000,
people: [{ x0: 0.3, y0: 0.12, x1: 0.48, y1: 0.82, score: 0.9, sharpness: 1 }],
balls: [],
},
width: 6000,
height: 4000,
reportage: true,
values: null,
angle: 0,
settings,
});
expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false);
});
});
+50 -8
View File
@@ -1,5 +1,5 @@
import type { EditCommand } from "@photoreport/contracts";
import { type Box, type Detections, type FocusHint, clipsBall, compose, minCropWidth, planCrop } from "./compose.js";
import { type Box, type Detections, type FocusHint, type LensHint, clipsBall, compose, minCropWidth, planCrop } from "./compose.js";
import { biasCrop, constrainRotated, frameOnSubject, keepPhotoAspect, tighter } from "./geometry.js";
import { type Look, WB_KEYS, TONE_KEYS, detailForCrop, lookValues, toneApplied } from "../autopilot/look.js";
import type { CropBias } from "../autopilot/cropBias.js";
@@ -10,6 +10,33 @@ const MIN_LEVEL = 0.25;
/** A crop this close to the whole frame is not worth making. */
const KEEP_WHOLE = 0.92;
/** The crop no longer contains the ball that was in play. Leaving it outside is the same as cutting it. */
function losesBall(rect: Box | null, ball: Box | null | undefined): boolean {
if (!rect || !ball) return false;
if (rect.x0 > ball.x0 + 1e-4) return true;
if (rect.y0 > ball.y0 + 1e-4) return true;
if (rect.x1 < ball.x1 - 1e-4) return true;
if (rect.y1 < ball.y1 - 1e-4) return true;
return false;
}
/** The learnt cut would take off a head or the feet that the crop had kept. */
function chopsKeptPlayer(original: Box, placed: Box, subject: Box): boolean {
const hadHead = original.y0 <= subject.y0 + 0.03;
const keepsHead = placed.y0 <= subject.y0 + 0.03;
if (hadHead && !keepsHead) return true;
const hadFeet = original.y1 >= subject.y1 - 0.03;
const keepsFeet = placed.y1 >= subject.y1 - 0.03;
if (hadFeet && !keepsFeet) return true;
const hadLeft = original.x0 <= subject.x0 + 0.02;
const keepsLeft = placed.x0 <= subject.x0 + 0.02;
if (hadLeft && !keepsLeft) return true;
const hadRight = original.x1 >= subject.x1 - 0.02;
const keepsRight = placed.x1 >= subject.x1 - 0.02;
if (hadRight && !keepsRight) return true;
return false;
}
export interface PlanSettings {
crop: boolean;
tone: boolean;
@@ -79,6 +106,8 @@ export function planFrame(input: {
cropBias?: Omit<CropBias, "scene"> | null;
/** The event's sport. Handball does not frame on a ball that is sitting on the floor. */
sport?: string | null;
/** Prime versus zoom. A long prime may step closer on one full-length; the framing still names the shot. */
lens?: LensHint | null;
settings: PlanSettings;
}): PlannedFrame {
const { detections, settings, width: W, height: H, reportage } = input;
@@ -89,18 +118,28 @@ export function planFrame(input: {
const faces = input.faces ?? [];
const focus = input.focus ?? null;
const sport = input.sport ?? null;
const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces, sport }) : null;
const lens = input.lens ?? null;
const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces, sport, lens }) : null;
const wideComposition = detections && !reportage && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full", context: "sport", sport }) : null;
const plans = reportage && detections ? { half: planCrop(detections, "half", aspect, { minWidth, focus, context, faces }), threeQuarter: planCrop(detections, "threeQuarter", aspect, { minWidth, focus, context, faces }) } : null;
let crop: Box | null = null;
let angle = input.angle;
if (settings.crop && composition) {
let rect = composition.rect;
const bias = input.cropBias;
const factor = bias?.scale ?? input.cropFactor ?? null;
// Match corrections (a shorter body, a tighter frame) stay on matches. Reportage keeps the frame it planned.
let bias = input.cropBias ?? null;
let factor = input.cropFactor ?? null;
if (reportage) {
bias = null;
factor = null;
} else if (bias?.scale != null) {
factor = bias.scale;
}
if (bias && typeof bias.cut === "number") {
// The photographer's cut on the body (legs, head, arms), not a uniform shrink.
rect = frameOnSubject(composition.rect, composition.subject, bias);
// It must not chop a player this photograph had kept whole.
const placed = frameOnSubject(composition.rect, composition.subject, bias);
if (!chopsKeptPlayer(composition.rect, placed, composition.subject)) rect = placed;
if (bias.dx) {
const w = rect.x1 - rect.x0;
const x0 = Math.min(Math.max(0, rect.x0 + bias.dx), 1 - w);
@@ -112,10 +151,13 @@ export function planFrame(input: {
rect = factor < 1 ? tighter(composition.rect, composition.subject, factor) : biasCrop(composition.rect, composition.subject, { dx: 0, dy: 0, scale: factor });
}
if (bias?.dAngle) angle = Math.max(-MAX_LEVEL, Math.min(MAX_LEVEL, angle + bias.dAngle));
// A learnt crop must not slice a ball the frame had kept whole.
// A learnt crop must not slice a ball the frame had kept whole, or leave that ball outside.
const balls = detections?.balls ?? [];
if (clipsBall(rect, balls)) rect = composition.rect;
if (!clipsBall(rect, balls) && rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(keepPhotoAspect(rect), angle, W, H);
if (clipsBall(rect, balls) || losesBall(rect, composition.ball)) rect = composition.rect;
let shaped: Box | null = constrainRotated(keepPhotoAspect(rect), angle, W, H);
if (losesBall(shaped, composition.ball)) shaped = constrainRotated(keepPhotoAspect(composition.rect), angle, W, H);
if (losesBall(shaped, composition.ball)) shaped = null;
if (shaped && !clipsBall(shaped, balls) && shaped.x1 - shaped.x0 < KEEP_WHOLE) crop = shaped;
}
const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(keepPhotoAspect(wideComposition.rect), angle, W, H) : null;
if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
+24 -10
View File
@@ -1,7 +1,7 @@
import { createReadStream, existsSync } from "node:fs";
import { DeliveryBestRequest, DeliveryRequest } from "@photoreport/contracts";
import { bestOfEvent } from "../autopilot/best.js";
import { IptcTemplate, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata";
import { IptcTemplate, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder, buildVars, withEventDay } from "@photoreport/metadata";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
@@ -137,16 +137,30 @@ function localCopyOf(
/** Renders the templates against a sample event so a broken template is refused when saved, not at delivery. */
function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra: Record<string, string> = {}) {
const sample = {
...buildVars(
{ home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") },
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
"Fotógrafo",
),
...extra,
};
const startsAt = new Date("2026-09-23T19:00:00Z");
const built = buildVars(
{
home: "Casa",
away: "Fora",
venue: "Pavilhão",
city: "Cidade",
sport: "andebol",
competition: "Competição",
competitionCode: "C01",
round: "1",
matchNumber: "1",
startsAt,
},
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
"Fotógrafo",
);
const fileSample = { ...built, ...extra };
const folderSample = { ...withEventDay(built, startsAt), ...extra };
try {
return { folder: renderFolder(folderTemplate, sample), fileName: renderFileName(fileNameTemplate, sample, "IMG_0001.JPG") };
return {
folder: renderFolder(folderTemplate, folderSample),
fileName: renderFileName(fileNameTemplate, fileSample, "IMG_0001.JPG"),
};
} catch (err) {
if (err instanceof PathTemplateError) throw badRequest("invalid_template", err.message);
throw err;
+32 -2
View File
@@ -7,7 +7,9 @@ import {
LOCAL_COPY_FOLDER,
PathTemplateError,
renderFileName,
folderDay,
renderFolder,
withEventDay,
} from "@photoreport/metadata";
import type { Db } from "../db.js";
import type { DeliveryItem, DeliveryTarget } from "../generated/prisma/client.js";
@@ -167,6 +169,13 @@ export interface DeliveryDeps {
originals?: { downloadOriginal(photoId: string): Promise<{ file: string; done: () => Promise<void> } | null> } | undefined;
}
/** A match has two sides or a fixture. Those stay on the kickoff day. */
function eventIsMatch(event: { away: string; fixtureId: string | null }): boolean {
if (event.fixtureId) return true;
if (event.away.trim().length > 0) return true;
return false;
}
/**
* Delivery queue: editors pick photos and a target; every photo is rendered (4000 px, IPTC) and uploaded on its
* own, with retries. The {n} in file names is fixed when the photo is queued, in capture order, so names never
@@ -564,7 +573,19 @@ export class DeliveryService {
const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null));
const vars = buildVars(eventInfoOf(item.event), photoInfoOf({ ...item.photo, exif }, { sequence: item.sequence }), item.photo.uploader?.name, { iptc: iptc?.values });
const named = sameExport && viaTarget ? { ...vars, destination: viaTarget.name } : vars;
let folder = renderFolder(sameExport && viaTarget ? viaTarget.localFolderTemplate || LOCAL_COPY_FOLDER : item.target.folderTemplate, named);
let folderNamed = named;
if (item.event) {
const day = folderDay(
{
startsAt: item.event.startsAt,
endsAt: item.event.ingestUntil,
match: eventIsMatch(item.event),
},
new Date(),
);
folderNamed = withEventDay(named, day);
}
let folder = renderFolder(sameExport && viaTarget ? viaTarget.localFolderTemplate || LOCAL_COPY_FOLDER : item.target.folderTemplate, folderNamed);
if (!sameExport && item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
// {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file).
// Untouched: the camera's own name, as a local FTP would have received it.
@@ -725,7 +746,16 @@ export class DeliveryService {
const target = await db.deliveryTarget.findFirst({ where: { id: targetId, organizationId } });
const event = await db.event.findFirst({ where: { id: eventId, organizationId } });
if (!target || !event) throw new DeliveryRejected("not_found");
const folder = renderFolder(target.folderTemplate, buildVars(eventInfoOf(event)));
const info = eventInfoOf(event);
const day = folderDay(
{
startsAt: info.startsAt,
endsAt: event.ingestUntil,
match: eventIsMatch(event),
},
new Date(),
);
const folder = renderFolder(target.folderTemplate, withEventDay(buildVars(info), day));
const client = this.client(target);
if (!client.shareLink) throw new DeliveryRejected("share_not_supported");
await client.ensureFolder(folder);
+9 -2
View File
@@ -423,7 +423,10 @@ export async function rosterOf(db: Db, eventId: string): Promise<string[] | null
return clubIds;
}
/** People with a face who match this season's sports_players on the given teams (federation id / birth+name / club name). */
/**
* People with a face on this season's squad for the given teams.
* The federation id only matches the same team, so a reserve side that copied the senior id stays out.
*/
async function peopleOnSquad(db: Db, organizationId: string, teamIds: string[], season: string): Promise<string[]> {
if (!teamIds.length) return [];
const rows = await db.$queryRaw<{ id: string }[]>`
@@ -438,7 +441,11 @@ async function peopleOnSquad(db: Db, organizationId: string, teamIds: string[],
AND squad.season = ${season}
AND (
squad.id = mine.id
OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id)
OR (
squad.external_id IS NOT NULL
AND squad.external_id = mine.external_id
AND squad.team_id = mine.team_id
)
OR (
squad.birth_date IS NOT NULL AND squad.full_name IS NOT NULL
AND mine.birth_date = squad.birth_date
+57 -29
View File
@@ -109,8 +109,9 @@ export class IngestService {
return { status: "skipped", reason: "unknown_login" };
}
// "Receber FTP aqui": pin is a preferred event for captures that still sit in its ingest window (and session).
// Outside that window the clock routes — a leftover pin on the afternoon training must not take the morning studio.
// "Receber FTP aqui": pin prefers this event. A shoot that runs past the window (extra time,
// penalties, the celebration) stays here while it is the same session. A later session follows the clock,
// so a pin left on from the afternoon does not take the next morning.
const target =
account.targetEventId && (!account.targetUntil || account.targetUntil > new Date())
? await db.event.findFirst({ where: { id: account.targetEventId, organizationId: account.organizationId, archivedAt: null }, select: { id: true } })
@@ -387,9 +388,10 @@ export class IngestService {
}
/**
* The event asked for on the upload (open library / desktop pin). Kept only while the capture sits in that
* event's ingest window and the photographer has not paused more than {@link INGEST_SESSION_GAP_MS} since
* their last photo there — otherwise the clock (or inbox) decides.
* The event asked for on the upload (open library, desktop pin, or "Receber FTP aqui"). Inside the ingest
* window it is kept while the photographer has not paused more than {@link INGEST_SESSION_GAP_MS}.
* Past the end of the window it is kept only as a continuation of that same session — extra time must not
* fall off an open pin, and a new session must not attach to it either.
*/
private async requestedEvent(
organizationId: string,
@@ -403,8 +405,11 @@ export class IngestService {
select: { ingestFrom: true, ingestUntil: true },
});
if (!event) return undefined;
if (at < event.ingestFrom || at > event.ingestUntil) return undefined;
if (!(await this.sameSession(requested, userId, at))) return undefined;
if (at < event.ingestFrom) return undefined;
const last = await this.lastCapture(requested, userId, at);
if (!withinIngestSession(at, last)) return undefined;
if (at <= event.ingestUntil) return requested;
if (!last) return undefined;
return requested;
}
@@ -433,8 +438,8 @@ export class IngestService {
return null;
}
/** Last capture by this photographer in the event; none yet → new session may start. */
private async sameSession(eventId: string, userId: string, at: Date): Promise<boolean> {
/** Last capture by this photographer in the event, strictly before `at`. */
private async lastCapture(eventId: string, userId: string, at: Date): Promise<Date | null> {
const last = await this.deps.db.photo.findFirst({
where: {
eventId,
@@ -444,7 +449,12 @@ export class IngestService {
orderBy: { capturedAt: "desc" },
select: { capturedAt: true },
});
return withinIngestSession(at, last?.capturedAt);
return last?.capturedAt ?? null;
}
/** None yet → a new session may start. A pause longer than {@link INGEST_SESSION_GAP_MS} starts another. */
private async sameSession(eventId: string, userId: string, at: Date): Promise<boolean> {
return withinIngestSession(at, await this.lastCapture(eventId, userId, at));
}
/**
@@ -497,35 +507,53 @@ export class IngestService {
}
/**
* Photos stored an hour early because the camera still writes +01:00 in winter. Re-read the stored file
* (the original, or the preview the desktop sent, which keeps the camera's clock) and, when it moves by
* that hour, put the capture time right and let the autopilot decide the frame again.
* Photos stored an hour early because an older read treated a summer offset (+01:00) as real in winter.
* Re-read the stored file and, when that hour is still missing after the login's own clock offset, put the
* capture time right and let the autopilot decide the frame again.
* The login offset is applied again here. Without it, a body set an hour back (clockOffsetSec -3600) is
* "repaired" forward and the offset the photographer saved is undone on every new photo.
*/
async backfillCaptureClock(limit = 100): Promise<number> {
const { db, storage, log } = this.deps;
const rows = await db.$queryRaw<
Array<{ id: string; storage_key: string; captured_at: Date | null; taken_at: Date; autopilot: unknown; exif: unknown }>
Array<{ id: string; storage_key: string; captured_at: Date | null; taken_at: Date; autopilot: unknown; exif: unknown; clock_offset_sec: number }>
>`
SELECT id, storage_key, captured_at, taken_at, autopilot, exif
FROM photos
WHERE status = 'READY'
AND created_at > now() - interval '3 days'
SELECT p.id, p.storage_key, p.captured_at, p.taken_at, p.autopilot, p.exif,
COALESCE((
SELECT CASE
WHEN COUNT(DISTINCT a.clock_offset_sec) = 1 THEN MIN(a.clock_offset_sec)
ELSE 0
END
FROM ftp_accounts a
WHERE a.user_id = p.uploader_id
AND a.organization_id = p.organization_id
), 0) AS clock_offset_sec
FROM photos p
WHERE p.status = 'READY'
AND p.created_at > now() - interval '3 days'
AND (
exif IS NULL
OR jsonb_typeof(exif::jsonb) <> 'object'
OR COALESCE((exif::jsonb->>'captureClockChecked')::boolean, false) IS NOT TRUE
p.exif IS NULL
OR jsonb_typeof(p.exif::jsonb) <> 'object'
OR COALESCE((p.exif::jsonb->>'captureClockChecked')::boolean, false) IS NOT TRUE
)
ORDER BY created_at DESC
ORDER BY p.created_at DESC
LIMIT ${limit}
`;
let fixed = 0;
for (const row of rows) {
const camera = await readCameraInfo(storage.resolve(row.storage_key)).catch(() => null);
const next = camera?.capturedAt ?? null;
const read = camera?.capturedAt ?? null;
const prev = row.captured_at ? new Date(row.captured_at).getTime() : null;
const hourOff = next && prev !== null && Math.abs(next.getTime() - prev - 3_600_000) < 2_000;
const offsetMs = Number(row.clock_offset_sec) * 1000;
let corrected: Date | null = null;
if (read && prev !== null) {
const adjusted = read.getTime() + offsetMs;
const storedHourEarly = Math.abs(adjusted - prev - 3_600_000) < 2_000;
const storedIgnoredOffset = offsetMs !== 0 && Math.abs(prev - read.getTime()) < 2_000 && Math.abs(prev - adjusted) >= 2_000;
if (storedHourEarly || storedIgnoredOffset) corrected = new Date(adjusted);
}
const autopilot = row.autopilot && typeof row.autopilot === "object" && !Array.isArray(row.autopilot) ? { ...(row.autopilot as Record<string, unknown>) } : null;
if (hourOff && autopilot) {
if (corrected && autopilot) {
delete autopilot.curated;
delete autopilot.chosen;
delete autopilot.gallery;
@@ -535,16 +563,16 @@ export class IngestService {
where: { id: row.id },
data: {
exif: withCaptureClockChecked(row.exif) as Prisma.InputJsonValue,
...(hourOff && next
...(corrected
? {
capturedAt: next,
...(prev !== null && Math.abs(taken - prev) < 2_000 ? { takenAt: next } : {}),
capturedAt: corrected,
...(prev !== null && Math.abs(taken - prev) < 2_000 ? { takenAt: corrected } : {}),
...(autopilot ? { autopilot: autopilot as Prisma.InputJsonValue } : {}),
}
: {}),
},
});
if (hourOff) fixed++;
if (corrected) fixed++;
}
if (rows.length) log.info({ scanned: rows.length, fixed }, "ingest: capture clock repair");
return fixed;
+2 -1
View File
@@ -57,7 +57,8 @@ export function sftpgoUser(
expiration_date: account.expiresAt ? account.expiresAt.getTime() : 0,
quota_size: (account.plan?.quotaMb ?? 0) * 1024 * 1024,
quota_files: account.plan?.quotaFiles ?? 0,
max_sessions: 4,
// Authenticated cameras have no session cap. SFTPGo reads 0 as no limit.
max_sessions: 0,
};
}
const UpdateBody = z.object({
+1
View File
@@ -21,6 +21,7 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum
width: photo.width,
height: photo.height,
capturedAt: photo.capturedAt?.toISOString() ?? null,
createdAt: photo.createdAt.toISOString(),
cameraModel: photo.cameraModel,
lens: photo.lens,
focalLength: photo.focalLength,
+25
View File
@@ -133,6 +133,31 @@ describe("only the best", () => {
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", () => {
+103 -39
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { clipsBall, compose, type Detection, findSubject, isHandball, isReportage, minCropWidth, planCrop, sendBlockedByBall } from "../src/composition/compose.js";
import { clipsBall, compose, type Detection, findSubject, isHandball, isLongPrime, isReportage, minCropWidth, planCrop, sendBlockedByBall, shotIntent } from "../src/composition/compose.js";
const person = (x0: number, y0: number, x1: number, y1: number, score = 0.9): Detection => ({ x0, y0, x1, y1, score });
const inside = (r: { x0: number; y0: number; x1: number; y1: number }, b: { x0: number; y0: number; x1: number; y1: number }) => r.x0 <= b.x0 + 1e-9 && r.y0 <= b.y0 + 1e-9 && r.x1 >= b.x1 - 1e-9 && r.y1 >= b.y1 - 1e-9;
@@ -29,6 +29,15 @@ describe("automatic crop", () => {
expect(main).toMatchObject(s.box);
});
it("does not throw a second player out of the frame", () => {
const main = person(0.18, 0.18, 0.4, 0.86);
const other = person(0.68, 0.2, 0.9, 0.84);
const c = compose({ ...frame, people: [main, other], balls: [] }, null, { framing: "tight", context: "sport" });
if (!c) return;
expect(inside(c.rect, main)).toBe(true);
expect(inside(c.rect, other)).toBe(true);
});
it("keeps a group together, and doesn't slice a big body at the crop's edge", () => {
const a = person(0.3, 0.2, 0.42, 0.8);
const b = person(0.4, 0.22, 0.52, 0.82);
@@ -139,6 +148,15 @@ describe("the ball follows the sport", () => {
expect(isHandball(null)).toBe(false);
});
it("keeps a ball in the outstretched hand inside the crop", () => {
const player = person(0.48, 0.15, 0.62, 0.92);
const ball = { x0: 0.02, y0: 0.28, x1: 0.08, y1: 0.36, score: 0.9 };
const c = compose({ ...frame, people: [player], balls: [ball] }, null, { framing: "tight", context: "sport", sport: "andebol" })!;
expect(c.reason).toBe("ball");
expect(inside(c.rect, player)).toBe(true);
expect(inside(c.rect, ball)).toBe(true);
});
it("in handball the ball in the hands wins over one on the floor, even when the floor ball overlaps the player and is closer to the body's middle", () => {
const player = { ...person(0.4, 0.15, 0.66, 0.996), sharpness: 1 };
const inHand = { x0: 0.48, y0: 0.08, x1: 0.56, y1: 0.18, score: 0.9 };
@@ -167,26 +185,68 @@ describe("reportage", () => {
expect(isReportage({ away: "", fixtureId: "11111111-1111-4111-8111-111111111111" })).toBe(false);
});
it("keeps the whole person when the event asked for the sports framing", () => {
const p = person(0.4, 0.15, 0.55, 0.8);
const c = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" })!;
expect(c.rect.y1).toBeGreaterThan(p.y1);
expect(c.rect.x0).toBeLessThanOrEqual(p.x0);
expect(c.rect.x1).toBeGreaterThanOrEqual(p.x1);
expect((p.y1 - p.y0) / (c.rect.y1 - c.rect.y0)).toBeLessThan(1);
it("names the shot from the frame", () => {
expect(shotIntent([person(0.35, 0.28, 0.52, 0.72)])).toBe("scene");
expect(shotIntent([person(0.3, 0.12, 0.48, 0.82)])).toBe("figure");
const left = person(0.16, 0.08, 0.36, 0.86);
const right = person(0.62, 0.06, 0.84, 0.88);
expect(shotIntent([left, right])).toBe("group");
expect(shotIntent([person(0.36, 0.15, 0.66, 0.996)])).toBe("closed");
});
it("keeps every head of a conversation, including someone stood in the shade", () => {
it("leaves a wide frame as shot", () => {
const speaker = person(0.35, 0.28, 0.52, 0.72);
const room = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "reportage" });
expect(room).toBeNull();
const match = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "sport" });
expect(match).not.toBeNull();
});
it("knows a long prime from a zoom and from a short prime", () => {
expect(isLongPrime({ focalLength: 135, range: [135, 135] })).toBe(true);
expect(isLongPrime({ focalLength: 100, range: [100, 100] })).toBe(true);
expect(isLongPrime({ focalLength: 85, range: [85, 85] })).toBe(false);
expect(isLongPrime({ focalLength: 200, range: [70, 200] })).toBe(false);
expect(isLongPrime({ focalLength: 400, name: "RF100-500mm F4.5-7.1" })).toBe(false);
expect(isLongPrime({ focalLength: 135, name: "RF135mm F1.8" })).toBe(true);
expect(isLongPrime({ focalLength: 200 })).toBe(false);
});
it("steps a full-length closer on a long prime, and leaves the same frame on a zoom", () => {
const p = person(0.3, 0.12, 0.48, 0.82);
const photo = { ...frame, people: [p], balls: [] };
const prime = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [135, 135] } })!;
expect(prime.rect.y0).toBeLessThanOrEqual(p.y0);
expect(prime.rect.y1).toBeGreaterThan(p.y1);
expect(prime.rect.x0).toBeLessThanOrEqual(p.x0);
expect(prime.rect.x1).toBeGreaterThanOrEqual(p.x1);
const width = prime.rect.x1 - prime.rect.x0;
expect(width).toBeGreaterThan(0.8);
expect(width).toBeLessThan(0.92);
const zoom = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [70, 200] } });
expect(zoom).toBeNull();
const wide = person(0.35, 0.28, 0.52, 0.72);
const scene = compose({ ...frame, people: [wide], balls: [] }, null, { context: "reportage", lens: { focalLength: 200, range: [200, 200] } });
expect(scene).toBeNull();
});
it("leaves a full-length as it was framed, and a match of the same picture still closes", () => {
const p = person(0.3, 0.12, 0.48, 0.82);
const room = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" });
expect(room).toBeNull();
const match = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "sport" });
expect(match).not.toBeNull();
if (!match) return;
expect(match.rect.x1 - match.rect.x0).toBeLessThan(0.92);
});
it("leaves a conversation as it was framed", () => {
const left = { ...person(0.16, 0.08, 0.36, 0.86), sharpness: 0.4 };
const center = { ...person(0.38, 0.16, 0.6, 0.92), sharpness: 1 };
const right = { ...person(0.62, 0.06, 0.84, 0.88), sharpness: 0.45 };
const c = compose({ ...frame, people: [left, center, right], balls: [] }, null, { framing: "tight", context: "reportage" })!;
expect(c.reason).toBe("group");
expect(c.people).toBe(3);
expect(c.rect.y0).toBeLessThanOrEqual(0.06);
expect(c.rect.y1).toBeGreaterThan(0.92);
expect(c.rect.x0).toBeLessThanOrEqual(0.16);
expect(c.rect.x1).toBeGreaterThanOrEqual(0.84);
const c = compose({ ...frame, people: [left, center, right], balls: [] }, null, { framing: "tight", context: "reportage" });
expect(c).toBeNull();
expect(shotIntent([left, center, right])).toBe("group");
});
it("does not slice the head of a person the crop otherwise keeps", () => {
@@ -220,20 +280,31 @@ describe("reportage", () => {
for (const j of [0.53, 0.74, 0.95]) expect(Math.abs(at - j)).toBeGreaterThanOrEqual(0.035);
});
it("keeps a complete foot when the head is already against the top edge", () => {
it("leaves a full-length that already fills the frame, so the foot stays", () => {
const p = person(0.4, 0.02, 0.55, 0.984);
const c = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" })!;
expect(c.rect.y1).toBeGreaterThan(p.y1 - 1e-6);
expect(c.rect.y0).toBeLessThanOrEqual(p.y0 + 1e-6);
const c = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" });
expect(c).toBeNull();
expect(shotIntent([p])).toBe("figure");
});
it("leaves out a stray hand at the edge of someone who is not the subject", () => {
it("does not close a full-length to delete a hand at the edge", () => {
const subject = person(0.22, 0.18, 0.4, 0.82);
const hand = person(0, 0.35, 0.07, 0.5, 0.8);
const c = compose({ ...frame, people: [subject, hand], balls: [] }, null, { context: "reportage" })!;
const handIn = Math.max(0, Math.min(c.rect.x1, hand.x1) - Math.max(c.rect.x0, hand.x0)) / (hand.x1 - hand.x0);
expect(handIn).toBeLessThan(0.05);
const c = compose({ ...frame, people: [subject, hand], balls: [] }, null, { context: "reportage" });
expect(c).toBeNull();
});
it("drops a person the frame already cut off, and keeps the full-length around the subject", () => {
const subject = person(0.32, 0.18, 0.5, 0.84);
const cutOff = person(0, 0.2, 0.16, 0.95);
const c = compose({ ...frame, people: [subject, cutOff], balls: [] }, null, { context: "reportage" })!;
const cutIn = Math.max(0, Math.min(c.rect.x1, cutOff.x1) - Math.max(c.rect.x0, cutOff.x0)) / (cutOff.x1 - cutOff.x0);
expect(cutIn).toBeLessThan(0.05);
expect(c.rect.x0).toBeLessThanOrEqual(subject.x0);
expect(c.rect.x1).toBeGreaterThanOrEqual(subject.x1);
expect(c.rect.y0).toBeLessThanOrEqual(subject.y0);
expect(c.rect.y1).toBeGreaterThan(subject.y1);
expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.8);
});
it("crops the whole person at the car, not the sharper face in the window", () => {
@@ -261,7 +332,8 @@ describe("reportage", () => {
});
it("keeps the closer woman whole when the woman behind her is sharper", () => {
// PSR39046, the glass entrance. The foreground figure is taller; the crop used to be a band on the woman behind.
// PSR39046, the glass entrance. The foreground figure is the full-length. Leaving the frame keeps her whole,
// instead of cutting a band on the woman behind.
const front = { ...person(0.45, 0.23, 0.636, 0.933, 0.9), sharpness: 0.6 };
const behind = { ...person(0.382, 0.304, 0.473, 0.667, 0.9), sharpness: 1 };
const c = compose({ width: 6000, height: 4000, people: [front, behind], balls: [] }, null, {
@@ -271,25 +343,17 @@ describe("reportage", () => {
{ x0: 0.5, y0: 0.25, x1: 0.56, y1: 0.34 },
{ x0: 0.4, y0: 0.31, x1: 0.45, y1: 0.4 },
],
})!;
expect(c.rect.y0).toBeLessThanOrEqual(front.y0 + 1e-6);
expect(c.rect.y1).toBeGreaterThan(front.y1 - 1e-6);
expect(c.rect.x0).toBeLessThanOrEqual(front.x0 + 1e-6);
expect(c.rect.x1).toBeGreaterThanOrEqual(front.x1 - 1e-6);
expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.7);
});
expect(c).toBeNull();
});
it("still frames three whole figures standing in the middle of a wide shot", () => {
// PSR16148. The boxes already are the bodies. The crop stays around them, it does not become the whole frame.
it("leaves a wide shot of small figures as it was framed", () => {
// People in the middle of a room, none of them large. The space around them is the photograph.
const a = { ...person(0.368, 0.296, 0.463, 0.614), sharpness: 0.84 };
const b = { ...person(0.477, 0.308, 0.547, 0.627), sharpness: 1 };
const c0 = { ...person(0.535, 0.293, 0.615, 0.62), sharpness: 0.85 };
const c = compose({ width: 6000, height: 4000, people: [a, b, c0], balls: [] }, null, { context: "reportage", minWidth: 0.5 })!;
expect(c.reason).toBe("group");
expect(c.rect.y0).toBeLessThanOrEqual(0.296);
expect(c.rect.y1).toBeGreaterThanOrEqual(0.627);
expect(c.rect.y1 - c.rect.y0).toBeLessThan(0.75);
expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.92);
const c = compose({ width: 6000, height: 4000, people: [a, b, c0], balls: [] }, null, { context: "reportage", minWidth: 0.5 });
expect(c).toBeNull();
});
it("makes a three-quarter plan below the hands, and refuses a half that would cut them", () => {
+42
View File
@@ -264,6 +264,48 @@ describe("library", () => {
expect(await send("c.jpg", "2026:09:23 22:00:00")).toMatchObject({ status: "ingested", eventId: null });
});
it("keeps a pin for extra time after the window, and does not undo a login clock offset", async () => {
const { orgId, photographer, event } = await setup();
const send = async (name: string, taken: string, offset = 0) => {
const file = path.join(dir, name);
await writeFile(file, await jpeg({ color: "#445566", taken }));
return service.ingest(file, {
organizationId: orgId,
userId: photographer.id,
source: "DESKTOP",
originalName: name,
eventId: event.id,
clockOffsetSec: offset,
});
};
// 00:20 wall in summer is 23:20 UTC, still inside the window that ends at 23:30.
expect(await send("late.jpg", "2026:09:24 00:20:00")).toMatchObject({ status: "ingested", eventId: event.id });
// 01:00 wall is 00:00 UTC, past the window, forty minutes later: the same match, not the inbox.
expect(await send("extra.jpg", "2026:09:24 01:00:00")).toMatchObject({ status: "ingested", eventId: event.id });
// Mark those two checked before the login offset changes, so the repair is only about the offset photo.
expect(await service.backfillCaptureClock(10)).toBe(0);
await ctx.db.ftpAccount.updateMany({ data: { clockOffsetSec: -3600 } });
const shifted = await send("clock.jpg", "2026:11:20 00:14:34", -3600);
const photoId = (shifted as { photoId: string }).photoId;
const photo = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } });
expect(photo.capturedAt?.toISOString()).toBe("2026-11-19T23:14:34.000Z");
expect(await service.backfillCaptureClock(10)).toBe(0);
const kept = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } });
expect(kept.capturedAt?.toISOString()).toBe("2026-11-19T23:14:34.000Z");
await ctx.db.ftpAccount.updateMany({ data: { clockOffsetSec: 0 } });
const early = await send("early.jpg", "2026:12:05 21:14:07", 0);
const earlyId = (early as { photoId: string }).photoId;
await ctx.db.photo.update({
where: { id: earlyId },
data: { capturedAt: new Date("2026-12-05T20:14:07.000Z"), exif: {} },
});
expect(await service.backfillCaptureClock(10)).toBe(1);
const repaired = await ctx.db.photo.findUniqueOrThrow({ where: { id: earlyId } });
expect(repaired.capturedAt?.toISOString()).toBe("2026-12-05T21:14:07.000Z");
});
it("an archive import stays in its put-away event when the photo was taken outside that window", async () => {
const { orgId, admin, photographer, event } = await setup();
await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-09-24T00:00:00Z") } });
+18
View File
@@ -62,6 +62,18 @@ export const t = {
photoMenuDevelop: "Revelar",
photoMenuLoupe: "Lupa",
photoMenuGrid: "Grelha",
photoMenuSend: "Enviar",
photoMenuMove: "Mover para evento",
photoMenuApplyDevelop: "Aplicar revelação básica",
photoMenuSelectAll: "Selecionar tudo",
photoMenuSelectNone: "Limpar seleção",
photoMenuNothingToSend: "Nada para enviar: as selecionadas estão rejeitadas ou ainda a chegar.",
eventMenu: "Evento",
eventMenuOpen: "Abrir",
eventMenuSettings: "Definições",
eventMenuAutopilot: "Piloto automático",
eventMenuFtp: "Receber o FTP local aqui",
eventMenuFtpStop: "Deixar de receber o FTP local",
folderSheet: {
opening: "A abrir a pasta…",
close: "Fechar",
@@ -97,6 +109,12 @@ export const t = {
noPhotos: "Sem fotografias neste filtro.",
noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.",
filter: "Filtro",
sortBy: "Ordem",
sortOptions: {
capture: { asc: "Captura", desc: "Captura, mais recente" },
arrival: { asc: "Chegada", desc: "Chegada, mais recente" },
name: { asc: "Nome do ficheiro", desc: "Nome do ficheiro, Z–A" },
},
flagFilter: { all: "Todas", PICK: "Escolhidas", UNFLAGGED: "Sem marca", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas" },
starsAtLeast: "Estrelas (pelo menos)",
starsOrMore: (n: number) => (n === 1 ? "1 estrela ou mais" : `${n} estrelas ou mais`),
+15 -1
View File
@@ -8,12 +8,26 @@ import { ZerozeroGamePicker } from "./ZerozeroGame.js";
* Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest
* are edited (tone, level, crop) and the best frames of each burst picked, and optionally delivered.
*/
export function AutopilotButton(props: { api: ApiClient; event: EventSummary; targets: DeliveryTarget[]; canEdit: boolean; onSaved: (e: EventSummary) => void }) {
export function AutopilotButton(props: {
api: ApiClient;
event: EventSummary;
targets: DeliveryTarget[];
canEdit: boolean;
onSaved: (e: EventSummary) => void;
/** Set from the event menu. Opens this panel once, then calls onAsked. */
autopilotAsk?: { id: string; n: number } | null;
onAsked?: () => void;
}) {
const L = t.autopilot;
const [open, setOpen] = useState(false);
const [s, setS] = useState<AutopilotSettings>(() => AutopilotSettings.parse(props.event.autopilot ?? {}));
const [state, setState] = useState<"idle" | "saving" | "error">("idle");
useEffect(() => setS(AutopilotSettings.parse(props.event.autopilot ?? {})), [props.event]);
useEffect(() => {
if (!props.autopilotAsk || props.autopilotAsk.id !== props.event.id) return;
setOpen(true);
props.onAsked?.();
}, [props.autopilotAsk, props.event.id, props.onAsked]);
const save = async (next: AutopilotSettings) => {
// Keep deliverTargetIds in sync with the two legacy slots (N exports = ordered list).
+102
View File
@@ -0,0 +1,102 @@
import type { EventSummary } from "@photoreport/sdk";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { EventsPanel } from "./EventsPanel.js";
import { PhotoContextMenu } from "./PhotoContextMenu.js";
function event(id: string, title: string): EventSummary {
return {
id,
organizationId: "org",
title,
home: title,
away: "",
homeShort: null,
awayShort: null,
venue: null,
city: null,
sport: null,
competition: null,
competitionCode: null,
round: null,
matchNumber: null,
startsAt: "2026-11-21T10:56:00.000Z",
ingestFrom: "2026-11-21T08:56:00.000Z",
ingestUntil: "2026-11-21T14:56:00.000Z",
iptcTemplate: {},
archivedAt: null,
photographers: [],
photoCount: 12,
};
}
describe("event context menu", () => {
it("asks for the event menu and does not fall through to the page", () => {
const onEventMenu = vi.fn();
const onPanelMenu = vi.fn();
const onInboxMenu = vi.fn();
render(
<EventsPanel
events={[event("asm", "Assembleia Geral FAP")]}
inboxCount={3}
scope="inbox"
canCreate
canSeeInbox
onOpen={() => {}}
onCreate={() => {}}
onEventMenu={onEventMenu}
onInboxMenu={onInboxMenu}
onPanelMenu={onPanelMenu}
/>,
);
const row = screen.getByRole("button", { name: /Assembleia Geral FAP/ });
fireEvent.contextMenu(row);
expect(onEventMenu).toHaveBeenCalledOnce();
const rowMenu = onEventMenu.mock.calls[0]?.[1] as MouseEvent;
expect(rowMenu.defaultPrevented).toBe(true);
expect(onPanelMenu).not.toHaveBeenCalled();
const inbox = screen.getByRole("button", { name: /Sem evento/ });
fireEvent.contextMenu(inbox);
expect(onInboxMenu).toHaveBeenCalledOnce();
const panel = screen.getByRole("complementary", { name: "Eventos" });
fireEvent.contextMenu(panel);
expect(onPanelMenu).toHaveBeenCalledOnce();
});
});
describe("photo context menu", () => {
it("sets a colour and opens a destination list", () => {
const onColor = vi.fn();
const onClose = vi.fn();
const onSend = vi.fn();
render(
<PhotoContextMenu
x={20}
y={20}
onClose={onClose}
onColor={onColor}
actions={[
{
id: "send",
label: "Enviar",
items: [{ id: "fpa", label: "FPA Eventos", onSelect: onSend }],
},
{ id: "pick", label: "Escolher", onSelect: () => {} },
]}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Vermelho" }));
expect(onColor).toHaveBeenCalledWith("RED");
expect(onClose).toHaveBeenCalledOnce();
fireEvent.click(screen.getByRole("menuitem", { name: "Enviar" }));
expect(onClose).toHaveBeenCalledOnce();
fireEvent.click(screen.getByRole("menuitem", { name: "FPA Eventos" }));
expect(onSend).toHaveBeenCalledOnce();
expect(onClose).toHaveBeenCalledTimes(2);
});
});
+9
View File
@@ -27,6 +27,9 @@ export function EventSettingsButton(props: {
canEdit: boolean;
onSaved: (e: EventSummary) => void;
onRemoved: (eventId: string) => void;
/** Set from the event menu. Opens this panel once, then calls onAsked. */
settingsAsk?: { id: string; n: number } | null;
onAsked?: () => void;
}) {
const L = t.eventSettings;
const { api, event } = props;
@@ -48,6 +51,12 @@ export function EventSettingsButton(props: {
const [error, setError] = useState<string | null>(null);
const [confirm, setConfirm] = useState(false);
useEffect(() => {
if (!props.settingsAsk || props.settingsAsk.id !== event.id) return;
setOpen(true);
props.onAsked?.();
}, [props.settingsAsk, event.id, props.onAsked]);
useEffect(() => {
setStartsAt(isoToLisbonLocal(event.startsAt));
setFrom(isoToLisbonLocal(event.ingestFrom));
+23
View File
@@ -29,6 +29,9 @@ export function EventsPanel(props: {
/** Events put away by hand (loaded when asked for); null: not shown. */
archived?: EventSummary[] | null;
onToggleArchived?: () => void;
onEventMenu?: (event: EventSummary, e: React.MouseEvent) => void;
onInboxMenu?: (e: React.MouseEvent) => void;
onPanelMenu?: (e: React.MouseEvent) => void;
}) {
const [older, setOlder] = useState(false);
const L = t.eventsList;
@@ -46,8 +49,14 @@ export function EventsPanel(props: {
const item = (e: EventSummary, archived = false) => (
<button
key={e.id}
data-event-id={e.id}
className={row(props.scope === e.id)}
onClick={() => props.onOpen(e.id)}
onContextMenu={(ev) => {
ev.preventDefault();
ev.stopPropagation();
props.onEventMenu?.(e, ev);
}}
>
<span className="min-w-0">
<span className={`block truncate ${archived ? "text-faint" : ""}`}>
@@ -74,6 +83,14 @@ export function EventsPanel(props: {
<aside
aria-label={t.events}
className="flex w-60 shrink-0 flex-col border-r border-line bg-panel max-lg:w-full max-lg:border-r-0 max-lg:border-b"
onContextMenu={(e) => {
e.preventDefault();
const el = e.target;
if (!(el instanceof HTMLElement)) return;
if (el.closest("input, textarea")) return;
if (el.closest("[data-event-id]")) return;
props.onPanelMenu?.(e);
}}
>
<div className="panel-head">
<span>{t.events}</span>
@@ -112,8 +129,14 @@ export function EventsPanel(props: {
<nav className="min-h-0 flex-1 overflow-y-auto py-1 max-lg:max-h-48">
{props.canSeeInbox && (
<button
data-event-id="inbox"
className={row(props.scope === "inbox")}
onClick={() => props.onOpen("inbox")}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
props.onInboxMenu?.(e);
}}
>
<span className="italic">{t.inbox}</span>
<span className="font-mono text-[11px]">{props.inboxCount}</span>
+24
View File
@@ -48,4 +48,28 @@ describe("grid", () => {
fireEvent.doubleClick(screen.getByRole("button", { name: /a\.jpg/ }));
expect(onOpen).toHaveBeenCalledWith("a");
});
it("opens a menu on the photo and on the empty sheet", () => {
const onMenu = vi.fn();
const onBackgroundMenu = vi.fn();
render(
<Grid
photos={[photo("a")]}
selected={new Set()}
focus={null}
srcFor={() => ""}
onPick={() => {}}
onOpen={() => {}}
onMenu={onMenu}
onBackgroundMenu={onBackgroundMenu}
/>,
);
const photoButton = screen.getByRole("button", { name: /a\.jpg/ });
fireEvent.contextMenu(photoButton);
expect(onMenu).toHaveBeenCalledWith("a", expect.anything());
expect(onBackgroundMenu).not.toHaveBeenCalled();
fireEvent.contextMenu(screen.getByRole("region", { name: "Grelha" }));
expect(onBackgroundMenu).toHaveBeenCalledOnce();
});
});
+8 -1
View File
@@ -155,6 +155,8 @@ export function Grid(props: {
onPick: (id: string, e: React.MouseEvent) => void;
onOpen: (id: string) => void;
onMenu?: (id: string, e: React.MouseEvent) => void;
/** Right-click on the empty sheet, not on a photo. */
onBackgroundMenu?: (e: React.MouseEvent) => void;
/** Drag a rectangle across the sheet, as in Photo Mechanic. Replaces the selection, or adds to it with Shift/Cmd. */
onSelectMany?: (ids: string[], focus: string | null) => void;
}) {
@@ -189,7 +191,12 @@ export function Grid(props: {
aria-label="Grelha"
className="relative grid content-start gap-1 p-1.5"
style={{ gridTemplateColumns: "repeat(auto-fill, minmax(168px, 1fr))" }}
onContextMenu={(e) => e.preventDefault()}
onContextMenu={(e) => {
const el = e.target;
if (el instanceof HTMLElement && el.closest("[data-photo-id]")) return;
e.preventDefault();
props.onBackgroundMenu?.(e);
}}
onPointerDown={(e) => {
if (e.button !== 0 || !props.onSelectMany) return;
drag.current = {
+2 -1
View File
@@ -3,7 +3,7 @@ import type { EventSummary } from "@photoreport/sdk";
import { useAuth } from "../auth.js";
import { planLocalAutopilot } from "../offline/autopilot.js";
import { cache } from "../offline/cache.js";
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { eventForArrival, exifDateTime, exifLens, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { localId, offlineQueue } from "../offline/queue.js";
import { useCallback, useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
@@ -233,6 +233,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
width: info.width,
height: info.height,
capturedAt,
lens: exifLens(preview),
}).catch(() => {}),
);
autopilotChain.current = plan.then(
+60 -19
View File
@@ -1,5 +1,5 @@
import type { ColorLabel } from "@photoreport/contracts";
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js";
@@ -10,7 +10,9 @@ export interface PhotoMenuAction {
label: string;
danger?: boolean;
disabled?: boolean;
onSelect: () => void;
onSelect?: () => void;
/** Opens beside this row. A leaf action has no items. */
items?: PhotoMenuAction[];
}
/** PhotoReport's own right-click menu — replaces the webview's "Open Image / Download / Copy". */
@@ -21,8 +23,10 @@ export function PhotoContextMenu(props: {
onClose: () => void;
onColor?: (color: ColorLabel) => void;
onRating?: (rating: number) => void;
label?: string;
}) {
const ref = useRef<HTMLDivElement>(null);
const [openId, setOpenId] = useState<string | null>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
@@ -42,14 +46,15 @@ export function PhotoContextMenu(props: {
};
}, [props.onClose]);
// Keep the menu on screen.
const left = Math.min(props.x, typeof window !== "undefined" ? window.innerWidth - 220 : props.x);
const left = Math.min(props.x, typeof window !== "undefined" ? window.innerWidth - 240 : props.x);
const top = Math.min(props.y, typeof window !== "undefined" ? window.innerHeight - props.actions.length * 32 - 88 : props.y);
const flyLeft = typeof window !== "undefined" && props.x > window.innerWidth - 480;
return (
<div
ref={ref}
role="menu"
aria-label={t.photoMenu}
className="fixed z-[60] min-w-[200px] border border-line bg-panel py-1 shadow-xl"
aria-label={props.label ?? t.photoMenu}
className="fixed z-[60] min-w-[220px] border border-line bg-panel py-1 shadow-xl"
style={{ left, top }}
>
{(props.onColor || props.onRating) && (
@@ -93,22 +98,58 @@ export function PhotoContextMenu(props: {
</div>
)}
{props.actions.map((a) => (
<button
<div
key={a.id}
type="button"
role="menuitem"
disabled={a.disabled}
className={`flex w-full px-3 py-1.5 text-left text-[13px] disabled:opacity-40 ${
a.danger ? "text-danger hover:bg-[#3a2020]" : "text-ink hover:bg-cell-on"
}`}
onClick={() => {
if (a.disabled) return;
a.onSelect();
props.onClose();
}}
className="relative"
onMouseEnter={() => setOpenId(a.items?.length ? a.id : null)}
>
{a.label}
</button>
<button
type="button"
role="menuitem"
aria-haspopup={a.items?.length ? "menu" : undefined}
disabled={a.disabled}
className={`flex w-full items-center gap-3 px-3 py-1.5 text-left text-[13px] disabled:opacity-40 ${
a.danger ? "border-t border-line text-danger hover:bg-[#3a2020]" : "text-ink hover:bg-cell-on"
}`}
onClick={() => {
if (a.disabled) return;
if (a.items?.length) {
setOpenId(a.id);
return;
}
a.onSelect?.();
props.onClose();
}}
>
<span className="min-w-0 flex-1 truncate">{a.label}</span>
{!!a.items?.length && <span aria-hidden="true" className="text-faint">›</span>}
</button>
{openId === a.id && !!a.items?.length && (
<div
role="menu"
className={`absolute top-0 z-[61] max-h-80 min-w-[200px] overflow-y-auto border border-line bg-panel py-1 shadow-xl ${
flyLeft ? "right-full" : "left-full"
}`}
>
{a.items.map((item) => (
<button
key={item.id}
type="button"
role="menuitem"
disabled={item.disabled}
className="flex w-full px-3 py-1.5 text-left text-[13px] text-ink hover:bg-cell-on disabled:opacity-40"
onClick={() => {
if (item.disabled) return;
item.onSelect?.();
props.onClose();
}}
>
<span className="min-w-0 flex-1 truncate">{item.label}</span>
</button>
))}
</div>
)}
</div>
))}
</div>
);
+27
View File
@@ -0,0 +1,27 @@
import { t } from "../i18n.js";
import { SORT_CHOICES, sortValue, parseSortValue, type LibrarySort } from "./sort.js";
/** The library order: capture time, arrival time, or file name, each oldest/A–Z or the other way. */
export function SortControl(props: { sort: LibrarySort; onChange: (sort: LibrarySort) => void }) {
const { sort, onChange } = props;
return (
<label className="flex items-center gap-1">
<span className="text-faint">{t.sortBy}</span>
<select
value={sortValue(sort)}
aria-label={t.sortBy}
onChange={(e) => {
const next = parseSortValue(e.target.value);
if (next) onChange(next);
}}
className="pr-field text-ink"
>
{SORT_CHOICES.map((item) => (
<option key={sortValue(item)} value={sortValue(item)}>
{t.sortOptions[item.field][item.direction]}
</option>
))}
</select>
</label>
);
}
+2 -2
View File
@@ -477,7 +477,7 @@ export function TargetForm({
field(
"folderTemplate",
v.kind === "LOCAL"
? "Subpasta ({event} = Casa x Fora, {iptcdate} = 20261009)"
? "Subpasta ({event} = Casa x Fora, {iptcdate} = dia do evento)"
: "Pasta ({event} = Casa x Fora)",
)}
{field(
@@ -620,7 +620,7 @@ export function TargetForm({
</div>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">
Subpasta ({"{iptcdate}"} = dia da foto, {"{event}"} = jogo, {"{destination}"} = nome deste destino)
Subpasta ({"{iptcdate}"} = dia do evento, {"{event}"} = jogo, {"{destination}"} = nome deste destino)
</span>
<input
className={`${input} font-mono text-[12px]`}
+7 -1
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from "vitest";
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "./active.js";
import { activePhoto, savedFilter, savedSort, saveFilter, saveSort, setActivePhoto } from "./active.js";
import { ALL_PHOTOS } from "./store.js";
describe("active photo across modules", () => {
@@ -25,5 +25,11 @@ describe("active photo across modules", () => {
expect(savedFilter("o1")).toEqual({ ...ALL_PHOTOS, minRating: 3 });
window.localStorage.setItem("pr.filter:o1", "nonsense");
expect(savedFilter("o1")).toEqual(ALL_PHOTOS);
expect(savedSort("o1")).toEqual({ field: "capture", direction: "asc" });
saveSort("o1", { field: "name", direction: "asc" });
expect(savedSort("o1")).toEqual({ field: "name", direction: "asc" });
window.localStorage.setItem("pr.sort:o1", "nope");
expect(savedSort("o1")).toEqual({ field: "capture", direction: "asc" });
});
});
+13
View File
@@ -1,4 +1,5 @@
import { prefs } from "../platform.js";
import { CAPTURE_ORDER, parseSortValue, type LibrarySort } from "./sort.js";
import { ALL_PHOTOS, type LibraryFilter } from "./store.js";
/**
@@ -13,6 +14,7 @@ interface ActivePhoto {
const activeKey = (orgId: string) => `active:${orgId}`;
const filterKey = (orgId: string) => `filter:${orgId}`;
const sortKey = (orgId: string) => `sort:${orgId}`;
/** The active photo of that folder, if there is one. */
export function activePhoto(orgId: string, scope: string | null | undefined): string | null {
@@ -67,3 +69,14 @@ export function savedFilter(orgId: string): LibraryFilter {
export function saveFilter(orgId: string, filter: LibraryFilter): void {
if (orgId) prefs.set(filterKey(orgId), JSON.stringify(filter));
}
/** The library order. A missing or old value stays on capture time, oldest first. */
export function savedSort(orgId: string): LibrarySort {
const raw = orgId ? prefs.get(sortKey(orgId)) : null;
if (!raw) return CAPTURE_ORDER;
return parseSortValue(raw) ?? CAPTURE_ORDER;
}
export function saveSort(orgId: string, sort: LibrarySort): void {
if (orgId) prefs.set(sortKey(orgId), `${sort.field}:${sort.direction}`);
}
+62
View File
@@ -0,0 +1,62 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { describe, expect, it } from "vitest";
import { parseSortValue, sortPhotos } from "./sort.js";
const photo = (id: string, extra: Partial<PhotoSummary> = {}): PhotoSummary => ({
id,
eventId: "e1",
originalName: `${id}.jpg`,
name: `${id}.jpg`,
sha256: id,
originalStored: true,
status: "READY",
width: 100,
height: 100,
capturedAt: "2026-11-20T20:00:00.000Z",
cameraModel: null,
lens: null,
focalLength: null,
aperture: null,
exposureTime: null,
iso: null,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: "", preview: "", source: "" },
...extra,
});
describe("library sort", () => {
const photos = [
photo("b", { name: "R3VS10.JPG", capturedAt: "2026-11-20T20:02:00.000Z", createdAt: "2026-11-20T21:00:00.000Z" }),
photo("a", { name: "R3VS2.JPG", capturedAt: "2026-11-20T20:05:00.000Z", createdAt: "2026-11-20T20:10:00.000Z" }),
photo("c", { name: "R3VS3.JPG", capturedAt: null, createdAt: "2026-11-20T22:00:00.000Z" }),
];
it("keeps capture order, oldest first, with an unknown time at the end", () => {
expect(sortPhotos(photos, { field: "capture", direction: "asc" }).map((p) => p.id)).toEqual(["b", "a", "c"]);
});
it("puts the newest capture first and still leaves an unknown time at the end", () => {
expect(sortPhotos(photos, { field: "capture", direction: "desc" }).map((p) => p.id)).toEqual(["a", "b", "c"]);
});
it("orders by when the file arrived, not by when it was taken", () => {
expect(sortPhotos(photos, { field: "arrival", direction: "asc" }).map((p) => p.id)).toEqual(["a", "b", "c"]);
expect(sortPhotos(photos, { field: "arrival", direction: "desc" }).map((p) => p.id)).toEqual(["c", "b", "a"]);
});
it("orders file names so 2 comes before 10", () => {
expect(sortPhotos(photos, { field: "name", direction: "asc" }).map((p) => p.name)).toEqual(["R3VS2.JPG", "R3VS3.JPG", "R3VS10.JPG"]);
expect(sortPhotos(photos, { field: "name", direction: "desc" }).map((p) => p.name)).toEqual(["R3VS10.JPG", "R3VS3.JPG", "R3VS2.JPG"]);
});
it("reads only a real menu value", () => {
expect(parseSortValue("arrival:desc")).toEqual({ field: "arrival", direction: "desc" });
expect(parseSortValue("rating:asc")).toBeNull();
expect(parseSortValue("name")).toBeNull();
});
});
+71
View File
@@ -0,0 +1,71 @@
import type { PhotoSummary } from "@photoreport/contracts";
/** How the library grid lines the photographs up. Capture, oldest first, is the contact sheet. */
export type LibrarySortField = "capture" | "arrival" | "name";
export type LibrarySortDirection = "asc" | "desc";
export interface LibrarySort {
field: LibrarySortField;
direction: LibrarySortDirection;
}
export const CAPTURE_ORDER: LibrarySort = { field: "capture", direction: "asc" };
const FIELDS: LibrarySortField[] = ["capture", "arrival", "name"];
const DIRECTIONS: LibrarySortDirection[] = ["asc", "desc"];
export const SORT_CHOICES: LibrarySort[] = FIELDS.flatMap((field) => DIRECTIONS.map((direction) => ({ field, direction })));
/** `capture:asc` from the order menu. Anything else is not a sort. */
export function parseSortValue(value: string): LibrarySort | null {
const [field, direction] = value.split(":");
if (!FIELDS.includes(field as LibrarySortField)) return null;
if (!DIRECTIONS.includes(direction as LibrarySortDirection)) return null;
return { field: field as LibrarySortField, direction: direction as LibrarySortDirection };
}
export function sortValue(sort: LibrarySort): string {
return `${sort.field}:${sort.direction}`;
}
function textOf(photo: PhotoSummary, field: LibrarySortField): string {
if (field === "arrival") return photo.createdAt ?? "";
if (field === "name") return photo.name;
return photo.capturedAt ?? "";
}
function compareText(left: string, right: string): number {
return left.localeCompare(right, "pt", { numeric: true, sensitivity: "base" });
}
/** A missing capture or arrival time stays at the end, in either direction. */
function missingLast(left: string, right: string): number {
if (left && right) return 0;
if (!left && !right) return 0;
if (!left) return 1;
return -1;
}
function comparePhotos(a: PhotoSummary, b: PhotoSummary, sort: LibrarySort): number {
const left = textOf(a, sort.field);
const right = textOf(b, sort.field);
const missing = missingLast(left, right);
if (missing !== 0) return missing;
const byField = compareText(left, right);
if (byField !== 0) {
if (sort.direction === "desc") return -byField;
return byField;
}
if (sort.field !== "name") {
const byName = compareText(a.name, b.name);
if (byName !== 0) return byName;
}
return a.id.localeCompare(b.id);
}
/** A new list in the chosen order. The stored folder stays in capture order. */
export function sortPhotos(photos: readonly PhotoSummary[], sort: LibrarySort): PhotoSummary[] {
const next = [...photos];
next.sort((a, b) => comparePhotos(a, b, sort));
return next;
}
+15
View File
@@ -146,6 +146,21 @@ describe("library store", () => {
expect(s.loading).toBe(false);
});
it("takes the arrival time from the server list, and stamps one that arrives without it", () => {
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1")], done: false });
s = libraryReducer(s, {
type: "loaded",
scope: "e1",
photos: [photo("a", "1", { createdAt: "2026-11-20T22:50:00.000Z" })],
done: true,
drop: ["a"],
});
expect(s.photos[0]?.createdAt).toBe("2026-11-20T22:50:00.000Z");
s = libraryReducer(s, { type: "message", message: { type: "photo.added", photo: photo("b", "2") } });
expect(s.photos.find((p) => p.id === "b")?.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
it("replaces expired file urls from the cache and keeps a mark made while the list was loading", () => {
const stale = { thumb: "/v1/files/photos/a/thumb?exp=1&v=2", preview: "/old-preview?v=2", source: "/old-source" };
const fresh = { thumb: "/v1/files/photos/a/thumb?exp=9&v=2", preview: "/new-preview?v=2", source: "/new-source" };
+11 -4
View File
@@ -59,6 +59,9 @@ function renderedVersion(url: string): number {
function withFreshFileUrls(current: PhotoSummary, incoming: PhotoSummary | undefined): PhotoSummary {
if (!incoming) return current;
let next = current;
if (incoming.createdAt && incoming.createdAt !== current.createdAt) {
next = { ...next, createdAt: incoming.createdAt };
}
if (current.status !== "READY" && incoming.status !== current.status) {
next = { ...next, status: incoming.status };
if (incoming.error) next = { ...next, error: incoming.error };
@@ -132,10 +135,14 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
const m = action.message;
if (m.type === "photo.added") {
// The server's copy of a photo shown from this computer: it takes the local one's place (and selection).
const local = state.photos.find((p) => p.id.startsWith("local:") && p.sha256 === m.photo.sha256);
if (local) return replaceLocal(state, local, m.photo);
if (!inScope(state.scope, m.photo) || state.photos.some((p) => p.id === m.photo.id)) return state;
return { ...state, photos: [...state.photos, m.photo].sort(byCapture) };
let arrived = m.photo;
if (!arrived.createdAt) {
arrived = { ...arrived, createdAt: new Date().toISOString() };
}
const local = state.photos.find((p) => p.id.startsWith("local:") && p.sha256 === arrived.sha256);
if (local) return replaceLocal(state, local, arrived);
if (!inScope(state.scope, arrived) || state.photos.some((p) => p.id === arrived.id)) return state;
return { ...state, photos: [...state.photos, arrived].sort(byCapture) };
}
if (m.type === "photo.updated") return libraryReducer(state, { type: "patch", ids: m.ids, patch: m.patch });
if (m.type === "photo.edited") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)) };
+7
View File
@@ -40,4 +40,11 @@ describe("local burst autopilot", () => {
const { picked } = decidePending(pending, 1, 1500, 1_400 + BURST_SETTLE_MS + 1);
expect(picked.map((f) => f.sha256)).toEqual(["b"]);
});
it("picks the open eyes when the sharper frame of the sequence blinked", () => {
const pending = [{ ...frame("shut", 0, 9), eyes: 0.2 }, { ...frame("open", 100, 4), eyes: 0.8 }];
const now = 1_800_000_000_000 + 100 + BURST_SETTLE_MS + 1;
const { picked } = decidePending(pending, 1, 1500, now);
expect(picked.map((f) => f.sha256)).toEqual(["open"]);
});
});
+21 -3
View File
@@ -1,8 +1,11 @@
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 { type LensHint, frameScore, isReportage } from "../../../api/src/composition/compose.js";
import { cameraLevelAngle } from "../../../api/src/composition/cameraLevel.js";
import { levelAngle, measuredValues, planFrame } from "../../../api/src/composition/planFrame.js";
import { bestOf, groupBursts } from "../../../api/src/autopilot/bursts.js";
import { rankForPick, sequenceWeight } from "../../../api/src/autopilot/sequenceScore.js";
import { eyesInPreview } from "./previewEyes.js";
import { settingsFromCommands, writePhotoFile } from "../desktop/lightroomSidecar.js";
import { loadEngine } from "../develop/engine.js";
import { isDesktop } from "../platform.js";
@@ -22,6 +25,8 @@ export interface PendingFrame {
camera: string;
score: number;
ops: EditCommand[];
/** How open the eyes look, compared only inside this burst. Null: not measured. */
eyes?: number | null;
decided?: boolean;
}
@@ -42,6 +47,8 @@ export async function planLocalAutopilot(args: {
iso?: number | null;
capturedAt?: string | null;
camera?: string | null;
/** The lens on this frame. A long prime may step closer; a zoom does not. */
lens?: LensHint | null;
}): Promise<void> {
if (!isDesktop() || !args.orgId || !args.event?.autopilot || !args.event.id) return;
const settings = AutopilotSettings.parse(args.event.autopilot);
@@ -54,7 +61,8 @@ export async function planLocalAutopilot(args: {
]);
// 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 fromCamera = cameraLevelAngle(args.preview);
const angle = settings.level && fromCamera !== null ? levelAngle(fromCamera, true) : levelAngle(measured.angle, settings.level);
const values = measuredValues(measured.values, settings, args.iso ?? null, style?.offsets ?? {});
// The crop (hands, a whole foot, an open team, a ball that is not sliced) is decided in compose.ts.
// The same rules run here and on the server. The server does not deliver a frame whose ball is cut.
@@ -68,9 +76,16 @@ export async function planLocalAutopilot(args: {
cropFactor: style?.cropFactor ?? null,
cropBias: style?.cropBias ?? null,
sport: args.event.sport,
lens: args.lens ?? null,
settings,
});
const score = frameScore(detections, planned.composition);
let eyes: number | null = null;
try {
eyes = await eyesInPreview(args.preview, detections.people);
} catch {
eyes = null;
}
const frame: PendingFrame = {
sha256: args.sha256,
capturedAt: args.capturedAt ?? null,
@@ -78,6 +93,7 @@ export async function planLocalAutopilot(args: {
camera: args.camera?.trim() || "local",
score,
ops: planned.ops,
eyes,
};
const pending = await loadPending(args.orgId, args.event.id);
const next = [...pending.filter((f) => f.sha256 !== frame.sha256), frame];
@@ -118,7 +134,9 @@ export function decidePending(pending: readonly PendingFrame[], picksPerBurst: n
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));
const weights = sequenceWeight(burst.map((frame) => ({ facing: null, eyes: frame.eyes ?? null })));
const pool = rankForPick(burst, weights, () => true);
const chosen = new Set(bestOf(pool, picksPerBurst).map((f) => f.sha256));
for (const frame of burst) {
const row = updated.find((u) => u.sha256 === frame.sha256);
if (row) row.decided = true;
+45 -2
View File
@@ -8,8 +8,28 @@ import { localId } from "./queue.js";
* server's copy takes their place (with what was done to them meanwhile).
*/
export interface ExifLens {
focalLength: number | null;
range: [number, number] | null;
name: string | null;
}
/** The capture time in a JPEG's EXIF (DateTimeOriginal, else DateTime), as written by the camera (local wall time). */
export function exifDateTime(bytes: ArrayBuffer): string | null {
return readCameraExif(bytes)?.date ?? null;
}
/** Focal length and whether the lens is a prime, from the same EXIF block the preview keeps. */
export function exifLens(bytes: ArrayBuffer): ExifLens {
const found = readCameraExif(bytes);
return {
focalLength: found?.focalLength ?? null,
range: found?.range ?? null,
name: found?.name ?? null,
};
}
function readCameraExif(bytes: ArrayBuffer): { date: string | null; focalLength: number | null; range: [number, number] | null; name: string | null } | null {
const v = new DataView(bytes);
if (v.byteLength < 4 || v.getUint16(0) !== 0xffd8) return null;
let off = 2;
@@ -23,7 +43,7 @@ export function exifDateTime(bytes: ArrayBuffer): string | null {
return null;
}
function readTiff(v: DataView, start: number, end: number): string | null {
function readTiff(v: DataView, start: number, end: number): { date: string | null; focalLength: number | null; range: [number, number] | null; name: string | null } | null {
if (start + 8 > end) return null;
const little = v.getUint16(start) === 0x4949;
const u16 = (o: number) => v.getUint16(start + o, little);
@@ -53,10 +73,33 @@ function readTiff(v: DataView, start: number, end: number): string | null {
const count = u32(entry + 4);
return ascii(count <= 4 ? entry + 8 : u32(entry + 8), count);
};
const rational = (entry: number | undefined, index: number) => {
if (entry === undefined) return null;
const type = u16(entry + 2);
const count = u32(entry + 4);
if (index >= count) return null;
if (type !== 5 && type !== 10) return null;
const at = count * 8 <= 4 ? entry + 8 : u32(entry + 8);
const o = at + index * 8;
if (start + o + 8 > end) return null;
const num = type === 10 ? v.getInt32(start + o, little) : u32(o);
const den = type === 10 ? v.getInt32(start + o + 4, little) : u32(o + 4);
if (!den) return null;
return num / den;
};
const ifd0 = entries(u32(4));
const exifAt = ifd0.get(0x8769);
const exif = exifAt !== undefined ? entries(u32(exifAt + 8)) : new Map<number, number>();
return text(exif.get(0x9003)) ?? text(ifd0.get(0x0132));
const min = rational(exif.get(0xa432), 0);
const max = rational(exif.get(0xa432), 1);
let range: [number, number] | null = null;
if (min != null && max != null && min > 0 && max > 0) range = [min, max];
return {
date: text(exif.get(0x9003)) ?? text(ifd0.get(0x0132)),
focalLength: rational(exif.get(0x920a), 0),
range,
name: text(exif.get(0xa434)),
};
}
/** "2026:10:09 20:26:47" (Lisbon wall time, as the API reads it) to an ISO instant. */
+31 -1
View File
@@ -2,7 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
import { ApiError, type ApiClient } from "@photoreport/sdk";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { initialLibrary, libraryReducer } from "../library/store.js";
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, routeLocally } from "./local.js";
import { eventForArrival, exifDateTime, exifLens, lisbonInstant, localPhoto, routeLocally } from "./local.js";
import { isNetworkError, localId, OfflineQueue } from "./queue.js";
function memoryStore() {
@@ -113,6 +113,7 @@ describe("photos arriving on this computer", () => {
it("reads the capture time and files it in the event of that time, as the server would", () => {
const at = lisbonInstant(exifDateTime(jpegWithDate("2026:10:09 20:26:47")));
expect(at).toBe("2026-10-09T19:26:47.000Z"); // Lisbon summer time
expect(exifLens(jpegWithDate("2026:10:09 20:26:47")).focalLength).toBeNull();
expect(lisbonInstant("2026:12:05 21:14:07")).toBe("2026-12-05T21:14:07.000Z");
const events = [
{ id: "braga", startsAt: "2026-10-09T19:15:00Z", ingestFrom: "2026-10-09T17:15:00Z", ingestUntil: "2026-10-09T23:15:00Z", archivedAt: null },
@@ -159,4 +160,33 @@ describe("photos arriving on this computer", () => {
// The local store then lets it go: nothing changes.
expect(libraryReducer(s, { type: "local", photos: [] }).photos.map((p) => p.id)).toEqual(["server-1"]);
});
it("reads a prime's focal length and a zoom's range from the preview", () => {
const prime = exifLens(jpegWithLens(135, 135, 135));
expect(prime.focalLength).toBe(135);
expect(prime.range).toEqual([135, 135]);
const zoom = exifLens(jpegWithLens(200, 70, 200));
expect(zoom.focalLength).toBe(200);
expect(zoom.range).toEqual([70, 200]);
});
});
/** Big-endian EXIF with FocalLength and LensSpecification (min, max, apertures). */
function jpegWithLens(focal: number, min: number, max: number): ArrayBuffer {
const u16 = (n: number) => [n >> 8, n & 0xff];
const u32 = (n: number) => [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];
const rational = (n: number) => [...u32(n), ...u32(1)];
const tiff: number[] = [0x4d, 0x4d, 0, 42, ...u32(8)];
// IFD0 at 8: ExifIFD pointer -> 26.
tiff.push(...u16(1), 0x87, 0x69, ...u16(4), ...u32(1), ...u32(26), ...u32(0));
// Exif IFD at 26: FocalLength (offset 56) and LensSpecification (offset 64).
tiff.push(...u16(2));
tiff.push(0x92, 0x0a, ...u16(5), ...u32(1), ...u32(56));
tiff.push(0xa4, 0x32, ...u16(5), ...u32(4), ...u32(64));
tiff.push(...u32(0));
tiff.push(...rational(focal));
tiff.push(...rational(min), ...rational(max), ...rational(2), ...rational(2));
const app1 = [0x45, 0x78, 0x69, 0x66, 0, 0, ...tiff];
const size = app1.length + 2;
return new Uint8Array([0xff, 0xd8, 0xff, 0xe1, size >> 8, size & 0xff, ...app1, 0xff, 0xd9]).buffer;
}
+59
View File
@@ -0,0 +1,59 @@
import type { Detection } from "../../../api/src/composition/compose.js";
import { eyeOpenness } from "../../../api/src/composition/eyeScore.js";
/**
* How open the eyes look on the head of the sharpest person, from the preview the desktop already has.
* Compared only with the other frames of the same sequence. Null when the head is too small to read.
*/
export async function eyesInPreview(jpeg: ArrayBuffer, people: readonly Detection[]): Promise<number | null> {
const person = sharpestPerson(people);
if (!person) return null;
let bitmap: ImageBitmap;
try {
bitmap = await createImageBitmap(new Blob([jpeg], { type: "image/jpeg" }), { imageOrientation: "from-image" });
} catch {
return null;
}
try {
return eyesOnBitmap(bitmap, person);
} finally {
bitmap.close();
}
}
function sharpestPerson(people: readonly Detection[]): Detection | null {
let best: Detection | null = null;
for (const person of people) {
const height = person.y1 - person.y0;
if (person.score < 0.4 || height < 0.08) continue;
if (!best) {
best = person;
continue;
}
const sharpPerson = person.sharpness ?? 1;
const sharpBest = best.sharpness ?? 1;
if (sharpPerson > sharpBest) best = person;
}
return best;
}
function eyesOnBitmap(bitmap: ImageBitmap, person: Detection): number | null {
const width = Math.round((person.x1 - person.x0) * bitmap.width);
const head = 0.35 * (person.y1 - person.y0);
const height = Math.round(head * bitmap.height);
if (width < 12 || height < 8) return null;
const left = Math.min(bitmap.width - 1, Math.max(0, Math.floor(person.x0 * bitmap.width)));
const top = Math.min(bitmap.height - 1, Math.max(0, Math.floor(person.y0 * bitmap.height)));
const cropW = Math.min(bitmap.width - left, width);
const cropH = Math.min(bitmap.height - top, height);
const canvas = document.createElement("canvas");
canvas.width = 48;
canvas.height = 32;
const ctx = canvas.getContext("2d", { willReadFrequently: true });
if (!ctx) return null;
ctx.drawImage(bitmap, left, top, cropW, cropH, 0, 0, 48, 32);
const px = ctx.getImageData(0, 0, 48, 32).data;
const grey = new Uint8Array(48 * 32);
for (let i = 0; i < grey.length; i++) grey[i] = px[i * 4] ?? 0;
return eyeOpenness(grey, 48, 32);
}
+342 -21
View File
@@ -1,4 +1,4 @@
import type { GallerySummary, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
import { controlsForModule, type GallerySummary, type LibraryMessage, type PhotoPatch, type PhotoSummary } from "@photoreport/contracts";
import { ApiError, hasRole, type DeliveryTarget, type EventSummary, type PhotoLookup } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
import { useLocation, useNavigate } from "react-router";
@@ -39,13 +39,15 @@ import { localPhotos } from "../offline/local.js";
import { isNetworkError, offlineQueue } from "../offline/queue.js";
import { ensureRoster } from "../offline/roster.js";
import { writePhotoFile } from "../desktop/lightroomSidecar.js";
import { patchPhotos, useQueueSize } from "../offline/sync.js";
import { deliver, patchPhotos, useQueueSize } from "../offline/sync.js";
import { FilterBar } from "../library/FilterBar.js";
import { SortControl } from "../library/SortControl.js";
import { sortPhotos } from "../library/sort.js";
import { LibraryMenus } from "../library/LibraryMenus.js";
import { SelectionBar } from "../library/SelectionBar.js";
import { SendButton } from "../library/SendButton.js";
import { isDesktop, prefs } from "../platform.js";
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
import { activePhoto, savedFilter, savedSort, saveFilter, saveSort, setActivePhoto } from "../library/active.js";
const PAGE = 500;
@@ -64,14 +66,26 @@ export function LibraryPage() {
const [inboxCount, setInboxCount] = useState(0);
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
const [iptcOpen, setIptcOpen] = useState(false);
const [photoMenu, setPhotoMenu] = useState<{ x: number; y: number; id: string } | null>(null);
const [photoMenu, setPhotoMenu] = useState<{ x: number; y: number; id: string | null } | null>(null);
const [eventMenu, setEventMenu] = useState<{
x: number;
y: number;
event: EventSummary | null;
where: "event" | "inbox" | "panel";
} | null>(null);
const [settingsAsk, setSettingsAsk] = useState<{ id: string; n: number } | null>(null);
const [autopilotAsk, setAutopilotAsk] = useState<{ id: string; n: number } | null>(null);
const clearSettingsAsk = useCallback(() => setSettingsAsk(null), []);
const clearAutopilotAsk = useCallback(() => setAutopilotAsk(null), []);
const [dropPartial, setDropPartial] = useState(false);
const { open: openFolderScan, syncGames } = useFolderScan();
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
const [sort, setSortState] = useState(() => savedSort(orgId));
const [players, setPlayers] = useState<PlayerPick[]>([]);
const onPlayers = useCallback((next: PlayerPick[]) => setPlayers((cur) => (samePicks(cur, next) ? cur : next)), []);
useEffect(() => setFilterState(savedFilter(orgId)), [orgId]);
useEffect(() => setSortState(savedSort(orgId)), [orgId]);
const setFilter = useCallback(
(f: LibraryFilter) => {
setFilterState(f);
@@ -79,6 +93,13 @@ export function LibraryPage() {
},
[orgId],
);
const setSort = useCallback(
(next: typeof sort) => {
setSortState(next);
saveSort(orgId, next);
},
[orgId],
);
const [loupe, setLoupe] = useState(false);
const [creating, setCreating] = useState(false);
const [view, setView] = useState<"grid" | "faces">("grid");
@@ -356,7 +377,14 @@ export function LibraryPage() {
syncGames(games);
}, [events, openEvent, syncGames]);
const playerIds = useMemo(() => photoIdsOf(players), [players]);
const visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter) && (playerIds === null || playerIds.has(p.id))), [state.photos, filter, playerIds]);
const visible = useMemo(() => {
const matched = state.photos.filter((photo) => {
if (!matchesFilter(photo, filter)) return false;
if (playerIds === null) return true;
return playerIds.has(photo.id);
});
return sortPhotos(matched, sort);
}, [state.photos, filter, playerIds, sort]);
const selectedPlayerIds = useMemo(() => players.map((p) => p.id), [players]);
useEffect(() => {
setPlayers([]);
@@ -364,7 +392,10 @@ export function LibraryPage() {
useEffect(() => {
if (!playerIds) return;
if (state.focus && playerIds.has(state.focus)) return;
const next = state.photos.filter((p) => playerIds.has(p.id) && matchesFilter(p, filter));
const next = sortPhotos(
state.photos.filter((p) => playerIds.has(p.id) && matchesFilter(p, filter)),
sort,
);
const first = next[0];
if (!first) return;
dispatch({ type: "select", id: first.id, mode: "single", visible: next.map((p) => p.id) });
@@ -492,10 +523,15 @@ export function LibraryPage() {
const onPhotoMenu = useCallback(
(id: string, e: React.MouseEvent) => {
if (!state.selected.has(id)) dispatch({ type: "select", id, mode: "single", visible: visibleIds });
setEventMenu(null);
setPhotoMenu({ x: e.clientX, y: e.clientY, id });
},
[state.selected, visibleIds],
);
const onGridMenu = useCallback((e: React.MouseEvent) => {
setEventMenu(null);
setPhotoMenu({ x: e.clientX, y: e.clientY, id: null });
}, []);
// Face boxes and names over the loupe.
useEffect(() => {
setLoupeFaces([]);
@@ -515,16 +551,145 @@ export function LibraryPage() {
const srcFor = useCallback((p: PhotoSummary) => api.absolute(p.urls.thumb), [api]);
const sendSelectionTo = useCallback(
async (targetId: string) => {
const ids = selection.filter((p) => p.flag !== "REJECT" && p.status === "READY").map((p) => p.id);
if (!ids.length) {
setInfo(t.photoMenuNothingToSend);
setTimeout(() => setInfo(null), 4000);
return;
}
try {
const result = await deliver(api, orgId, targetId, ids);
if (result.waiting) setInfo(t.offline.queuedDelivery);
else setInfo(t.delivered(result.queued.length, result.skipped.length));
} catch (err) {
if (err instanceof ApiError) setInfo(err.code);
else setInfo(t.unexpectedError);
}
setTimeout(() => setInfo(null), 4000);
},
[api, orgId, selection],
);
const applyDevelop = useCallback(async () => {
if (!focus || selection.length < 2) return;
const controlIds = controlsForModule("basic").map((control) => control.id);
const commands = await commandsForPhoto(api, focus.id, controlIds, false);
const ids = selection.map((p) => p.id).filter((id) => id !== focus.id);
if (!commands.length || !ids.length) return;
queueSync(orgId, ids, commands);
await offlineQueue(orgId).flush(api);
setInfo(t.dev.synced(ids.length));
setTimeout(() => setInfo(null), 4000);
}, [api, focus, orgId, selection]);
const toggleArchive = useCallback(
async (event: EventSummary) => {
try {
const saved = await api.updateEvent(event.id, { archived: !event.archivedAt });
if (saved.archivedAt) {
setEvents((list) => list.filter((item) => item.id !== saved.id));
setArchivedEvents((list) => {
if (!list) return list;
return [saved, ...list.filter((item) => item.id !== saved.id)];
});
if (state.scope === saved.id) {
setSheet(null);
void open("inbox");
}
} else {
setEvents((list) => [saved, ...list.filter((item) => item.id !== saved.id)]);
setArchivedEvents((list) => (list ? list.filter((item) => item.id !== saved.id) : list));
}
} catch (err) {
if (err instanceof ApiError) setError(t.eventSettings.errors[err.code] ?? err.code);
else setError(t.unexpectedError);
}
},
[api, open, state.scope],
);
const moveSelectionTo = useCallback(
(event: EventSummary) => {
const ids = selection.map((p) => p.id);
if (!ids.length) return;
void api.updatePhotos(orgId, ids, { eventId: event.id }).then(
() => {
dispatch({ type: "patch", ids, patch: { eventId: event.id } });
setInfo(t.movedToEvent(ids.length, event.title));
setTimeout(() => setInfo(null), 4000);
},
() => setError(t.unexpectedError),
);
},
[orgId, selection, api],
);
const photoMenuActions = useMemo((): PhotoMenuAction[] => {
if (!photoMenu || !canCull) return [];
if (!photoMenu) return [];
if (!photoMenu.id) {
return [
{
id: "all",
label: t.photoMenuSelectAll,
onSelect: () => dispatch({ type: "selectAll", visible: visibleIds }),
},
{
id: "none",
label: t.photoMenuSelectNone,
onSelect: () => dispatch({ type: "selectAll", visible: [] }),
},
];
}
const ids = selection.map((p) => p.id);
const inEvent = isEventScope(state.scope);
const actions: PhotoMenuAction[] = [
{ id: "pick", label: t.photoMenuPick, onSelect: () => void patch(ids, { flag: "PICK" }) },
{ id: "reject", label: t.photoMenuReject, onSelect: () => void patch(ids, { flag: "REJECT" }) },
{ id: "clear", label: t.photoMenuClear, onSelect: () => void patch(ids, { flag: "NONE" }) },
{ id: "info", label: t.photoMenuInfo, onSelect: () => setIptcOpen(true) },
];
const actions: PhotoMenuAction[] = [];
if (canCull) {
actions.push(
{ id: "pick", label: t.photoMenuPick, onSelect: () => void patch(ids, { flag: "PICK" }) },
{ id: "reject", label: t.photoMenuReject, onSelect: () => void patch(ids, { flag: "REJECT" }) },
{ id: "clear", label: t.photoMenuClear, onSelect: () => void patch(ids, { flag: "NONE" }) },
);
if (targets.length) {
actions.push({
id: "send",
label: t.photoMenuSend,
items: targets.map((target) => ({
id: `send-${target.id}`,
label: target.name,
onSelect: () => void sendSelectionTo(target.id),
})),
});
} else {
actions.push({
id: "send-setup",
label: t.setUpDelivery,
onSelect: () => navigate("/delivery"),
});
}
const destinations = events.filter((event) => event.id !== state.scope && !event.archivedAt);
const canMove = !!destinations.length && !state.scope?.startsWith("search:") && !state.scope?.startsWith("face:");
if (canMove) {
actions.push({
id: "move",
label: t.photoMenuMove,
items: destinations.map((event) => ({
id: `move-${event.id}`,
label: event.title,
onSelect: () => moveSelectionTo(event),
})),
});
}
if (focus && selection.length > 1) {
actions.push({
id: "apply-develop",
label: t.photoMenuApplyDevelop,
onSelect: () => void applyDevelop(),
});
}
}
actions.push({ id: "info", label: t.photoMenuInfo, onSelect: () => setIptcOpen(true) });
if (loupe) {
actions.push({ id: "grid", label: t.photoMenuGrid, onSelect: () => setLoupe(false) });
} else if (focus) {
@@ -535,11 +700,130 @@ export function LibraryPage() {
onSelect: () => navigate(`/develop/${focus.id}`),
});
}
if (inEvent) {
actions.push({ id: "remove", label: t.photoMenuRemove, danger: true, onSelect: () => setRemoveOpen(true) });
if (canCull && inEvent) {
actions.push({
id: "remove",
label: t.photoMenuRemove,
danger: true,
onSelect: () => setRemoveOpen(true),
});
}
return actions;
}, [photoMenu, canCull, selection, state.scope, loupe, focus, patch, navigate]);
}, [
photoMenu,
canCull,
selection,
state.scope,
loupe,
focus,
patch,
navigate,
targets,
events,
visibleIds,
sendSelectionTo,
moveSelectionTo,
applyDevelop,
]);
const eventMenuActions = useMemo((): PhotoMenuAction[] => {
if (!eventMenu) return [];
const actions: PhotoMenuAction[] = [];
const event = eventMenu.event;
if (eventMenu.where === "panel") {
if (canCreate) {
actions.push({ id: "new", label: t.newEvent, onSelect: () => setCreating(true) });
}
if (canCreate) {
actions.push({
id: "archived",
label: archivedEvents ? t.eventsList.hideArchived : t.eventsList.archived,
onSelect: () => {
if (archivedEvents) {
setArchivedEvents(null);
return;
}
api.listEvents(orgId, { archived: true }).then(
(r) => setArchivedEvents(r.events),
() => setArchivedEvents([]),
);
},
});
}
return actions;
}
if (eventMenu.where === "inbox") {
actions.push({
id: "open",
label: t.eventMenuOpen,
onSelect: () => {
setSheet(null);
void open("inbox");
},
});
if (canCreate) actions.push({ id: "new", label: t.newEvent, onSelect: () => setCreating(true) });
return actions;
}
if (!event) return actions;
actions.push({
id: "open",
label: t.eventMenuOpen,
onSelect: () => {
setSheet(null);
void open(event.id);
},
});
if (canCreate) {
actions.push({
id: "settings",
label: t.eventMenuSettings,
onSelect: () => {
if (state.scope !== event.id) {
setSheet(null);
void open(event.id);
}
setSettingsAsk({ id: event.id, n: Date.now() });
},
});
}
if (canCull) {
actions.push({
id: "autopilot",
label: t.eventMenuAutopilot,
onSelect: () => {
if (state.scope !== event.id) {
setSheet(null);
void open(event.id);
}
setAutopilotAsk({ id: event.id, n: Date.now() });
},
});
}
if (desktop && !event.archivedAt) {
if (localFtp.target?.id === event.id) {
actions.push({
id: "ftp-stop",
label: t.eventMenuFtpStop,
onSelect: () => localFtp.setTarget(null),
});
} else {
actions.push({
id: "ftp",
label: t.eventMenuFtp,
onSelect: () => localFtp.setTarget(event),
});
}
}
if (canCreate) {
actions.push({
id: "archive",
label: event.archivedAt ? t.eventSettings.unarchive : t.eventSettings.archive,
onSelect: () => void toggleArchive(event),
});
actions.push({ id: "new", label: t.newEvent, onSelect: () => setCreating(true) });
}
return actions;
}, [eventMenu, canCreate, canCull, archivedEvents, api, orgId, open, desktop, localFtp, toggleArchive, state.scope]);
if (!organization) return <p className="p-6 text-sm text-muted">{t.noAccess}</p>;
const picks = state.photos.filter((p) => p.flag === "PICK").length;
@@ -565,6 +849,18 @@ export function LibraryPage() {
else api.listEvents(orgId, { archived: true }).then((r) => setArchivedEvents(r.events), () => setArchivedEvents([]));
},
})}
onEventMenu={(event, e) => {
setPhotoMenu(null);
setEventMenu({ x: e.clientX, y: e.clientY, event, where: "event" });
}}
onInboxMenu={(e) => {
setPhotoMenu(null);
setEventMenu({ x: e.clientX, y: e.clientY, event: null, where: "inbox" });
}}
onPanelMenu={(e) => {
setPhotoMenu(null);
setEventMenu({ x: e.clientX, y: e.clientY, event: null, where: "panel" });
}}
/>
<div className="flex min-h-[70vh] min-w-0 flex-1 flex-col lg:min-h-0">
@@ -593,6 +889,7 @@ export function LibraryPage() {
/>
)}
<FilterBar filter={filter} onChange={setFilter} />
<SortControl sort={sort} onChange={setSort} />
{players.length > 0 && (
<span className="flex min-w-0 items-center gap-2">
<span className="max-w-72 truncate text-ink" title={players.map((p) => p.name).join(", ")}>
@@ -662,13 +959,23 @@ export function LibraryPage() {
void loadEvents();
void open("inbox");
}}
settingsAsk={settingsAsk}
onAsked={clearSettingsAsk}
/>
)}
{canCull && openEvent && (
<SquadsButton api={api} event={openEvent} canEdit={canCreate} facesTick={facesTick} selectedIds={selectedPlayerIds} onPlayers={onPlayers} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
)}
{canCull && openEvent && (
<AutopilotButton api={api} event={openEvent} targets={targets} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
<AutopilotButton
api={api}
event={openEvent}
targets={targets}
canEdit={canCreate}
autopilotAsk={autopilotAsk}
onAsked={clearAutopilotAsk}
onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))}
/>
)}
<span className="ml-auto flex items-center">
{canCull && !sheet && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
@@ -897,7 +1204,7 @@ export function LibraryPage() {
total={visibleIds.length}
faces={loupeFaces}
onClose={() => setLoupe(false)}
{...(canCull ? { onMenu: onPhotoMenu } : {})}
onMenu={onPhotoMenu}
/>
) : visible.length || suggested.length ? (
<>
@@ -910,7 +1217,8 @@ export function LibraryPage() {
onPick={onPick}
onSelectMany={(ids, focus) => dispatch({ type: "selectMany", ids, focus })}
onOpen={onOpenLoupe}
{...(canCull ? { onMenu: onPhotoMenu } : {})}
onMenu={onPhotoMenu}
onBackgroundMenu={onGridMenu}
/>
{suggested.length > 0 && (
<div className="border-t border-line">
@@ -944,8 +1252,21 @@ export function LibraryPage() {
y={photoMenu.y}
actions={photoMenuActions}
onClose={() => setPhotoMenu(null)}
onColor={(color) => void patch(selection.map((p) => p.id), { colorLabel: color })}
onRating={(rating) => void patch(selection.map((p) => p.id), { rating })}
{...(photoMenu.id && canCull
? {
onColor: (color: PhotoSummary["colorLabel"]) => void patch(selection.map((p) => p.id), { colorLabel: color }),
onRating: (rating: number) => void patch(selection.map((p) => p.id), { rating }),
}
: {})}
/>
)}
{eventMenu && eventMenuActions.length > 0 && (
<PhotoContextMenu
label={t.eventMenu}
x={eventMenu.x}
y={eventMenu.y}
actions={eventMenuActions}
onClose={() => setEventMenu(null)}
/>
)}
{removeOpen && isEventScope(state.scope) && (
+27 -12
View File
@@ -25,9 +25,13 @@ Following the AP and NPPA codes:
face sits behind. With no usable point, the subject is the sharp person with a face, not the biggest one. With
a ball in play, the ball and everyone contesting it come along. Without one, the subject and the sharp people
with them (a duel, a celebration, a line-up). Non-person photos (empty pitch, kit detail) are unchanged.
- **Who is not the subject:** they are in whole, or they are out. A person the photo has already cut in half
stays out when the crop can move into the clean space around the subject. When leaving them out would cut the
subject or the ball, the crop does the best it can. The subject themselves may stand at the frame edge.
- **Who is not the subject:** they are in whole, or they are out. A player who is large in the frame (close
to the camera, or nearly as tall as the subject) is part of the photograph: the crop does not throw them out
and does not cut through them. If keeping those players means there is nothing to crop, the photo stays as
shot. A small figure in the background, a blurred body in front, and a person the photo has already cut in
half may stay out. When leaving them out would cut the subject or the ball, the crop does the best it can.
The subject themselves may stand at the frame edge. A correction learnt from other photos must not chop a
player this frame had kept whole.
- **The ball depends on the sport** of the event. Handball plays the ball in the hands or in the air. A ball
below the knee is on the floor: it does not frame the photo, even when it overlaps the player's legs and sits
closer to the middle of the body. Football plays the ball on the ground, so the ball at the feet is the one
@@ -43,9 +47,16 @@ Following the AP and NPPA codes:
mid-thigh when the foot already leaves the photo. The face is big (a median face of 14% of the frame height)
near the top.
- **"full"** keeps whole bodies when they fit: Peter's usual crop, about two thirds of the frame.
- **Reportage** keeps a whole hand and a whole foot when they are in the photo. The sports framing on the event
is ignored. A person the frame has already cut in half is not pulled into the subject: half a body at the
edge is background, and the crop leaves it out whenever it can.
- **Reportage** reads the shot the way a picture editor does, and trusts the framing. A long shot (the person
under half the picture) is the place. A full-length, or a conversation whose bodies are whole, is already the
photograph: the space around them was left on purpose, and it is not closed to match a sports fill. A prime of
100mm or longer is the exception on a single full-length: that lens cannot zoom, so the crop may step in to
about 85% of the frame, still centred on the photograph. A zoom (even at 200mm) is not that exception — the
photographer could have zoomed, so the space stays. A long shot and a group stay on a prime too. A frame the
camera already cut (the feet leave the picture, and the person is large) is only finished, at mid-limb, and a
person the frame already cut off at the edge is left out. The sports framing on the event is ignored, including
a crop learnt from matches. A later frame of that moment may still be a half or a three-quarter. A whole hand
and a whole foot stay in. A person the frame has already cut in half is not pulled into the subject.
- **Never cut:** heads, faces, a hand or a foot that is whole in the photo, hands holding the ball, the ball itself.
A person who is in the crop keeps their head, including someone a little less sharp stood in the shade. In
reportage the people of a conversation are one subject, so the crop is built around all of them.
@@ -89,9 +100,10 @@ A camera at 10–30 frames per second sends several photos of the same moment.
frame and near the subject, faces visible. Ties go to the earliest frame (usually the peak of the action).
- **Facing and eyes:** inside one burst, a frame of a player from behind loses to a frame where the face is
visible, and shut eyes lose to open ones. Open eyes always win when the burst has both — including a shot or a
grimace: if another frame of the same moment has the eyes open, that one is kept. If every frame is a back, or
the eyes cannot be told apart, the sharpest frame stays. A back is not dropped from the match when it is the
only picture of that moment. One closed face in a group is enough to lose the frame in reportage.
grimace, and including when the blink is sharper: if another frame of the same moment has the eyes open, that
one is kept. If every frame is a back, or the eyes cannot be told apart, the sharpest frame stays. A back is
not dropped from the match when it is the only picture of that moment. One closed face in a group is enough to
lose the frame in reportage.
- **No usable face:** do not pick a frame whose subject has no clear face when the same burst has one that does.
A photo that is not of a person (empty pitch, kit detail) is unchanged.
- **Keep:** the best 1–2 frames per burst (configurable), flagged as picks. The rest stay unflagged (never
@@ -118,9 +130,12 @@ is, in order:
as picks;
3. **only the picks** are edited: white balance, tone, level (horizon or verticals, at most a few degrees), crop,
and the finishing look. The rest of the sequence stays as shot (and need not be uploaded for that decision).
The level reads the advertising boards, stands, posts and railings first, never the pitch markings (lines on
grass), which perspective tilts; when those disagree it falls back to a general Level; when nothing agrees
the photo is left as it is;
The level uses the camera's own roll when the file still has it (Canon LevelInfo, the viewfinder level).
A level camera stays level: a brick wall must not tilt the frame. With no roll in the file, the level reads
the advertising boards, stands, posts and railings, 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. A ball in play stays inside the crop, including one in an outstretched hand. Leaving it
outside is the same as cutting it;
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.
+2
View File
@@ -8,4 +8,6 @@ the external authentication hook (`/v1/sftpgo/auth`), against the FTP logins and
name and renames when complete, so the worker never sees half a file).
2. Set the same random key (24+ characters) in the hook URL and in `apps/api/.env` as `SFTPGO_HOOK_KEY`.
3. Open FTP 21 and the passive range in the firewall; set `force_passive_ip` to the public address if behind NAT.
`max_per_host_connections` and `max_total_connections` are 0 (no cap). SFTPGo's own default is 20 per address,
which refuses a camera that already has several connections open. A logged-in camera is not limited here.
4. In the app (Metadados -> Logins FTP), create a login per camera body; the password is shown once.
+3 -1
View File
@@ -1,7 +1,9 @@
{
"common": {
"upload_mode": 1,
"setstat_mode": 1
"setstat_mode": 1,
"max_total_connections": 0,
"max_per_host_connections": 0
},
"ftpd": {
"bindings": [{ "port": 21, "force_passive_ip": "", "passive_connections_security": 1 }],
+3
View File
@@ -125,7 +125,10 @@ export interface PhotoSummary {
delivery?: PhotoDelivery;
width: number | null;
height: number | null;
/** When the shutter fired. Null when the file has no capture time. */
capturedAt: string | null;
/** When the file arrived in the library. Missing on copies cached before this was sent. */
createdAt?: string;
cameraModel: string | null;
lens: string | null;
focalLength: number | null;
+1 -1
View File
@@ -66,7 +66,7 @@ export function renderFileName(template: string, vars: TemplateVars, originalFil
}
/**
* Subfolders for the local copy of an export: the capture day, the game, and the destination's name
* Subfolders for the local copy of an export: the event's day, the game, and the destination's name
* (`20261018 - Águas Santas Milaneza x Sporting CP - Record`). `{destination}` is filled only for that copy.
*/
export const LOCAL_COPY_FOLDER = "/{iptcdate} - {event} - {destination}/";
+29 -1
View File
@@ -3,7 +3,7 @@ import { applyTemplate, toExiftoolArgs } from "./iptc.js";
import { PathTemplateError, renderFileName, renderFolder } from "./paths.js";
import { PM_VARIABLE_NAMES } from "./pmvars.js";
import { badModifiers, render } from "./template.js";
import { buildVars } from "./vars.js";
import { buildVars, folderDay, withEventDay } from "./vars.js";
describe("Photo Mechanic variables", () => {
const event = { home: "ABC Braga", away: "CDE Gil Eanes", startsAt: new Date("2026-10-11T17:00:00Z") };
@@ -15,6 +15,34 @@ describe("Photo Mechanic variables", () => {
expect(renderFileName("{initials}_{datesort}_{originalName}", vars, "IMG_1234.JPG")).toBe("PS_20261011_IMG_1234.jpg");
});
it("keeps a match on the event day when the photo is sent after midnight", () => {
const match = { home: "FC Porto", away: "USC Paredes", startsAt: new Date("2026-11-20T20:45:00Z") };
const shot = buildVars(match, { capturedAt: new Date("2026-11-21T00:14:00Z") }, "Victor Sousa");
const now = new Date("2026-11-21T00:30:00Z");
const day = folderDay(
{ startsAt: match.startsAt, endsAt: new Date("2026-11-21T00:45:00Z"), match: true },
now,
);
const folderVars = withEventDay(shot, day);
expect(renderFolder("/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}", folderVars)).toBe(
"/fotografia/2026.11.20 FC Porto x USC Paredes/",
);
expect(renderFolder("/{iptcdate} - {event}", folderVars)).toBe("/20261120 - FC Porto x USC Paredes/");
expect(shot.iptcdate).toBe("20261121");
expect(folderVars.timesort).toBe(shot.timesort);
expect(renderFileName("PS_{event}_{timesort}", shot, "R3VS5056.JPG")).toBe("PS_FC Porto x USC Paredes_00140000.jpg");
});
it("uses the current day only when the event itself runs for several days", () => {
const camp = { home: "Estágio", away: "", startsAt: new Date("2026-11-20T10:00:00Z") };
const endsAt = new Date("2026-11-22T18:00:00Z");
const shot = buildVars(camp, { capturedAt: new Date("2026-11-21T15:00:00Z") });
const saturday = folderDay({ startsAt: camp.startsAt, endsAt, match: false }, new Date("2026-11-21T15:10:00Z"));
const sunday = folderDay({ startsAt: camp.startsAt, endsAt, match: false }, new Date("2026-11-22T11:00:00Z"));
expect(renderFolder("/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}", withEventDay(shot, saturday))).toBe("/2026.11.21 Estágio/");
expect(renderFolder("/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}", withEventDay(shot, sunday))).toBe("/2026.11.22 Estágio/");
});
it("falls back to the event day without a capture time", () => {
const v = buildVars(event, {});
expect(v.datesort).toBe("20261011");
+70
View File
@@ -581,5 +581,75 @@ export function pmVars(photo: PmPhoto = {}, iptc: PmIptc = {}, opts: { now?: Dat
return out;
}
/**
* The calendar day of `at` in Lisbon, under the folder date names ({date}, {iptcdate}, {year4}...).
* The clock time of the shot is not included: a folder stays on one day.
*/
export function eventDayFields(at: Date): Record<string, string> {
const w = wall(at);
const values: Record<string, string | undefined> = { ...dateVars(w), ...iptcDateVars(w) };
const aliases: Record<string, string[]> = {
date: ["shot"],
datemil: ["datm"],
datesort: ["dats"],
datesortdash: ["dtsd"],
month: ["mn"],
month0: ["mn0"],
monthname: ["mnn"],
monthname3: ["mnn3"],
monthnameap: ["mnap"],
year2: ["yr2"],
year4: ["yr4"],
iptcdate: ["idat"],
iptcday: ["iday"],
iptcday0: ["idy0"],
iptcdow: ["idow"],
iptcdow3: ["idw3"],
iptcmonth: ["imn"],
iptcmonth0: ["imn0"],
iptcmonthname: ["imnn"],
iptcyear2: ["iyr2"],
iptcyear4: ["iyr4"],
};
const dayNames = [
"date",
"datemil",
"datesort",
"datesortdash",
"day",
"day0",
"dow",
"dow3",
"month",
"month0",
"monthname",
"monthname3",
"monthnameap",
"year2",
"year4",
"iptcdate",
"iptcday",
"iptcday0",
"iptcdow",
"iptcdow3",
"iptcmonth",
"iptcmonth0",
"iptcmonthname",
"iptcmonthname3",
"iptcmonthnameap",
"iptcyear2",
"iptcyear4",
];
const out: Record<string, string> = {};
for (const name of dayNames) {
const value = values[name];
if (!value) continue;
out[name] = value;
const shorts = aliases[name] ?? [];
for (const alias of shorts) out[alias] = value;
}
return out;
}
/** Every Photo Mechanic variable name (and short name) this module knows. */
export const PM_VARIABLE_NAMES: ReadonlySet<string> = new Set(Object.keys(pmVars({ capturedAt: new Date(0) })));
+50 -1
View File
@@ -1,4 +1,4 @@
import { type PmIptc, type PmPhoto, pmVars } from "./pmvars.js";
import { eventDayFields, type PmIptc, type PmPhoto, pmVars } from "./pmvars.js";
import type { TemplateVars } from "./template.js";
/** What an event knows about itself; filled by an admin or editor when the event is created. */
@@ -121,6 +121,55 @@ export function buildVars(event: EventInfo, photo: PhotoInfo = {}, photographer?
return out;
}
/** What a folder needs to choose its day. A match is one day. Anything else may run for several days. */
export interface FolderSpan {
startsAt: Date;
/** When the event stops taking photos. Missing means a single day. */
endsAt?: Date | undefined;
/** Home and away, or a fixture. A match stays on its start day after midnight. */
match?: boolean | undefined;
}
/** A finish before this hour, Lisbon, is still the previous day's job (a match that runs past midnight). */
const NEXT_MORNING_HOUR = 6;
function calendarDay(at: Date): { y: number; m: number; d: number; hh: number } {
const p = parts(at);
return { y: Number(p.y), m: Number(p.m), d: Number(p.d), hh: Number(p.hh) };
}
/** True when the window is a real second day, not a single job that finishes in the early morning. */
function coversSeveralDays(startsAt: Date, endsAt: Date): boolean {
const start = calendarDay(startsAt);
const end = calendarDay(endsAt);
const startIndex = Date.UTC(start.y, start.m - 1, start.d);
const endIndex = Date.UTC(end.y, end.m - 1, end.d);
const days = Math.round((endIndex - startIndex) / 86_400_000);
if (days <= 0) return false;
if (days === 1 && end.hh < NEXT_MORNING_HOUR) return false;
return true;
}
/**
* The day written into a folder.
* A match, and any event that is only one day, keeps the event's start day.
* An event that runs for several days uses the day the folder is created.
*/
export function folderDay(span: FolderSpan, now: Date): Date {
if (span.match) return span.startsAt;
if (!span.endsAt) return span.startsAt;
if (!coversSeveralDays(span.startsAt, span.endsAt)) return span.startsAt;
return now;
}
/**
* Folder names use `day` for {iptcdate}, {iptcyear4} and the other day fields.
* The file name keeps the shot's own clock ({timesort}).
*/
export function withEventDay(vars: TemplateVars, day: Date): TemplateVars {
return { ...vars, ...eventDayFields(day) };
}
/** Capture time in Lisbon wall-clock time with its offset, for IPTC DateCreated/TimeCreated. */
export function createdStamp(at: Date): { date: string; time: string; iso: string } {
const p = parts(at);