Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91bc9aefc7 | ||
|
|
6ba556ba9f | ||
|
|
f36da3408b | ||
|
|
0fa7c91366 | ||
|
|
a9d89eae19 | ||
|
|
3db365452f | ||
|
|
88cd74f5ff | ||
|
|
52fe4b67db | ||
|
|
c922e21cc6 | ||
|
|
e77bbfcf53 | ||
|
|
5052fd5c92 | ||
|
|
c9dc67b1eb | ||
|
|
72bc65cf6e | ||
|
|
f04b61e279 | ||
|
|
1fb6ca171d | ||
|
|
c94696ee53 | ||
|
|
88e74d34ba | ||
|
|
7813475a7c | ||
|
|
7d597e05f5 |
No files matched your search
@@ -32,6 +32,17 @@ Read `docs/ARCHITECTURE.md` before any task. One task id per branch/PR (`task/BI
|
||||
13. **Prefer Rust for local heavy work.** Detection, measure, level, develop and anything CPU-bound on the
|
||||
desktop should live in `engine/` (native / WASM), not in ad-hoc TypeScript, when practical. TypeScript
|
||||
orchestrates; Rust does the pixels and the scores. Safer, faster, one implementation with the workers.
|
||||
14. **Start from the latest `origin/main`.** Paperclip, Claude Code and Cursor fetch and fast-forward this
|
||||
checkout before editing. Do not leave the work only on an old branch or another folder. A pinned engine
|
||||
revision is the LightCraft `rev` in the root `Cargo.toml`, not a stale checkout of this repo.
|
||||
15. **The photograph's aspect is not a dial.** The autopilot and every automatic file write keep the original
|
||||
aspect (`docs/photo-editing-rules.md`). A straightened crop is written as the corners Lightroom turns back
|
||||
around the crop centre (`apps/app/src/desktop/lightroomCrop.ts`). Writing the levelled rectangle plus the
|
||||
angle makes Lightroom show Custom. Do not invent another ratio to satisfy a framing rule.
|
||||
16. **Lightroom round-trip is the file, not the catalog.** While the desktop app is open it reads crop, pick,
|
||||
stars and colour back from the work-folder original and sends them to the server. Exposure and the other
|
||||
develop sliders are written out and are not read back. A change that Lightroom has not written into the
|
||||
file is invisible. Newsroom fields (caption, title, keywords, creator) go on the first `rdf:Description`.
|
||||
|
||||
## Porting from the old projects
|
||||
|
||||
|
||||
@@ -61,4 +61,15 @@ describe("sequence choice", () => {
|
||||
const pool = rankForPick(frames, weights, (frame) => frame.score >= 8);
|
||||
expect(pool.map((frame) => frame.id)).toEqual(["b"]);
|
||||
});
|
||||
|
||||
it("prefers a sharp clear face over an occluded one when the burst has a choice", () => {
|
||||
const weights = sequenceWeight([
|
||||
{ facing: 1, eyes: 0.7, faceSharp: true, occluded: true },
|
||||
{ facing: 1, eyes: 0.7, faceSharp: true, occluded: false },
|
||||
]);
|
||||
expect(weights[0]!).toBeLessThan(0.1);
|
||||
expect(weights[1]).toBe(1);
|
||||
const onlyOccluded = sequenceWeight([{ facing: 1, eyes: null, faceSharp: true, occluded: true }]);
|
||||
expect(onlyOccluded[0]).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -47,6 +47,37 @@ function subjectOf(autopilot: unknown): Box | null {
|
||||
return s;
|
||||
}
|
||||
|
||||
function ballOf(autopilot: unknown): Box | null {
|
||||
const b = (autopilot as { ball?: Box } | null)?.ball;
|
||||
if (!b || typeof b.x0 !== "number" || typeof b.y0 !== "number" || typeof b.x1 !== "number" || typeof b.y1 !== "number") return null;
|
||||
return b;
|
||||
}
|
||||
|
||||
function peopleOf(autopilot: unknown): Box[] {
|
||||
const raw = (autopilot as { peopleBoxes?: Box[] } | null)?.peopleBoxes;
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.filter((p) => p && typeof p.x0 === "number" && typeof p.y0 === "number" && typeof p.x1 === "number" && typeof p.y1 === "number");
|
||||
}
|
||||
|
||||
/** Face covered by another body or the ball (docs/photo-editing-rules.md §3). */
|
||||
function faceOccluded(face: Box, subject: Box | null, people: Box[], ball: Box | null): boolean {
|
||||
const faceArea = area(face);
|
||||
if (faceArea <= 0) return false;
|
||||
if (ball) {
|
||||
const share = overlap(face, ball) / faceArea;
|
||||
if (share > 0.18) return true;
|
||||
}
|
||||
for (const p of people) {
|
||||
if (subject && overlap(p, subject) / Math.max(area(subject), 1e-9) > 0.7) continue;
|
||||
const share = overlap(face, p) / faceArea;
|
||||
if (share < 0.2) continue;
|
||||
// Covering the centre of the face, not just brushing the cheek in a duel.
|
||||
const mid = { x0: face.x0 + 0.25 * (face.x1 - face.x0), y0: face.y0 + 0.25 * (face.y1 - face.y0), x1: face.x1 - 0.25 * (face.x1 - face.x0), y1: face.y1 - 0.25 * (face.y1 - face.y0) };
|
||||
if (overlap(mid, p) / Math.max(area(mid), 1e-9) > 0.35) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function facingOf(subject: Box | null, faces: FaceBox[], done: boolean): 0 | 1 | null {
|
||||
if (!done) return null;
|
||||
const clear = faces.filter((f) => f.sharpness == null || f.sharpness >= MIN_SHARPNESS);
|
||||
@@ -119,11 +150,21 @@ export async function sequenceWeights(db: Db, photos: readonly LookPhoto[], gapM
|
||||
const own = byPhoto.get(frame.id) ?? [];
|
||||
const subject = subjectOf(frame.autopilot);
|
||||
const facing = facingOf(subject, own, frame.facesStatus === "DONE");
|
||||
looks.set(frame.id, { facing, eyes: null });
|
||||
const face = faceForEyes(subject, own);
|
||||
let faceSharp: boolean | null = null;
|
||||
let occluded: boolean | null = null;
|
||||
if (facing === 1 && face) {
|
||||
faceSharp = face.sharpness == null || face.sharpness >= MIN_SHARPNESS;
|
||||
occluded = faceOccluded(face, subject, peopleOf(frame.autopilot), ballOf(frame.autopilot));
|
||||
} else if (facing === 0) {
|
||||
faceSharp = false;
|
||||
occluded = null;
|
||||
}
|
||||
looks.set(frame.id, { facing, eyes: null, faceSharp, occluded });
|
||||
if (!preview || facing !== 1) continue;
|
||||
// Reportage: the most closed face in the group. A match: the sharpest face on the subject.
|
||||
const chosen = reportage ? facesOnSubject(subject, own) : [faceForEyes(subject, own)].filter((f): f is FaceBox => !!f);
|
||||
for (const face of chosen) jobs.push({ photo: frame, face });
|
||||
const chosen = reportage ? facesOnSubject(subject, own) : [face].filter((f): f is FaceBox => !!f);
|
||||
for (const f of chosen) jobs.push({ photo: frame, face: f });
|
||||
}
|
||||
}
|
||||
const eyes = new Map<string, number | null>();
|
||||
@@ -142,8 +183,13 @@ export async function sequenceWeights(db: Db, photos: readonly LookPhoto[], gapM
|
||||
for (const burst of groupBursts(frames, gapMs)) {
|
||||
if (burst.length < 2) continue;
|
||||
const rows = burst.map((frame) => {
|
||||
const look = looks.get(frame.id) ?? { facing: null, eyes: null };
|
||||
return { facing: look.facing, eyes: eyes.get(frame.id) ?? null };
|
||||
const look = looks.get(frame.id) ?? { facing: null, eyes: null, faceSharp: null, occluded: null };
|
||||
return {
|
||||
facing: look.facing,
|
||||
eyes: eyes.get(frame.id) ?? null,
|
||||
faceSharp: look.faceSharp ?? null,
|
||||
occluded: look.occluded ?? null,
|
||||
};
|
||||
});
|
||||
const weights = sequenceWeight(rows, reportage);
|
||||
burst.forEach((frame, i) => out.set(frame.id, weights[i] ?? 1));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* 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.
|
||||
* A sharp clear face beats a soft or occluded one when the burst has a choice.
|
||||
*/
|
||||
|
||||
export interface SequenceLook {
|
||||
@@ -8,6 +9,10 @@ export interface SequenceLook {
|
||||
facing: 0 | 1 | null;
|
||||
/** Higher means the eyes look more open. null: not measured. */
|
||||
eyes: number | null;
|
||||
/** Face on the subject is sharp enough. null: unknown. */
|
||||
faceSharp?: boolean | null;
|
||||
/** Face covered by another body or the ball. null: unknown. */
|
||||
occluded?: boolean | null;
|
||||
}
|
||||
|
||||
/** Below this, eyes count as shut when another frame in the burst is clearly more open. */
|
||||
@@ -24,11 +29,16 @@ export function sequenceWeight(frames: readonly SequenceLook[], reportage = fals
|
||||
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);
|
||||
const hasClearSharp = frames.some((f) => f.facing === 1 && f.faceSharp === true && f.occluded !== true);
|
||||
// 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 (hasClearSharp && f.facing === 1) {
|
||||
if (f.occluded === true) w *= shut;
|
||||
else if (f.faceSharp === false) w *= 0.2;
|
||||
}
|
||||
if (f.eyes === null || !known.length) return w;
|
||||
const gap = best - f.eyes;
|
||||
const clearlyShut = hasOpen && f.eyes < EYES_SHUT && gap >= EYES_GAP;
|
||||
|
||||
@@ -61,6 +61,10 @@ export interface AutopilotRecord {
|
||||
picked?: boolean;
|
||||
/** People in the subject (a duel, a celebration). */
|
||||
people?: number;
|
||||
/** Detection boxes for occlusion checks in a burst (not only the subject count). */
|
||||
peopleBoxes?: Box[];
|
||||
/** Ball in play, when the frame is about one. */
|
||||
ball?: Box | null;
|
||||
/** "reportage" keeps a whole person; "sport" is a ball in play. */
|
||||
context?: "sport" | "reportage";
|
||||
/** Laplacian variance of the subject, for telling a sharp sequence from a blurred one. */
|
||||
@@ -151,6 +155,7 @@ export class AutopilotService {
|
||||
values = measuredValues(auto.values, settings, photo.iso, style?.offsets ?? {});
|
||||
}
|
||||
// The sensor's roll beats the lines in the picture (a brick wall is not a horizon).
|
||||
// Prefer LevelInfo on the preview, then the original (R1 often keeps roll on the CR3), then EXIF JSON.
|
||||
let cameraAngle: number | null = null;
|
||||
if (settings.level) {
|
||||
try {
|
||||
@@ -158,6 +163,20 @@ export class AutopilotService {
|
||||
} catch {
|
||||
cameraAngle = null;
|
||||
}
|
||||
if (cameraAngle === null && photo.originalStored) {
|
||||
const original = storage.resolve(photo.storageKey);
|
||||
if (existsSync(original)) {
|
||||
try {
|
||||
cameraAngle = cameraLevelAngle(readFileSync(original));
|
||||
} catch {
|
||||
cameraAngle = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cameraAngle === null) {
|
||||
const fromExif = rollAngleFromExif(photo.exif);
|
||||
if (fromExif !== null) cameraAngle = fromExif;
|
||||
}
|
||||
}
|
||||
const angle = cameraAngle !== null ? levelAngle(cameraAngle, true) : levelAngle(rawAngle, settings.level);
|
||||
const load = this.deps.detector();
|
||||
@@ -172,6 +191,13 @@ export class AutopilotService {
|
||||
x1: f.x1,
|
||||
y1: f.y1,
|
||||
}));
|
||||
let edgeClutter: ((rect: Box) => number) | undefined;
|
||||
try {
|
||||
const { edgeClutterOf } = await import("../composition/edgeClutter.js");
|
||||
edgeClutter = await edgeClutterOf(preview, { x0: 0, y0: 0, x1: 1, y1: 1 });
|
||||
} catch {
|
||||
edgeClutter = undefined;
|
||||
}
|
||||
const planned = planFrame({
|
||||
detections,
|
||||
width: W,
|
||||
@@ -185,6 +211,7 @@ export class AutopilotService {
|
||||
cropBias: style?.cropBias ?? null,
|
||||
sport: photo.event?.sport ?? null,
|
||||
lens: lensHintFromExif(photo.exif, photo.focalLength, photo.lens),
|
||||
...(edgeClutter ? { edgeClutter } : {}),
|
||||
settings,
|
||||
});
|
||||
const ops = planned.ops;
|
||||
@@ -198,6 +225,8 @@ export class AutopilotService {
|
||||
const record: AutopilotRecord = {
|
||||
score: detections ? frameScore(detections, composition) : 0,
|
||||
people: detections && composition ? peopleIn(detections, composition.subject) : 0,
|
||||
peopleBoxes: detections?.people.map((p) => ({ x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y1 })) ?? [],
|
||||
ball: composition?.ball ?? null,
|
||||
reason: composition?.reason ?? null,
|
||||
subject: composition?.subject ?? null,
|
||||
crop,
|
||||
@@ -597,6 +626,15 @@ function photoAspect(width: number | null | undefined, height: number | null | u
|
||||
return [3, 2];
|
||||
}
|
||||
|
||||
/** Canon RollAngle from ingest EXIF JSON (degrees). Sign matches crop straighten (cancels clockwise roll). */
|
||||
export function rollAngleFromExif(exif: unknown): number | null {
|
||||
if (!exif || typeof exif !== "object") return null;
|
||||
const raw = (exif as { rollAngle?: unknown }).rollAngle;
|
||||
if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
|
||||
if (Math.abs(raw) > 8) return null;
|
||||
return Math.round(-raw * 100) / 100;
|
||||
}
|
||||
|
||||
/** A tighter plan keeps the crop and the structure scaled to that crop, so the halo does not grow with the tighter frame. */
|
||||
function cropOps(photoId: string, key: string, rect: Box, angle: number, aspect: readonly number[], detail: Record<string, number>): { opId: string; command: EditCommand }[] {
|
||||
const ops: { opId: string; command: EditCommand }[] = [];
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
* 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 maker note sits in the Exif IFD, not in IFD0. The EOS R1 JPEG often omits this tag; the
|
||||
* autopilot then tries the original CR3 and ingest `rollAngle` EXIF before the line-based level.
|
||||
* 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.
|
||||
|
||||
@@ -14,12 +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 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.
|
||||
* - A generic event is reportage. One clear person is the subject, even with empty floor around them
|
||||
* (someone walking, a suitcase beside them): the crop keeps the whole body and what they carry, and
|
||||
* cuts that empty floor. It is not a sports fill. A conversation stays as framed. A distant figure
|
||||
* (under about a fifth of the frame) is the place. A figure that already fills the frame stays.
|
||||
* A frame the camera already closed is only finished (mid-limb). A person already cut off at the edge
|
||||
* is left out.
|
||||
* - "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.
|
||||
*
|
||||
@@ -60,6 +60,8 @@ export interface Detections {
|
||||
height: number;
|
||||
people: Detection[];
|
||||
balls: Detection[];
|
||||
/** Suitcase, handbag or backpack next to a person. Part of the subject, not scenery. */
|
||||
carried?: Detection[];
|
||||
}
|
||||
|
||||
export interface Composition {
|
||||
@@ -98,6 +100,22 @@ export const TUNING = {
|
||||
wJoint: 0.8,
|
||||
/** A hand or a foot of someone who is not the subject, left in the frame. */
|
||||
wStray: 4,
|
||||
/** Horizontal lead room: how hard to pull the subject off-centre toward their back. */
|
||||
wLead: 1.4,
|
||||
/** Where the subject sits in the crop when facing right (more space on the right). */
|
||||
leadRight: 0.38,
|
||||
/** Where the subject sits in the crop when facing left. */
|
||||
leadLeft: 0.62,
|
||||
/** Bright / ad clutter on a crop edge relative to the interior. */
|
||||
wEdgeClutter: 2.2,
|
||||
/**
|
||||
* How hard to push away from the delivery floor (`minLongEdge` / `CROP_FLOOR_PX`). A crop that only works
|
||||
* near that floor is a bad read of the photo — prefer a wider frame or leave it as shot.
|
||||
*/
|
||||
wFloor: 3.5,
|
||||
/** Prefer another burst frame when the planned crop is this tight (span of the longer crop side). */
|
||||
scoreComfortFrom: 0.5,
|
||||
scoreComfortSpan: 0.35,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -173,6 +191,11 @@ export interface ComposeOptions {
|
||||
* A zoom, or an unknown lens, does not: the photographer could have zoomed, so the space is the picture.
|
||||
*/
|
||||
lens?: LensHint | null;
|
||||
/**
|
||||
* How much brighter/more saturated a crop's edge bands are than its interior (0 = clean).
|
||||
* Used to prefer a cleaner frame without changing the photograph's aspect.
|
||||
*/
|
||||
edgeClutter?: (rect: Box) => number;
|
||||
}
|
||||
|
||||
/** What the file says about the lens. `range` equal at both ends is a prime. */
|
||||
@@ -216,6 +239,57 @@ export function isLongPrime(lens: LensHint | null | undefined): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A zoom parked at (or very near) its wide end: the photographer chose the wide plan on purpose
|
||||
* (e.g. 15–35 at 15). Aggressive sports reframe is wrong — typically only straighten.
|
||||
*/
|
||||
export function isWideZoomOpen(lens: LensHint | null | undefined): boolean {
|
||||
if (!lens) return false;
|
||||
const focal = lens.focalLength;
|
||||
if (focal == null || !Number.isFinite(focal)) return false;
|
||||
const range = lens.range;
|
||||
if (range && range[0] > 0 && range[1] > range[0] + 1) {
|
||||
const span = range[1] - range[0];
|
||||
const nearWide = focal <= range[0] + Math.max(2, 0.08 * span);
|
||||
return nearWide;
|
||||
}
|
||||
const name = lens.name ?? "";
|
||||
const m = name.match(/(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)/);
|
||||
if (!m) return false;
|
||||
const lo = Number(m[1]);
|
||||
const hi = Number(m[2]);
|
||||
if (!(hi > lo + 1)) return false;
|
||||
return focal <= lo + Math.max(2, 0.08 * (hi - lo));
|
||||
}
|
||||
|
||||
/**
|
||||
* Horizontal facing for lead room: -1 left, +1 right, 0 unknown.
|
||||
* Face offset on the body wins; otherwise the ball side relative to the subject.
|
||||
*/
|
||||
export function facingSide(subject: Box, faces: readonly Box[], ball: Box | null | undefined): -1 | 0 | 1 {
|
||||
const head = { x0: subject.x0, y0: subject.y0, x1: subject.x1, y1: subject.y0 + 0.5 * (subject.y1 - subject.y0) };
|
||||
let best: Box | null = null;
|
||||
let bestO = 0;
|
||||
for (const f of faces) {
|
||||
const o = overlap(f, head) / Math.max(area(f), 1e-9);
|
||||
if (o > 0.2 && o > bestO) {
|
||||
best = f;
|
||||
bestO = o;
|
||||
}
|
||||
}
|
||||
if (best) {
|
||||
const bias = cx(best) - cx(subject);
|
||||
if (bias > 0.03) return 1;
|
||||
if (bias < -0.03) return -1;
|
||||
}
|
||||
if (ball) {
|
||||
const bias = cx(ball) - cx(subject);
|
||||
if (bias > 0.04) return 1;
|
||||
if (bias < -0.04) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** A generic event: no opponent and no fixture. The crop is a person, not a match. */
|
||||
export function isReportage(event: { away?: string | null; fixtureId?: string | null } | null): boolean {
|
||||
if (!event) return false;
|
||||
@@ -272,19 +346,45 @@ function edgeAccident(p: Detection, tallest: number): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* A person shorter than this is scenery in a place, not who the photo is about.
|
||||
* Taller than this, alone in the frame, they are the subject — a suitcase and empty floor do not hide them.
|
||||
*/
|
||||
function framedOnPurpose(inSubject: Detection[], others: Detection[]): boolean {
|
||||
const CLEAR_PERSON = 0.22;
|
||||
|
||||
/**
|
||||
* Reportage leaves the photograph when it is not one clear person with room around them.
|
||||
* A conversation stays. A distant figure stays. A body that already fills the height stays.
|
||||
* Someone the frame already cut off at the edge is not a reason to leave the rest.
|
||||
*/
|
||||
function leaveAsShot(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;
|
||||
if (!intent || intent === "closed") return false;
|
||||
const tallestPerson = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||||
const tallest = h(tallestPerson);
|
||||
if (others.some((p) => edgeAccident(p, tallest))) return false;
|
||||
if (intent === "group") return true;
|
||||
// Several people under half the frame: the place, or a wide shot. One person that size is the subject.
|
||||
if (intent === "scene" && inSubject.length > 1) return true;
|
||||
if (tallest < CLEAR_PERSON) return true;
|
||||
if (tallestPerson.y0 <= 0.06 && tallestPerson.y1 >= 0.94) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A bag or suitcase touching the person is part of the subject. One across the frame is not. */
|
||||
function withCarried(box: Box, people: Detection[], carried: readonly Detection[] | undefined): Box {
|
||||
if (!carried?.length) return box;
|
||||
let out = box;
|
||||
for (const item of carried) {
|
||||
if (item.score < 0.35) continue;
|
||||
let close = false;
|
||||
for (const p of people) {
|
||||
const gapX = Math.max(0, Math.max(p.x0, item.x0) - Math.min(p.x1, item.x1));
|
||||
const gapY = Math.max(0, Math.max(p.y0, item.y0) - Math.min(p.y1, item.y1));
|
||||
if (overlap(p, item) > 0 || (gapX < 0.12 && gapY < 0.15)) close = true;
|
||||
}
|
||||
if (close) out = union(out, item);
|
||||
}
|
||||
return true;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -427,9 +527,17 @@ export function findSubject(
|
||||
return held(a) - held(b) || dist(a) - dist(b);
|
||||
})[0];
|
||||
if (ball) {
|
||||
// Everyone big and close to the ball is in the duel, in focus or not (the goalkeeper facing the shot).
|
||||
// Not someone the frame has already cut in half: they are background, and the crop leaves them out.
|
||||
const contest = people.filter((p) => p === main || (!cutOff(p) && h(p) >= 0.6 * h(main) && Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) && overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p)));
|
||||
// Sharp people big and close to the ball are in the duel. Soft / OOF bodies near the ball are scenery —
|
||||
// they must not expand the subject box (docs/photo-editing-rules.md).
|
||||
const contest = people.filter(
|
||||
(p) =>
|
||||
p === main ||
|
||||
(!cutOff(p) &&
|
||||
sharp(p) >= withMain * sharp(main) &&
|
||||
h(p) >= 0.6 * h(main) &&
|
||||
Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) &&
|
||||
overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p)),
|
||||
);
|
||||
if (!contest.includes(main)) contest.push(main);
|
||||
const box = contest.reduce<Box>((u, p) => union(u, p), { x0: ball.x0, y0: ball.y0, x1: ball.x1, y1: ball.y1 });
|
||||
return { box, reason: "ball", people: contest, ball };
|
||||
@@ -482,29 +590,39 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
|
||||
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 { reason, people: inSubject, ball } = found;
|
||||
const s = withCarried(found.box, inSubject, d.carried);
|
||||
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 = 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.
|
||||
// A conversation, a distant figure, or a body that already fills the frame stays as shot.
|
||||
// One clear person does not: empty floor and a suitcase are not "no subject".
|
||||
const primeFigure = reportage && isLongPrime(opts.lens) && shotIntent(inSubject) === "figure";
|
||||
if (reportage && framedOnPurpose(inSubject, others) && !primeFigure) return null;
|
||||
if (reportage && leaveAsShot(inSubject, others)) return null;
|
||||
// Zoom at the wide end: the photographer opened on purpose — do not reframe (level only later).
|
||||
if (isWideZoomOpen(opts.lens)) return null;
|
||||
const headroom = 0.04 * tallest;
|
||||
const lead = reportage ? 0 : facingSide(s, faces, ball ?? null);
|
||||
const edgeClutter = opts.edgeClutter;
|
||||
const minWidth = opts.minWidth ?? 0;
|
||||
const balls = d.balls.filter((b) => b.score >= MIN_BALL);
|
||||
const feetIn = s.y1 < FEET_IN_FRAME;
|
||||
// A little ground under a sole that is whole in the photo, so the crop line is not the shoe.
|
||||
const sole = feetIn ? Math.min(SOLE_LIMIT, s.y1 + Math.min(SOLE_PAD * tallest, Math.max(0, SOLE_LIMIT - s.y1))) : s.y1;
|
||||
const finish = (c: (Composition & { cost?: number }) | null): Composition | null => (c ? { ...c, ball: ball ?? null } : null);
|
||||
// Near the delivery floor the subject was read too small / too far — do not force a super-crop.
|
||||
const finish = (c: (Composition & { cost?: number }) | null): Composition | null => {
|
||||
if (!c) return null;
|
||||
if (minWidth > 0 && w(c.rect) <= minWidth * 1.08) return null;
|
||||
return { ...c, ball: ball ?? null };
|
||||
};
|
||||
// A lined-up team, or a wide frame of many people. Keep every one of them. A tight cut would delete the row.
|
||||
// If nothing fits without cutting someone, leave the photograph as it was shot.
|
||||
const open = !ball && inSubject.length >= OPEN_PEOPLE && w(s) >= OPEN_SPAN;
|
||||
if (open) {
|
||||
const bottom = Math.min(1, feetIn ? sole : s.y1);
|
||||
return finish(
|
||||
frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, false, false, true, balls) ??
|
||||
frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, true, balls),
|
||||
frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, false, false, true, balls, false, 0, edgeClutter) ??
|
||||
frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, true, balls, false, 0, edgeClutter),
|
||||
);
|
||||
}
|
||||
// A person, not a ball: reportage, or a match photo where nobody is playing the ball. The sports cut stays
|
||||
@@ -515,27 +633,28 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
|
||||
if (feetIn) {
|
||||
// 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);
|
||||
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter)
|
||||
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter)
|
||||
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter);
|
||||
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);
|
||||
const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, true, false, ball, balls, lead, edgeClutter);
|
||||
if (cut) return finish(cut);
|
||||
return null;
|
||||
}
|
||||
// The foot already leaves the photo. Stopping on the sock is the same as cutting the ankle.
|
||||
if (!feetIn) {
|
||||
const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, false, reportage, ball, balls);
|
||||
const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, false, reportage, ball, balls, lead, edgeClutter);
|
||||
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, 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);
|
||||
// One person: score a real crop (empty floor goes). Do not prefer the untouched frame.
|
||||
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false)
|
||||
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false)
|
||||
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false);
|
||||
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));
|
||||
return finish(frame(s, ratio, s.y0 + MID_THIGH * tallest, headroom, tallest, others, inSubject, reason, minWidth, false, true, reportage, balls, false, lead, edgeClutter));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -543,7 +662,7 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
|
||||
* so it cannot slide down onto the sock. A ball in the hands stays below the cut. The hip, the knee and the
|
||||
* ankle are never the line.
|
||||
*/
|
||||
function cutAboveTheAnkle(s: Box, ratio: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight: boolean, reportage: boolean, ball?: Box, balls: readonly Box[] = []): (Composition & { cost: number }) | null {
|
||||
function cutAboveTheAnkle(s: Box, ratio: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight: boolean, reportage: boolean, ball?: Box, balls: readonly Box[] = [], lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number): (Composition & { cost: number }) | null {
|
||||
// The line is on the person. The subject box can start higher, at a ball held overhead, and that must not
|
||||
// pull the cut up onto the hip.
|
||||
const body = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||||
@@ -556,7 +675,7 @@ function cutAboveTheAnkle(s: Box, ratio: number, headroom: number, tallest: numb
|
||||
return !JOINTS.some((j) => Math.abs(at - j) < JOINT_BAND);
|
||||
});
|
||||
const tries = lines
|
||||
.map((bottom) => frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, tight, true, reportage, balls))
|
||||
.map((bottom) => frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, tight, true, reportage, balls, false, lead, edgeClutter))
|
||||
.filter((c): c is Composition & { cost: number } => !!c);
|
||||
return tries.reduce<(Composition & { cost: number }) | null>((a, b) => (!a || b.cost < a.cost ? b : a), null);
|
||||
}
|
||||
@@ -573,7 +692,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[] = [], closer = false): (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, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number, holdFrame?: boolean): (Composition & { cost: number }) | null {
|
||||
const mainSharp = Math.max(...inSubject.map(sharp));
|
||||
const keep = requiredBox(s, inSubject);
|
||||
let best: { rect: Box; cost: number } | null = null;
|
||||
@@ -609,12 +728,15 @@ 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;
|
||||
if (reportage && overlapsStray(r, others, tallest)) continue;
|
||||
// Soft scraps and stray limbs: out of the crop in sport and reportage when possible.
|
||||
if (overlapsStray(r, others, tallest)) continue;
|
||||
if (overlapsSoftScrap(r, others, mainSharp, 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.
|
||||
// is not a crop. Soft scenery 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);
|
||||
const stayWide = holdFrame ?? reportage;
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight, stayWide, closer, lead, edgeClutter, minWidth) + jointCost(r, inSubject, others, mainSharp);
|
||||
if (!best || c < best.cost) best = { rect: r, cost: c };
|
||||
}
|
||||
}
|
||||
@@ -623,20 +745,24 @@ 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, trustFrame = false, closer = 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, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number, minWidth = 0): number {
|
||||
let c = 0;
|
||||
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
|
||||
// Sharp people cut in half by the crop's edge look wrong. Soft scraps still cost when they sit in the frame.
|
||||
for (const p of others) {
|
||||
const f = overlap(r, p) / Math.max(area(p), 1e-9);
|
||||
// Only a hand or a foot of someone who is not being photographed: leave it out. A whole other person stays
|
||||
// on the rule below (in, or out, never sliced).
|
||||
if (strayLimb(p, tallest)) {
|
||||
if (strayLimb(p, tallest) || softScrap(p, mainSharp, tallest)) {
|
||||
if (f > 0.02) c += TUNING.wStray * f;
|
||||
continue;
|
||||
}
|
||||
if (f <= 0.03 || f >= 0.95) continue;
|
||||
const focus = Math.min(1, sharp(p) / Math.max(mainSharp, 1e-6));
|
||||
if (focus < TUNING.inFocus) continue;
|
||||
if (focus < TUNING.inFocus) {
|
||||
// Soft body left partly in: dirty frame — prefer the crop that puts them out.
|
||||
c += TUNING.wStray * 0.6 * Math.min(f, 1 - f);
|
||||
continue;
|
||||
}
|
||||
const size = Math.min(1, h(p) / tallest);
|
||||
c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f));
|
||||
}
|
||||
@@ -662,8 +788,19 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
|
||||
// The subject fills a good part of the height (people tall in the frame).
|
||||
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
|
||||
}
|
||||
// Centred across.
|
||||
c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r));
|
||||
// Lead room when facing is known; otherwise centre.
|
||||
let anchor = 0.5;
|
||||
if (lead > 0) anchor = TUNING.leadRight;
|
||||
else if (lead < 0) anchor = TUNING.leadLeft;
|
||||
const subjectAt = (cx(s) - r.x0) / Math.max(w(r), 1e-6);
|
||||
if (lead) c += TUNING.wLead * Math.abs(subjectAt - anchor);
|
||||
else c += TUNING.wCentre * Math.abs(subjectAt - 0.5);
|
||||
if (edgeClutter) c += TUNING.wEdgeClutter * edgeClutter(r);
|
||||
// A crop that sits on the delivery floor is a bad evaluation — pay to stay wider.
|
||||
if (minWidth > 0) {
|
||||
const headroom = (w(r) - minWidth) / Math.max(minWidth, 1e-6);
|
||||
if (headroom < 0.25) c += TUNING.wFloor * (0.25 - headroom);
|
||||
}
|
||||
// Heads a little below the top: not touching it, not floating in empty space.
|
||||
const head = (s.y0 - r.y0) / ch;
|
||||
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - (tight ? TIGHT.headMax : TUNING.headMax)));
|
||||
@@ -821,15 +958,34 @@ function strayLimb(p: Detection, tallest: number): boolean {
|
||||
return p.x0 < 0.02 || p.x1 > 0.98 || p.y0 < 0.02 || p.y1 > 0.98;
|
||||
}
|
||||
|
||||
/** Soft / tiny non-subject: scenery that should leave the crop when possible. */
|
||||
function softScrap(p: Detection, mainSharp: number, tallest: number): boolean {
|
||||
if (strayLimb(p, tallest) || sliver(p)) return true;
|
||||
if (h(p) < 0.28 * tallest) return true;
|
||||
if (sharp(p) < TUNING.inFocus * Math.max(mainSharp, 1e-6)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function overlapsStray(r: Box, others: Detection[], tallest: number): boolean {
|
||||
for (const p of others) {
|
||||
if (!strayLimb(p, tallest)) continue;
|
||||
if (!strayLimb(p, tallest) && !sliver(p)) continue;
|
||||
const share = overlap(r, p) / Math.max(area(p), 1e-9);
|
||||
if (share > 0.02) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Soft or tiny body left only partly in the crop — prefer the tighter clean frame. */
|
||||
function overlapsSoftScrap(r: Box, others: Detection[], mainSharp: number, tallest: number): boolean {
|
||||
for (const p of others) {
|
||||
if (!softScrap(p, mainSharp, tallest)) continue;
|
||||
if (strayLimb(p, tallest) || sliver(p)) continue;
|
||||
const share = overlap(r, p) / Math.max(area(p), 1e-9);
|
||||
if (share > 0.04 && share < 0.85) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function overlapsEdgeCut(r: Box, others: Detection[], tallest: number): boolean {
|
||||
for (const p of others) {
|
||||
if (!edgeAccident(p, tallest)) continue;
|
||||
@@ -877,7 +1033,7 @@ export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: numbe
|
||||
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width);
|
||||
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);
|
||||
const made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true, reportage, balls, false, 0, opts.edgeClutter);
|
||||
if (!made) return null;
|
||||
if (made.rect.y1 > bottom + 0.025) return null;
|
||||
return made.rect;
|
||||
@@ -913,5 +1069,17 @@ export function frameScore(d: Detections, c: Composition | null): number {
|
||||
const subject = d.people.filter((p) => p.x0 >= c.subject.x0 - 1e-9 && p.x1 <= c.subject.x1 + 1e-9 && p.y0 >= c.subject.y0 - 1e-9 && p.y1 <= c.subject.y1 + 1e-9);
|
||||
const focus = Math.max(0, ...subject.map((p) => p.focus ?? 0));
|
||||
const tallest = Math.max(0, ...subject.map(h));
|
||||
return Math.log10(1 + focus) * (0.6 + Math.min(1, tallest / 0.5)) * (c.reason === "ball" ? 1.15 : 1);
|
||||
let peak = 1;
|
||||
if (c.reason === "ball" && c.ball && subject.length) {
|
||||
// Closer ball-to-body = peak contact; approach / follow-through lose.
|
||||
const body = subject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||||
const dist = Math.hypot(cx(c.ball) - cx(body), cy(c.ball) - cy(body)) / Math.max(h(body), 1e-6);
|
||||
const touch = overlap(c.ball, body) > 0;
|
||||
peak = touch ? 1.35 : Math.max(0.75, 1.25 - dist);
|
||||
}
|
||||
// A frame that only works with a heavy reframe loses to one the photographer already framed.
|
||||
const cropSpan = Math.max(w(c.rect), h(c.rect));
|
||||
const comfort = Math.min(1, Math.max(0, (cropSpan - TUNING.scoreComfortFrom) / TUNING.scoreComfortSpan));
|
||||
const cropWeight = 0.7 + 0.3 * comfort;
|
||||
return Math.log10(1 + focus) * (0.6 + Math.min(1, tallest / 0.5)) * (c.reason === "ball" ? 1.15 : 1) * peak * cropWeight;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import * as ort from "onnxruntime-node";
|
||||
import { modelsDir } from "../lib/models.js";
|
||||
import sharp from "sharp";
|
||||
import type { Detection, Detections } from "./compose.js";
|
||||
import { BALL, PERSON, YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf } from "./yolox.js";
|
||||
import { BACKPACK, BALL, HANDBAG, PERSON, SUITCASE, YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf } from "./yolox.js";
|
||||
|
||||
/**
|
||||
* People and balls in a photo, with YOLOX-s (Apache-2.0, COCO classes; infra/faces/download-models.sh fetches it).
|
||||
@@ -94,7 +94,8 @@ export class SubjectDetector {
|
||||
const all = decodeYolox(raw, scale, width, height);
|
||||
const people = nmsKeep(all.filter((d) => d.cls === PERSON));
|
||||
await addSharpness(file, people);
|
||||
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)) };
|
||||
const carried = nmsKeep(all.filter((d) => d.cls === BACKPACK || d.cls === HANDBAG || d.cls === SUITCASE));
|
||||
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)), carried };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import sharp from "sharp";
|
||||
import type { Box } from "./compose.js";
|
||||
|
||||
/**
|
||||
* How much brighter a crop's edge bands are than its interior (ads, boards, blown highlights).
|
||||
* 0 = clean; higher = prefer another crop. Best-effort sample of the upright preview.
|
||||
*/
|
||||
export async function edgeClutterOf(file: string, rect: Box): Promise<(r: Box) => number> {
|
||||
const img = sharp(file).rotate().resize(128, 128, { fit: "fill" }).removeAlpha().raw();
|
||||
const { data, info } = await img.toBuffer({ resolveWithObject: true });
|
||||
const w = info.width;
|
||||
const h = info.height;
|
||||
const ch = info.channels;
|
||||
const lum = (x: number, y: number): number => {
|
||||
const i = (Math.min(h - 1, Math.max(0, y)) * w + Math.min(w - 1, Math.max(0, x))) * ch;
|
||||
return (data[i]! + data[i + 1]! + data[i + 2]!) / 3;
|
||||
};
|
||||
const mean = (x0: number, y0: number, x1: number, y1: number): number => {
|
||||
const xa = Math.floor(x0 * w);
|
||||
const ya = Math.floor(y0 * h);
|
||||
const xb = Math.max(xa + 1, Math.ceil(x1 * w));
|
||||
const yb = Math.max(ya + 1, Math.ceil(y1 * h));
|
||||
let sum = 0;
|
||||
let n = 0;
|
||||
for (let y = ya; y < yb; y++) {
|
||||
for (let x = xa; x < xb; x++) {
|
||||
sum += lum(x, y);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
return n ? sum / n : 0;
|
||||
};
|
||||
// Capture a baseline for the whole photo so the returned function is sync and cheap.
|
||||
void rect;
|
||||
return (r: Box): number => {
|
||||
const band = 0.08 * Math.min(r.x1 - r.x0, r.y1 - r.y0);
|
||||
if (band <= 0.01) return 0;
|
||||
const inner = mean(r.x0 + band, r.y0 + band, r.x1 - band, r.y1 - band);
|
||||
if (inner < 1) return 0;
|
||||
const edges = [
|
||||
mean(r.x0, r.y0, r.x1, r.y0 + band),
|
||||
mean(r.x0, r.y1 - band, r.x1, r.y1),
|
||||
mean(r.x0, r.y0, r.x0 + band, r.y1),
|
||||
mean(r.x1 - band, r.y0, r.x1, r.y1),
|
||||
];
|
||||
const hot = Math.max(...edges);
|
||||
const ratio = hot / inner;
|
||||
if (ratio < 1.25) return 0;
|
||||
return Math.min(2, (ratio - 1.25) * 2);
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { keepPhotoAspect } from "./geometry.js";
|
||||
import { planFrame, type PlanSettings } from "./planFrame.js";
|
||||
import { cropTooHard, levelWithoutChopping, planFrame, type PlanSettings } from "./planFrame.js";
|
||||
|
||||
const settings: PlanSettings = {
|
||||
crop: true,
|
||||
@@ -22,6 +22,14 @@ describe("keepPhotoAspect", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("cropTooHard", () => {
|
||||
it("refuses a crop that sits on the delivery floor", () => {
|
||||
// 2400 px floor on a 6000 px long edge → min width 0.4; 0.41 is still too close.
|
||||
expect(cropTooHard({ x0: 0.3, y0: 0.2, x1: 0.71, y1: 0.8 }, 6000, 4000, 2400)).toBe(true);
|
||||
expect(cropTooHard({ x0: 0.1, y0: 0.05, x1: 0.9, y1: 0.95 }, 6000, 4000, 2400)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planFrame", () => {
|
||||
it("does not turn the photograph into another format", () => {
|
||||
const planned = planFrame({
|
||||
@@ -47,12 +55,13 @@ describe("planFrame", () => {
|
||||
expect(crop.params.aspect).toEqual([6000, 4000]);
|
||||
});
|
||||
|
||||
it("does not close a reportage frame the camera left open, even when matches are cropped tight", () => {
|
||||
it("crops one clear person in reportage and ignores a learnt sports cut", () => {
|
||||
const person = { x0: 0.35, y0: 0.28, x1: 0.52, y1: 0.72 };
|
||||
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 }],
|
||||
people: [{ ...person, score: 0.9, sharpness: 1 }],
|
||||
balls: [],
|
||||
},
|
||||
width: 6000,
|
||||
@@ -63,7 +72,17 @@ describe("planFrame", () => {
|
||||
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);
|
||||
const crop = planned.ops.find((op) => op.command === "crop.set");
|
||||
expect(crop?.command).toBe("crop.set");
|
||||
if (!crop || crop.command !== "crop.set") return;
|
||||
const rect = crop.params.rect;
|
||||
expect(rect.x0).toBeLessThanOrEqual(person.x0);
|
||||
expect(rect.x1).toBeGreaterThanOrEqual(person.x1);
|
||||
expect(rect.y0).toBeLessThanOrEqual(person.y0);
|
||||
expect(rect.y1).toBeGreaterThan(person.y1);
|
||||
expect(rect.x1 - rect.x0).toBeLessThan(0.92);
|
||||
// The learnt match cut (half the body) must not land on this photograph.
|
||||
expect(rect.y1).toBeGreaterThan(person.y0 + 0.7 * (person.y1 - person.y0));
|
||||
});
|
||||
|
||||
it("does not apply a learnt cut that chops a player the crop had kept", () => {
|
||||
@@ -90,12 +109,13 @@ describe("planFrame", () => {
|
||||
expect(crop.params.rect.x1).toBeGreaterThanOrEqual(0.62);
|
||||
});
|
||||
|
||||
it("does not close a reportage full-length the camera already composed", () => {
|
||||
it("crops a reportage full-length that still has empty floor around the person", () => {
|
||||
const person = { x0: 0.3, y0: 0.12, x1: 0.48, y1: 0.82 };
|
||||
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 }],
|
||||
people: [{ ...person, score: 0.9, sharpness: 1 }],
|
||||
balls: [],
|
||||
},
|
||||
width: 6000,
|
||||
@@ -105,6 +125,45 @@ describe("planFrame", () => {
|
||||
angle: 0,
|
||||
settings,
|
||||
});
|
||||
const crop = planned.ops.find((op) => op.command === "crop.set");
|
||||
expect(crop?.command).toBe("crop.set");
|
||||
if (!crop || crop.command !== "crop.set") return;
|
||||
const rect = crop.params.rect;
|
||||
expect(rect.y0).toBeLessThanOrEqual(person.y0);
|
||||
expect(rect.y1).toBeGreaterThan(person.y1);
|
||||
expect(rect.x0).toBeLessThanOrEqual(person.x0);
|
||||
expect(rect.x1).toBeGreaterThanOrEqual(person.x1);
|
||||
expect(rect.x1 - rect.x0).toBeLessThan(0.92);
|
||||
});
|
||||
|
||||
it("reduces the straighten angle when leveling would chop the subject's feet", () => {
|
||||
// Subject nearly fills the frame — rotating then re-fitting about centre
|
||||
// shrinks past the feet unless we drop the angle.
|
||||
const subject = { x0: 0.05, y0: 0.02, x1: 0.95, y1: 0.98 };
|
||||
const rect = { x0: 0, y0: 0, x1: 1, y1: 1 };
|
||||
const out = levelWithoutChopping(rect, subject, 8, 6000, 4000);
|
||||
expect(Math.abs(out.angle)).toBeLessThan(8);
|
||||
expect(out.rect.y1).toBeGreaterThanOrEqual(subject.y1 - 0.03);
|
||||
expect(out.rect.y0).toBeLessThanOrEqual(subject.y0 + 0.03);
|
||||
});
|
||||
|
||||
it("does not reframe when the zoom is at its wide end", () => {
|
||||
const planned = planFrame({
|
||||
detections: {
|
||||
width: 6000,
|
||||
height: 4000,
|
||||
people: [{ x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.92, score: 0.9, sharpness: 1 }],
|
||||
balls: [{ x0: 0.5, y0: 0.7, x1: 0.54, y1: 0.75, score: 0.9 }],
|
||||
},
|
||||
width: 6000,
|
||||
height: 4000,
|
||||
reportage: false,
|
||||
values: null,
|
||||
angle: 0,
|
||||
lens: { focalLength: 15, range: [15, 35], name: "RF15-35mm F2.8 L IS USM" },
|
||||
settings,
|
||||
});
|
||||
expect(planned.composition).toBeNull();
|
||||
expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,10 @@ const MAX_LEVEL = 8;
|
||||
const MIN_LEVEL = 0.25;
|
||||
/** A crop this close to the whole frame is not worth making. */
|
||||
const KEEP_WHOLE = 0.92;
|
||||
/** Crop long-edge must clear the delivery floor by this factor, else leave as shot. */
|
||||
const MIN_LONG_EDGE_HEADROOM = 1.05;
|
||||
/** Crop width must clear `minCropWidth` by this factor, else the read was too aggressive. */
|
||||
const MIN_WIDTH_HEADROOM = 1.08;
|
||||
|
||||
/** 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 {
|
||||
@@ -20,6 +24,20 @@ function losesBall(rect: Box | null, ball: Box | null | undefined): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the crop sits on the organisation's delivery floor (`minLongEdge` / `CROP_FLOOR_PX`).
|
||||
* Forcing that much zoom usually means the subject or framing was misread.
|
||||
*/
|
||||
export function cropTooHard(rect: Box, width: number, height: number, minLongEdge: number): boolean {
|
||||
const cropW = rect.x1 - rect.x0;
|
||||
const cropH = rect.y1 - rect.y0;
|
||||
const longPx = Math.max(cropW * width, cropH * height);
|
||||
if (longPx < minLongEdge * MIN_LONG_EDGE_HEADROOM) return true;
|
||||
const floor = minCropWidth(width, height, minLongEdge);
|
||||
if (floor > 0 && cropW <= floor * MIN_WIDTH_HEADROOM) 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;
|
||||
@@ -37,6 +55,20 @@ function chopsKeptPlayer(original: Box, placed: Box, subject: Box): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply straighten while keeping the photograph's aspect. If the rotated crop would chop a head, foot or
|
||||
* side the unrotated crop had kept, reduce the angle (half → quarter → zero). Subject intact beats a level horizon.
|
||||
*/
|
||||
export function levelWithoutChopping(rect: Box, subject: Box, angle: number, w: number, h: number): { rect: Box; angle: number } {
|
||||
if (!angle) return { rect, angle: 0 };
|
||||
const tries = [angle, angle / 2, angle / 4, 0];
|
||||
for (const tryAngle of tries) {
|
||||
const shaped = constrainRotated(rect, tryAngle, w, h);
|
||||
if (!chopsKeptPlayer(rect, shaped, subject)) return { rect: shaped, angle: tryAngle };
|
||||
}
|
||||
return { rect, angle: 0 };
|
||||
}
|
||||
|
||||
export interface PlanSettings {
|
||||
crop: boolean;
|
||||
tone: boolean;
|
||||
@@ -108,20 +140,61 @@ export function planFrame(input: {
|
||||
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;
|
||||
/** Bright edge clutter score for a crop candidate (same aspect). */
|
||||
edgeClutter?: (rect: Box) => number;
|
||||
settings: PlanSettings;
|
||||
}): PlannedFrame {
|
||||
const { detections, settings, width: W, height: H, reportage } = input;
|
||||
// The photograph's own aspect. A preset (4:5, 16:9, a portrait of a landscape frame) is not used.
|
||||
const aspect = null;
|
||||
const minWidth = minCropWidth(W, H, settings.minLongEdge);
|
||||
const context = reportage ? "reportage" : "sport";
|
||||
const context: "sport" | "reportage" = reportage ? "reportage" : "sport";
|
||||
const faces = input.faces ?? [];
|
||||
const focus = input.focus ?? null;
|
||||
const sport = input.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;
|
||||
const edgeClutter = input.edgeClutter;
|
||||
const composition = detections
|
||||
? compose(detections, aspect, {
|
||||
minWidth,
|
||||
focus,
|
||||
framing: settings.framing,
|
||||
context,
|
||||
faces,
|
||||
sport,
|
||||
lens,
|
||||
...(edgeClutter ? { edgeClutter } : {}),
|
||||
})
|
||||
: null;
|
||||
const wideComposition =
|
||||
detections && !reportage && settings.framing === "tight"
|
||||
? compose(detections, aspect, {
|
||||
minWidth,
|
||||
focus,
|
||||
framing: "full",
|
||||
context: "sport",
|
||||
sport,
|
||||
...(edgeClutter ? { edgeClutter } : {}),
|
||||
})
|
||||
: null;
|
||||
const plans = reportage && detections
|
||||
? {
|
||||
half: planCrop(detections, "half", aspect, {
|
||||
minWidth,
|
||||
focus,
|
||||
context,
|
||||
faces,
|
||||
...(edgeClutter ? { edgeClutter } : {}),
|
||||
}),
|
||||
threeQuarter: planCrop(detections, "threeQuarter", aspect, {
|
||||
minWidth,
|
||||
focus,
|
||||
context,
|
||||
faces,
|
||||
...(edgeClutter ? { edgeClutter } : {}),
|
||||
}),
|
||||
}
|
||||
: null;
|
||||
let crop: Box | null = null;
|
||||
let angle = input.angle;
|
||||
if (settings.crop && composition) {
|
||||
@@ -154,13 +227,32 @@ export function planFrame(input: {
|
||||
// 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) || 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);
|
||||
const base = keepPhotoAspect(rect);
|
||||
const leveled = levelWithoutChopping(base, composition.subject, angle, W, H);
|
||||
angle = leveled.angle;
|
||||
let shaped: Box | null = leveled.rect;
|
||||
if (losesBall(shaped, composition.ball)) {
|
||||
const again = levelWithoutChopping(keepPhotoAspect(composition.rect), composition.subject, angle, W, H);
|
||||
angle = again.angle;
|
||||
shaped = again.rect;
|
||||
}
|
||||
if (losesBall(shaped, composition.ball)) shaped = null;
|
||||
if (shaped && !clipsBall(shaped, balls) && shaped.x1 - shaped.x0 < KEEP_WHOLE) crop = shaped;
|
||||
if (shaped && !clipsBall(shaped, balls) && shaped.x1 - shaped.x0 < KEEP_WHOLE) {
|
||||
// A super-crop at the configured floor means the subject/read was wrong — keep the photograph.
|
||||
if (!cropTooHard(shaped, W, H, settings.minLongEdge)) crop = shaped;
|
||||
}
|
||||
}
|
||||
const wideBase = wideComposition ? keepPhotoAspect(wideComposition.rect) : null;
|
||||
const wideLeveled = wideBase ? levelWithoutChopping(wideBase, wideComposition!.subject, angle, W, H) : null;
|
||||
let wide: Box | null = null;
|
||||
if (settings.crop && wideLeveled && wideLeveled.rect.x1 - wideLeveled.rect.x0 < KEEP_WHOLE) {
|
||||
if (!cropTooHard(wideLeveled.rect, W, H, settings.minLongEdge)) wide = wideLeveled.rect;
|
||||
}
|
||||
if (!crop && angle) {
|
||||
const full = levelWithoutChopping({ x0: 0, y0: 0, x1: 1, y1: 1 }, { x0: 0.1, y0: 0.1, x1: 0.9, y1: 0.9 }, angle, W, H);
|
||||
angle = full.angle;
|
||||
crop = full.rect;
|
||||
}
|
||||
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);
|
||||
const lockedPlans = plans
|
||||
? {
|
||||
half: plans.half ? keepPhotoAspect(plans.half) : null,
|
||||
|
||||
@@ -11,7 +11,7 @@ import { modelsDir } from "../lib/models.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { readFocusPoint } from "../ingest/exif.js";
|
||||
import { focusFromExifJson } from "../ingest/focus.js";
|
||||
import { compose, isReportage } from "./compose.js";
|
||||
import { compose, findSubject, isReportage } from "./compose.js";
|
||||
import { lazyDetector } from "./detect.js";
|
||||
|
||||
const Params = z.object({ photoId: z.uuid() });
|
||||
@@ -51,7 +51,15 @@ export async function registerCompositionRoutes(app: FastifyInstance, deps: { db
|
||||
const original = photo.originalStored ? storage.resolve(photo.storageKey) : preview;
|
||||
const focus = focusFromExifJson(photo.exif) ?? (existsSync(original) ? await readFocusPoint(original) : null);
|
||||
const context = isReportage(photo.event) ? "reportage" : "sport";
|
||||
return { crop: compose(detections, aspect ? aspect[0] / aspect[1] : null, { focus, context, faces: photo.faces, sport: photo.event?.sport ?? null }) };
|
||||
const faces = photo.faces;
|
||||
const sport = photo.event?.sport ?? null;
|
||||
const crop = compose(detections, aspect ? aspect[0] / aspect[1] : null, { focus, context, faces, sport });
|
||||
let found = crop != null;
|
||||
if (!found) {
|
||||
const subject = findSubject(detections, focus, { reportage: context === "reportage", sport, faces });
|
||||
found = subject != null;
|
||||
}
|
||||
return { crop, found };
|
||||
});
|
||||
|
||||
/** YOLOX-s, so the desktop can crop with the same detector. Not a face model: no biometrics gate. */
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { Detection } from "./compose.js";
|
||||
|
||||
/** YOLOX-s input. People are COCO class 0, the sports ball is class 32. */
|
||||
/** YOLOX-s input. People are COCO class 0, the sports ball is class 32. Bags travel with the person. */
|
||||
export const YOLOX_SIZE = 640;
|
||||
export const PERSON = 0;
|
||||
export const BACKPACK = 24;
|
||||
export const HANDBAG = 26;
|
||||
export const SUITCASE = 28;
|
||||
export const BALL = 32;
|
||||
|
||||
const WANTED = [PERSON, BALL, BACKPACK, HANDBAG, SUITCASE];
|
||||
|
||||
export interface RawDet extends Detection {
|
||||
cls: number;
|
||||
}
|
||||
@@ -23,7 +28,7 @@ export function decodeYolox(raw: Float32Array, scale: number, width: number, hei
|
||||
const o = a * stride;
|
||||
const obj = raw[o + 4]!;
|
||||
if (obj < 0.1) continue;
|
||||
for (const cls of [PERSON, BALL]) {
|
||||
for (const cls of WANTED) {
|
||||
const score = obj * raw[o + 5 + cls]!;
|
||||
if (score < 0.25) continue;
|
||||
const bx = (raw[o]! + x) * s;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { cullFromCameraRating, ratingFromTags, readCameraInfo, withCameraRatingChecked } from "./exif.js";
|
||||
import { cullFromCameraRating, cullFromXmpPacket, ratingFromTags, readCameraInfo, withCameraRatingChecked } from "./exif.js";
|
||||
|
||||
describe("on-camera star ratings", () => {
|
||||
it("maps EXIF Rating and RatingPercent tags", () => {
|
||||
@@ -26,6 +26,16 @@ describe("on-camera star ratings", () => {
|
||||
expect(cullFromCameraRating(4)).toEqual({ rating: 4, flag: "PICK" });
|
||||
});
|
||||
|
||||
it("reads Lightroom pick without stars", () => {
|
||||
expect(cullFromXmpPacket(`<xmpDM:pick>1</xmpDM:pick><xmp:Rating>0</xmp:Rating>`)).toEqual({ flag: "PICK" });
|
||||
expect(cullFromXmpPacket(`xmpDM:pick="-1"`)).toEqual({ flag: "REJECT" });
|
||||
expect(cullFromXmpPacket(`<xmp:Rating>3</xmp:Rating><xmp:Label>Blue</xmp:Label>`)).toEqual({
|
||||
rating: 3,
|
||||
flag: "PICK",
|
||||
colorLabel: "BLUE",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks exif so the backfill does not re-read the same file", () => {
|
||||
expect(withCameraRatingChecked(undefined)).toEqual({ cameraRatingChecked: true });
|
||||
expect(withCameraRatingChecked({ owner: "PS" })).toEqual({ owner: "PS", cameraRatingChecked: true });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PmPhoto } from "@photoreport/metadata";
|
||||
import { libraryMarksFromXmp, xmpPacketFromJpeg, type PmPhoto } from "@photoreport/metadata";
|
||||
import exifr from "exifr";
|
||||
import { type FocusHint, focusFromTags } from "./focus.js";
|
||||
|
||||
@@ -42,6 +42,11 @@ export type CameraExtra = Pick<
|
||||
focusY0?: number;
|
||||
focusX1?: number;
|
||||
focusY1?: number;
|
||||
/**
|
||||
* Canon electronic-level roll in degrees (MakerNotes RollAngle / LevelInfo), clockwise positive as the
|
||||
* camera wrote it. Used when the JPEG preview has no LevelInfo (common on EOS R1).
|
||||
*/
|
||||
rollAngle?: number;
|
||||
};
|
||||
|
||||
export interface CameraInfo {
|
||||
@@ -85,6 +90,40 @@ export function cullFromCameraRating(rating: number | undefined): { rating: numb
|
||||
return { rating, flag: "PICK" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Cull from Lightroom / Photo Mechanic XMP on the file: `xmpDM:pick`, stars, colour.
|
||||
* Prefer this over stars alone — a flagged file with Rating 0 must still land as PICK.
|
||||
*/
|
||||
export type XmpCull = {
|
||||
rating?: number;
|
||||
flag?: "PICK" | "REJECT";
|
||||
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
|
||||
};
|
||||
|
||||
export function cullFromXmpPacket(xmp: string | null | undefined): XmpCull {
|
||||
if (!xmp) return {};
|
||||
const marks = libraryMarksFromXmp(xmp);
|
||||
const out: XmpCull = {};
|
||||
if (marks.flag === "REJECT") out.flag = "REJECT";
|
||||
else if (marks.flag === "PICK") out.flag = "PICK";
|
||||
const rating = marks.rating;
|
||||
if (typeof rating === "number" && rating > 0) {
|
||||
out.rating = rating;
|
||||
if (!out.flag) out.flag = "PICK";
|
||||
}
|
||||
const color = marks.colorLabel;
|
||||
if (color === "RED" || color === "YELLOW" || color === "GREEN" || color === "BLUE" || color === "PURPLE") {
|
||||
out.colorLabel = color;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Read XMP from a JPEG buffer or raw XMP bytes and return library cull fields. */
|
||||
export function cullFromJpegBytes(bytes: Buffer | Uint8Array): ReturnType<typeof cullFromXmpPacket> {
|
||||
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
||||
return cullFromXmpPacket(xmpPacketFromJpeg(view));
|
||||
}
|
||||
|
||||
/** Marker in `photos.exif` so the worker does not re-read files that already had no stars. */
|
||||
export const CAMERA_RATING_CHECKED = "cameraRatingChecked";
|
||||
|
||||
@@ -183,7 +222,8 @@ function extraOf(tags: Record<string, unknown>): CameraExtra {
|
||||
const lat = num(tags.latitude);
|
||||
const lon = num(tags.longitude);
|
||||
const alt = num(tags.GPSAltitude);
|
||||
const extra: CameraExtra = {
|
||||
// Build then drop undefined keys — exactOptionalPropertyTypes forbids `rollAngle?: number | undefined`.
|
||||
const draft = {
|
||||
exposureCompensation: num(tags.ExposureCompensation) ?? num(tags.ExposureBiasValue),
|
||||
flashFired: flash === undefined ? undefined : (flash & 1) === 1,
|
||||
meteringMode: metering === undefined ? undefined : (METERING[metering] ?? (metering === 255 ? "Other" : undefined)),
|
||||
@@ -191,6 +231,7 @@ function extraOf(tags: Record<string, unknown>): CameraExtra {
|
||||
whiteBalance: wb === undefined ? undefined : wb === 0 ? "Auto" : "Manual",
|
||||
focalLength35: num(tags.FocalLengthIn35mmFormat),
|
||||
lensRange: lensInfo[0] && lensInfo[1] ? [lensInfo[0], lensInfo[1]] : undefined,
|
||||
rollAngle: num(tags.RollAngle) ?? num(tags.CameraRollAngle) ?? num((tags as { rollAngle?: unknown }).rollAngle),
|
||||
software,
|
||||
// Canon and Nikon write the firmware as the Software ("Firmware Version 1.8.1", "Ver.1.10").
|
||||
firmware: software && /firmware|^ver\.?\s*\d/i.test(software) ? software.replace(/^firmware\s*version\s*/i, "") : undefined,
|
||||
@@ -205,7 +246,7 @@ function extraOf(tags: Record<string, unknown>): CameraExtra {
|
||||
longitude: lon,
|
||||
altitude: alt === undefined ? undefined : num(tags.GPSAltitudeRef) === 1 ? -alt : alt,
|
||||
};
|
||||
return Object.fromEntries(Object.entries(extra).filter(([, v]) => v !== undefined)) as CameraExtra;
|
||||
return Object.fromEntries(Object.entries(draft).filter(([, v]) => v !== undefined)) as CameraExtra;
|
||||
}
|
||||
|
||||
/** The focus point in a file (the original, which still has the camera's EXIF). Null when the body wrote none. */
|
||||
@@ -236,6 +277,8 @@ export async function readCameraInfo(file: string | Buffer): Promise<CameraInfo>
|
||||
iptc: false,
|
||||
xmp: true,
|
||||
icc: false,
|
||||
// Canon LevelInfo / RollAngle for bodies that keep the electronic level in MakerNotes (R1 often only on CR3).
|
||||
mergeOutput: true,
|
||||
reviveValues: false,
|
||||
translateValues: false,
|
||||
})) as Record<string, unknown> | undefined;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { applyRename } from "../library/rename.js";
|
||||
import { mkdir, rename, rm, stat } from "node:fs/promises";
|
||||
import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import type { Db } from "../db.js";
|
||||
@@ -9,7 +9,14 @@ import { stripNulBytes } from "../lib/sanitize.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import { LocalStorage, sha256File, UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
|
||||
import { readEmbeddedIptc } from "./embedded.js";
|
||||
import { cullFromCameraRating, readCameraInfo, withCameraRatingChecked, withCaptureClockChecked, withCaptureClockRecurate } from "./exif.js";
|
||||
import {
|
||||
cullFromCameraRating,
|
||||
cullFromJpegBytes,
|
||||
readCameraInfo,
|
||||
withCameraRatingChecked,
|
||||
withCaptureClockChecked,
|
||||
withCaptureClockRecurate,
|
||||
} from "./exif.js";
|
||||
import { jpegFileComplete } from "./jpeg.js";
|
||||
|
||||
export const ACCEPTED_EXTENSIONS = new Set([".jpg", ".jpeg"]);
|
||||
@@ -173,6 +180,13 @@ export class IngestService {
|
||||
|
||||
const camera = await readCameraInfo(file).catch(() => ({}) as Awaited<ReturnType<typeof readCameraInfo>>);
|
||||
const embedded = await readEmbeddedIptc(file);
|
||||
// Lightroom / Photo Mechanic pick, stars and colour on the file — not stars alone.
|
||||
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
|
||||
try {
|
||||
xmpCull = cullFromJpegBytes(await readFile(file));
|
||||
} catch {
|
||||
xmpCull = {};
|
||||
}
|
||||
const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined;
|
||||
// Archive imports name their own event. No camera time: keep the folder/pin the photographer named — do not
|
||||
// invent "now" (that would also force today's open event). With a capture time, the pin only wins inside its
|
||||
@@ -215,8 +229,9 @@ export class IngestService {
|
||||
// Always mark that stars were read, so the worker backfill skips this file.
|
||||
exif: withCameraRatingChecked(camera.extra && Object.keys(camera.extra).length ? camera.extra : undefined) as Prisma.InputJsonValue,
|
||||
...(Object.keys(embedded).length && { embeddedIptc: embedded }),
|
||||
// Stars set on the body (or in Photo Mechanic): rating + Escolhida so filters and live picks see them.
|
||||
// Stars on the body, then XMP pick/colour from Lightroom / Photo Mechanic (pick with Rating 0 still counts).
|
||||
...cullFromCameraRating(camera.rating),
|
||||
...xmpCull,
|
||||
});
|
||||
try {
|
||||
photo = await db.photo.create({ data });
|
||||
@@ -349,26 +364,37 @@ export class IngestService {
|
||||
const { db, storage, log } = this.deps;
|
||||
const key = storage.originalKey(photo.organizationId, photo.sha256, ext === ".jpeg" ? ".jpg" : ext);
|
||||
const size = (await stat(file)).size;
|
||||
// Read cull marks before adopt moves the file out of the ingest path.
|
||||
const existing = await db.photo.findUnique({ where: { id: photo.id }, select: { rating: true, flag: true, colorLabel: true, exif: true } });
|
||||
const needCull = (existing?.rating ?? photo.rating ?? 0) <= 0 || existing?.flag === "NONE";
|
||||
const camera = needCull ? await readCameraInfo(file).catch(() => null) : null;
|
||||
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
|
||||
if (needCull) {
|
||||
try {
|
||||
xmpCull = cullFromJpegBytes(await readFile(file));
|
||||
} catch {
|
||||
xmpCull = {};
|
||||
}
|
||||
}
|
||||
const cull = { ...cullFromCameraRating(camera?.rating), ...xmpCull };
|
||||
if (key !== photo.storageKey) await rm(storage.resolve(photo.storageKey), { force: true });
|
||||
await storage.adopt(file, key);
|
||||
// Previews (thumb/preview) stay: they already show this photo. Only the stored file changes.
|
||||
// Faces and shirt numbers were read from the 2048 px preview: read them again from the full photo.
|
||||
const org = await db.organization.findUnique({ where: { id: photo.organizationId }, select: { biometricsEnabled: true } });
|
||||
// Preview JPEGs often lack the body's star rating; apply it from the original when still unrated.
|
||||
const existing = await db.photo.findUnique({ where: { id: photo.id }, select: { rating: true, flag: true, exif: true } });
|
||||
const camera = (existing?.rating ?? photo.rating ?? 0) > 0 ? null : await readCameraInfo(file).catch(() => null);
|
||||
const cull = cullFromCameraRating(camera?.rating);
|
||||
const data: Prisma.PhotoUpdateInput = {
|
||||
storageKey: key,
|
||||
byteSize: size,
|
||||
originalStored: true,
|
||||
};
|
||||
if (org?.biometricsEnabled) data.facesStatus = "PENDING";
|
||||
if (typeof cull.rating === "number" && cull.rating > 0) data.rating = cull.rating;
|
||||
if (cull.flag && existing?.flag === "NONE") data.flag = cull.flag;
|
||||
if (cull.colorLabel && existing?.colorLabel === "NONE") data.colorLabel = cull.colorLabel;
|
||||
if (needCull) data.exif = withCameraRatingChecked(existing?.exif) as Prisma.InputJsonValue;
|
||||
const updated = await db.photo.update({
|
||||
where: { id: photo.id },
|
||||
data: {
|
||||
storageKey: key,
|
||||
byteSize: size,
|
||||
originalStored: true,
|
||||
...(org?.biometricsEnabled && { facesStatus: "PENDING" }),
|
||||
...("rating" in cull ? { rating: cull.rating } : {}),
|
||||
...("flag" in cull && existing?.flag === "NONE" ? { flag: cull.flag } : {}),
|
||||
...(camera ? { exif: withCameraRatingChecked(existing?.exif) as Prisma.InputJsonValue } : {}),
|
||||
},
|
||||
data,
|
||||
});
|
||||
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
|
||||
// Deliveries waiting for it go now.
|
||||
@@ -484,21 +510,44 @@ export class IngestService {
|
||||
for (const row of rows) {
|
||||
const file = storage.resolve(row.storage_key);
|
||||
const camera = await readCameraInfo(file).catch(() => null);
|
||||
const cull = cullFromCameraRating(camera?.rating);
|
||||
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
|
||||
try {
|
||||
xmpCull = cullFromJpegBytes(await readFile(file));
|
||||
} catch {
|
||||
xmpCull = {};
|
||||
}
|
||||
const cull = { ...cullFromCameraRating(camera?.rating), ...xmpCull };
|
||||
const data: Prisma.PhotoUpdateInput = {
|
||||
exif: withCameraRatingChecked(row.exif) as Prisma.InputJsonValue,
|
||||
};
|
||||
if ("rating" in cull) {
|
||||
const patch: {
|
||||
rating?: number;
|
||||
flag?: "PICK" | "REJECT";
|
||||
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
|
||||
} = {};
|
||||
let changed = false;
|
||||
if (typeof cull.rating === "number" && cull.rating > 0) {
|
||||
data.rating = cull.rating;
|
||||
if (row.flag === "NONE") data.flag = "PICK";
|
||||
applied++;
|
||||
patch.rating = cull.rating;
|
||||
changed = true;
|
||||
}
|
||||
if (cull.flag && row.flag === "NONE") {
|
||||
data.flag = cull.flag;
|
||||
patch.flag = cull.flag;
|
||||
changed = true;
|
||||
}
|
||||
if (cull.colorLabel) {
|
||||
data.colorLabel = cull.colorLabel;
|
||||
patch.colorLabel = cull.colorLabel;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) applied++;
|
||||
await db.photo.update({ where: { id: row.id }, data });
|
||||
if ("rating" in cull) {
|
||||
if (changed) {
|
||||
broadcaster.library(row.organization_id, {
|
||||
type: "photo.updated",
|
||||
ids: [row.id],
|
||||
patch: { rating: cull.rating, ...(row.flag === "NONE" ? { flag: "PICK" as const } : {}) },
|
||||
patch,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+103
-20
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { clipsBall, compose, type Detection, findSubject, isHandball, isLongPrime, isReportage, minCropWidth, planCrop, sendBlockedByBall, shotIntent } from "../src/composition/compose.js";
|
||||
import { clipsBall, compose, facingSide, findSubject, frameScore, isHandball, isLongPrime, isReportage, isWideZoomOpen, minCropWidth, planCrop, sendBlockedByBall, shotIntent, type Detection } 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;
|
||||
@@ -54,10 +54,14 @@ describe("automatic crop", () => {
|
||||
const c = compose({ ...frame, people: [blurred, referee], balls: [] })!;
|
||||
expect(c.reason).toBe("person");
|
||||
expect(referee).toMatchObject(c.subject);
|
||||
// About two thirds of the frame, with the referee in the middle.
|
||||
// About two thirds of the frame; soft foreground is left out when possible, so the crop may sit off-centre.
|
||||
expect(c.rect.x1 - c.rect.x0).toBeGreaterThan(0.55);
|
||||
expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.85);
|
||||
expect(Math.abs((c.rect.x0 + c.rect.x1) / 2 - 0.5)).toBeLessThan(0.05);
|
||||
expect(inside(c.rect, referee)).toBe(true);
|
||||
const softShare =
|
||||
Math.max(0, Math.min(c.rect.x1, blurred.x1) - Math.max(c.rect.x0, blurred.x0)) *
|
||||
Math.max(0, Math.min(c.rect.y1, blurred.y1) - Math.max(c.rect.y0, blurred.y0));
|
||||
expect(softShare / ((blurred.x1 - blurred.x0) * (blurred.y1 - blurred.y0))).toBeLessThan(0.5);
|
||||
});
|
||||
|
||||
it("never crops across a knee or an ankle, and keeps the delivery's resolution", () => {
|
||||
@@ -194,10 +198,12 @@ describe("reportage", () => {
|
||||
expect(shotIntent([person(0.36, 0.15, 0.66, 0.996)])).toBe("closed");
|
||||
});
|
||||
|
||||
it("leaves a wide frame as shot", () => {
|
||||
it("crops a single person standing in the frame, and keeps them whole", () => {
|
||||
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 room = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "reportage" })!;
|
||||
expect(inside(room.rect, speaker)).toBe(true);
|
||||
expect(room.rect.x1 - room.rect.x0).toBeLessThan(0.92);
|
||||
expect(room.rect.y1).toBeGreaterThan(speaker.y1);
|
||||
const match = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "sport" });
|
||||
expect(match).not.toBeNull();
|
||||
});
|
||||
@@ -212,7 +218,7 @@ describe("reportage", () => {
|
||||
expect(isLongPrime({ focalLength: 200 })).toBe(false);
|
||||
});
|
||||
|
||||
it("steps a full-length closer on a long prime, and leaves the same frame on a zoom", () => {
|
||||
it("crops a full-length on a prime and on a zoom, and keeps a suitcase with the person", () => {
|
||||
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] } })!;
|
||||
@@ -221,19 +227,24 @@ describe("reportage", () => {
|
||||
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).toBeGreaterThan(0.7);
|
||||
expect(width).toBeLessThan(0.92);
|
||||
const zoom = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [70, 200] } });
|
||||
expect(zoom).toBeNull();
|
||||
const zoom = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [70, 200] } })!;
|
||||
expect(inside(zoom.rect, p)).toBe(true);
|
||||
expect(zoom.rect.x1 - zoom.rect.x0).toBeLessThan(0.92);
|
||||
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();
|
||||
const suitcase = { x0: 0.54, y0: 0.5, x1: 0.64, y1: 0.7, score: 0.8 };
|
||||
const scene = compose({ ...frame, people: [wide], balls: [], carried: [suitcase] }, null, { context: "reportage", lens: { focalLength: 200, range: [200, 200] } })!;
|
||||
expect(inside(scene.rect, wide)).toBe(true);
|
||||
expect(inside(scene.rect, suitcase)).toBe(true);
|
||||
expect(scene.rect.y1).toBeGreaterThan(suitcase.y1);
|
||||
});
|
||||
|
||||
it("leaves a full-length as it was framed, and a match of the same picture still closes", () => {
|
||||
it("crops a reportage full-length without a sports fill, 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 room = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" })!;
|
||||
expect(inside(room.rect, p)).toBe(true);
|
||||
expect(room.rect.x1 - room.rect.x0).toBeLessThan(0.92);
|
||||
const match = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "sport" });
|
||||
expect(match).not.toBeNull();
|
||||
if (!match) return;
|
||||
@@ -290,8 +301,10 @@ describe("reportage", () => {
|
||||
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" });
|
||||
expect(c).toBeNull();
|
||||
const c = compose({ ...frame, people: [subject, hand], balls: [] }, null, { context: "reportage" })!;
|
||||
expect(inside(c.rect, subject)).toBe(true);
|
||||
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.5);
|
||||
});
|
||||
|
||||
it("drops a person the frame already cut off, and keeps the full-length around the subject", () => {
|
||||
@@ -304,7 +317,7 @@ describe("reportage", () => {
|
||||
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);
|
||||
expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.7);
|
||||
});
|
||||
|
||||
it("crops the whole person at the car, not the sharper face in the window", () => {
|
||||
@@ -343,8 +356,11 @@ 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).toBeNull();
|
||||
})!;
|
||||
expect(c.rect.y0).toBeLessThanOrEqual(front.y0);
|
||||
expect(c.rect.y1).toBeGreaterThan(front.y1 - 1e-6);
|
||||
expect(c.rect.x0).toBeLessThanOrEqual(front.x0);
|
||||
expect(c.rect.x1).toBeGreaterThanOrEqual(front.x1);
|
||||
});
|
||||
|
||||
it("leaves a wide shot of small figures as it was framed", () => {
|
||||
@@ -440,3 +456,70 @@ describe("hands, feet, the ball and an open plan", () => {
|
||||
for (const p of crowd) expect(inside(c.rect, p)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clean framing, lead room, wide zoom, peak contact", () => {
|
||||
it("does not expand the subject with a soft body near the ball", () => {
|
||||
const sharp = { ...person(0.4, 0.2, 0.52, 0.85), sharpness: 1 };
|
||||
const soft = { ...person(0.2, 0.05, 0.45, 0.95), sharpness: 0.2 };
|
||||
const ball = { x0: 0.45, y0: 0.72, x1: 0.5, y1: 0.78, score: 0.9 };
|
||||
const s = findSubject({ ...frame, people: [sharp, soft], balls: [ball] }, null, { sport: "futebol" })!;
|
||||
expect(s.reason).toBe("ball");
|
||||
expect(s.people).toEqual([sharp]);
|
||||
expect(s.box.x0).toBeGreaterThan(soft.x0 + 0.05);
|
||||
});
|
||||
|
||||
it("leaves a tiny soft scrap out of a sport crop when a cleaner frame fits", () => {
|
||||
const main = { ...person(0.4, 0.15, 0.58, 0.9), sharpness: 1 };
|
||||
const scrap = { ...person(0.05, 0.7, 0.12, 0.85), sharpness: 0.2 };
|
||||
const c = compose({ ...frame, people: [main, scrap], balls: [] }, null, { framing: "full", context: "sport" })!;
|
||||
const share = Math.max(0, Math.min(c.rect.x1, scrap.x1) - Math.max(c.rect.x0, scrap.x0)) * Math.max(0, Math.min(c.rect.y1, scrap.y1) - Math.max(c.rect.y0, scrap.y0));
|
||||
expect(share / ((scrap.x1 - scrap.x0) * (scrap.y1 - scrap.y0))).toBeLessThan(0.05);
|
||||
});
|
||||
|
||||
it("puts lead room on the facing side of the subject", () => {
|
||||
const body = { ...person(0.35, 0.15, 0.55, 0.9), sharpness: 1 };
|
||||
const face = { x0: 0.48, y0: 0.16, x1: 0.54, y1: 0.28 };
|
||||
expect(facingSide(body, [face], null)).toBe(1);
|
||||
const c = compose({ ...frame, people: [body], balls: [] }, null, { framing: "full", context: "sport", faces: [face] })!;
|
||||
const at = ((body.x0 + body.x1) / 2 - c.rect.x0) / (c.rect.x1 - c.rect.x0);
|
||||
expect(at).toBeLessThan(0.48);
|
||||
});
|
||||
|
||||
it("treats a zoom at its wide end as intentional framing", () => {
|
||||
expect(isWideZoomOpen({ focalLength: 15, range: [15, 35] })).toBe(true);
|
||||
expect(isWideZoomOpen({ focalLength: 35, range: [15, 35] })).toBe(false);
|
||||
expect(isWideZoomOpen({ focalLength: 135, range: [70, 200] })).toBe(false);
|
||||
const main = { ...person(0.4, 0.15, 0.58, 0.9), sharpness: 1 };
|
||||
expect(compose({ ...frame, people: [main], balls: [] }, null, { lens: { focalLength: 15, range: [15, 35] } })).toBeNull();
|
||||
});
|
||||
|
||||
it("scores peak ball contact higher than a distant ball", () => {
|
||||
const body = { ...person(0.4, 0.2, 0.55, 0.85), sharpness: 1, focus: 400 };
|
||||
const near = { x0: 0.48, y0: 0.7, x1: 0.52, y1: 0.76, score: 0.9 };
|
||||
const far = { x0: 0.75, y0: 0.3, x1: 0.79, y1: 0.36, score: 0.9 };
|
||||
const dNear = { ...frame, people: [body], balls: [near] };
|
||||
const dFar = { ...frame, people: [body], balls: [far] };
|
||||
const cNear = compose(dNear, null, { sport: "futebol" })!;
|
||||
const cFar = { ...cNear, ball: far, reason: "ball" as const };
|
||||
expect(frameScore(dNear, cNear)).toBeGreaterThan(frameScore(dFar, cFar));
|
||||
});
|
||||
|
||||
it("refuses a crop that only works at the delivery floor", () => {
|
||||
// Preview-sized file: minWidth is 1 — any crop sits on the floor, so leave as shot.
|
||||
const main = { ...person(0.4, 0.15, 0.6, 0.9), sharpness: 1 };
|
||||
expect(compose({ width: 2048, height: 1365, people: [main], balls: [] }, null, { minWidth: 1, framing: "full" })).toBeNull();
|
||||
// High floor with a subject that would need a fill near that floor.
|
||||
const far = { ...person(0.46, 0.35, 0.54, 0.55), sharpness: 1 };
|
||||
const ball = { x0: 0.49, y0: 0.5, x1: 0.52, y1: 0.54, score: 0.9 };
|
||||
const tight = compose({ ...frame, people: [far], balls: [ball] }, null, { minWidth: 0.68, framing: "tight", sport: "futebol" });
|
||||
if (tight) expect(tight.rect.x1 - tight.rect.x0).toBeGreaterThan(0.68 * 1.08);
|
||||
});
|
||||
|
||||
it("scores a lightly cropped frame above a heavy reframe of the same subject", () => {
|
||||
const body = { ...person(0.4, 0.15, 0.6, 0.9), sharpness: 1, focus: 400 };
|
||||
const d = { ...frame, people: [body], balls: [] };
|
||||
const wide = { rect: { x0: 0.1, y0: 0.05, x1: 0.9, y1: 0.95 }, subject: body, reason: "person" as const, people: 1 };
|
||||
const tight = { rect: { x0: 0.35, y0: 0.2, x1: 0.65, y1: 0.7 }, subject: body, reason: "person" as const, people: 1 };
|
||||
expect(frameScore(d, wide)).toBeGreaterThan(frameScore(d, tight));
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config";
|
||||
/** Pure tests. The default config migrates a database, which these do not need. */
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/**/*.test.ts"],
|
||||
include: ["src/**/*.test.ts", "test/compose.test.ts"],
|
||||
fileParallelism: false,
|
||||
},
|
||||
});
|
||||
@@ -5,7 +5,11 @@ import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { App } from "./App.js";
|
||||
|
||||
vi.mock("./library/realtime.js", () => ({ useLibraryLive: () => "live", onSocketLive: () => () => {} }));
|
||||
vi.mock("./library/realtime.js", () => ({
|
||||
useLibraryLive: () => "live",
|
||||
onSocketLive: () => () => {},
|
||||
isSocketLive: () => false,
|
||||
}));
|
||||
|
||||
const ME: Me = {
|
||||
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { isLocalId, offlineQueue } from "../offline/queue.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { reconcileSoftCrops } from "./softCropWatch.js";
|
||||
|
||||
@@ -8,7 +10,7 @@ const EVERY_MS = 4_000;
|
||||
/**
|
||||
* Desktop only: while signed in, notice Lightroom / Photo Mechanic soft-crop writes on local originals
|
||||
* and apply them as develop crops (same path as cropping in Revelar — including autopilot learning).
|
||||
* A colour class Photo Mechanic paints on the same file is copied onto the library photo.
|
||||
* Pick / stars / colour on the same file are copied onto the library photo (offline queue when still local).
|
||||
*/
|
||||
export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { enabled?: boolean; everyMs?: number }) {
|
||||
const { api, organization } = useAuth();
|
||||
@@ -19,9 +21,24 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const tick = async () => {
|
||||
try {
|
||||
await reconcileSoftCrops(async (id, photoId, color) => {
|
||||
await api.updatePhotos(id, [photoId], { colorLabel: color });
|
||||
});
|
||||
await reconcileSoftCrops(
|
||||
async (id, photoId, color) => {
|
||||
if (isLocalId(photoId)) {
|
||||
localPhotos.patch(photoId, { colorLabel: color });
|
||||
offlineQueue(id).add({ kind: "patch", ids: [photoId], patch: { colorLabel: color } });
|
||||
return;
|
||||
}
|
||||
await api.updatePhotos(id, [photoId], { colorLabel: color });
|
||||
},
|
||||
async (id, photoId, patch) => {
|
||||
if (isLocalId(photoId)) {
|
||||
localPhotos.patch(photoId, patch);
|
||||
offlineQueue(id).add({ kind: "patch", ids: [photoId], patch });
|
||||
return;
|
||||
}
|
||||
await api.updatePhotos(id, [photoId], patch);
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
/* older desktop without local_stat, or offline index miss */
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@ import type { ApiClient, EventSummary } from "@photoreport/sdk";
|
||||
import { useEffect } from "react";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { flushAllPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
|
||||
import { rememberPhotoFrame } from "./lightroomCrop.js";
|
||||
import { flushFailedPhotoFiles, flushRecentPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
|
||||
|
||||
const LOCAL = "local:";
|
||||
const idToSha = new Map<string, string>();
|
||||
@@ -14,18 +15,57 @@ function remember(id: string, sha256: string | null | undefined): void {
|
||||
idToSha.set(id, sha256);
|
||||
}
|
||||
|
||||
let shaByPhotoId: Map<string, string> | null = null;
|
||||
let shaByPhotoIdRaw = "";
|
||||
|
||||
/** Hash of the original on disk for this server photo, recorded when the file was uploaded. */
|
||||
function originalSha(photoId: string): string | null {
|
||||
if (!photoId || photoId.startsWith(LOCAL)) return null;
|
||||
let raw = "";
|
||||
try {
|
||||
raw = localStorage.getItem("pr.localmap") ?? "";
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!shaByPhotoId || raw !== shaByPhotoIdRaw) {
|
||||
const next = new Map<string, string>();
|
||||
try {
|
||||
const map = JSON.parse(raw || "{}") as Record<string, unknown>;
|
||||
for (const [sha, serverId] of Object.entries(map)) {
|
||||
if (!sha || typeof serverId !== "string" || !serverId) continue;
|
||||
next.set(serverId, sha);
|
||||
}
|
||||
} catch {
|
||||
// A broken map falls back to the sha the server stored.
|
||||
}
|
||||
shaByPhotoId = next;
|
||||
shaByPhotoIdRaw = raw;
|
||||
}
|
||||
return shaByPhotoId.get(photoId) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The file Lightroom has is the original on disk. Its hash is often not the sha the server stored
|
||||
* (that one can be the preview). Writing the server sha looks up a file that is not in the work folder.
|
||||
*/
|
||||
function diskSha(photoId: string, apiSha: string | null | undefined): string | null {
|
||||
const onDisk = originalSha(photoId);
|
||||
if (onDisk) return onDisk;
|
||||
if (apiSha) return apiSha;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The original Lightroom has open. The server hash can be the preview, which is not in the work folder. */
|
||||
export function fileShaForPhoto(photoId: string, apiSha: string | null | undefined): string | null {
|
||||
return diskSha(photoId, apiSha);
|
||||
}
|
||||
|
||||
function shaOf(id: string): string | null {
|
||||
if (id.startsWith(LOCAL)) return id.slice(LOCAL.length);
|
||||
const onDisk = originalSha(id);
|
||||
if (onDisk) return onDisk;
|
||||
const known = idToSha.get(id);
|
||||
if (known) return known;
|
||||
try {
|
||||
const map = JSON.parse(localStorage.getItem("pr.localmap") ?? "{}") as Record<string, string>;
|
||||
for (const [sha, serverId] of Object.entries(map)) {
|
||||
if (serverId === id) return sha;
|
||||
}
|
||||
} catch {
|
||||
// A broken map only means this photo is written the next time it is seen.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -110,10 +150,12 @@ function writeKnown(sha: string, update: FileMarkUpdate, developSeq: number, pho
|
||||
export function onFileMarkMessage(api: ApiClient, message: LibraryMessage): void {
|
||||
if (!isDesktop()) return;
|
||||
if (message.type === "photo.added") {
|
||||
remember(message.photo.id, message.photo.sha256);
|
||||
const sha = diskSha(message.photo.id, message.photo.sha256);
|
||||
if (!sha) return;
|
||||
remember(message.photo.id, sha);
|
||||
const marks = marksOf(message.photo.flag, message.photo.rating, message.photo.colorLabel, message.photo.delivery === "DONE");
|
||||
// Always push the resolved IPTC (and any pick / develop) into the work-folder file Lightroom imports.
|
||||
writeKnown(message.photo.sha256, marks ?? {}, message.photo.developSeq, message.photo.id, api, true);
|
||||
writeKnown(sha, marks ?? {}, message.photo.developSeq, message.photo.id, api, true);
|
||||
return;
|
||||
}
|
||||
if (message.type === "photo.updated") {
|
||||
@@ -161,8 +203,10 @@ function marksOf(flag: string, rating: number, colorLabel: string, sent: boolean
|
||||
export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<void> {
|
||||
if (!isDesktop() || !orgId || caughtUp.has(orgId)) return;
|
||||
caughtUp.add(orgId);
|
||||
// Re-apply anything already remembered (survives a desktop update that swallowed earlier writes).
|
||||
flushAllPhotoFiles();
|
||||
// Only retry writes that failed. Rewriting every remembered original first left today's files
|
||||
// waiting behind thousands of older JPEGs, so Lightroom imported them with no metadata.
|
||||
flushFailedPhotoFiles();
|
||||
flushRecentPhotoFiles();
|
||||
let events: EventSummary[] = [];
|
||||
try {
|
||||
events = (await api.listEvents(orgId)).events.filter((event) => eventIsCurrent(event, Date.now()));
|
||||
@@ -186,11 +230,14 @@ export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<v
|
||||
offset += page.photos.length;
|
||||
if (!page.photos.length) break;
|
||||
for (const photo of page.photos) {
|
||||
remember(photo.id, photo.sha256);
|
||||
const sha = diskSha(photo.id, photo.sha256);
|
||||
if (!sha) continue;
|
||||
rememberPhotoFrame(sha, photo.width, photo.height);
|
||||
remember(photo.id, sha);
|
||||
const sent = photo.delivery === "DONE";
|
||||
const marks = marksOf(photo.flag, photo.rating, photo.colorLabel, sent);
|
||||
// Picks, develop and the resolved IPTC (event template + overrides) go into the file Lightroom imports.
|
||||
writeKnown(photo.sha256, marks ?? {}, photo.developSeq, photo.id, api, true);
|
||||
writeKnown(sha, marks ?? {}, photo.developSeq, photo.id, api, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,13 +249,22 @@ export function FileMarksSync({ api, orgId }: { api: ApiClient; orgId: string })
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
void catchUpFileMarks(api, orgId);
|
||||
// The first pass often runs before the session token is ready. Retry until one pass sticks.
|
||||
// A write also fails while the JPEG is still in the ingest folder; retry those, not the whole library.
|
||||
const retry = window.setInterval(() => {
|
||||
flushFailedPhotoFiles();
|
||||
void catchUpFileMarks(api, orgId);
|
||||
}, 15 * 1000);
|
||||
// Periodic retry: a one-shot catch-up at login misses photos that arrive later, and a failed
|
||||
// ftp_write_xmp must not leave the work folder empty for the rest of the day.
|
||||
const timer = window.setInterval(() => {
|
||||
caughtUp.delete(orgId);
|
||||
void catchUpFileMarks(api, orgId);
|
||||
}, 10 * 60 * 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
return () => {
|
||||
window.clearInterval(retry);
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [api, orgId]);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fromLightroomEdges, toLightroomEdges } from "./lightroomCrop.js";
|
||||
|
||||
/** PSR12211.JPG: a 3:2 crop with a strong straighten. Written raw, Lightroom levelled it to about 1.21. */
|
||||
const shot = { left: 0.024609, top: 0.078821, right: 0.799609, bottom: 0.853821 };
|
||||
const angle = -5.9;
|
||||
const width = 6000;
|
||||
const height = 4000;
|
||||
|
||||
function sides(rect: { left: number; top: number; right: number; bottom: number }): { w: number; h: number } {
|
||||
return { w: rect.right - rect.left, h: rect.bottom - rect.top };
|
||||
}
|
||||
|
||||
describe("Lightroom crop corners", () => {
|
||||
it("keeps the photograph's aspect after Lightroom levels the straighten", () => {
|
||||
const stored = toLightroomEdges(shot, angle, width, height);
|
||||
const shown = fromLightroomEdges(stored, angle, width, height);
|
||||
const got = sides(shown);
|
||||
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
|
||||
expect(stored.left).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.top).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.right).toBeLessThanOrEqual(1);
|
||||
expect(stored.bottom).toBeLessThanOrEqual(1);
|
||||
const pxW = got.w * width;
|
||||
const pxH = got.h * height;
|
||||
expect(pxW / pxH).toBeCloseTo(width / height, 3);
|
||||
});
|
||||
|
||||
it("shrinks a crop that would leave the photo once it is turned", () => {
|
||||
const full = { left: 0.01, top: 0.01, right: 0.99, bottom: 0.99 };
|
||||
const stored = toLightroomEdges(full, 2.64, width, height);
|
||||
expect(stored.left).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.top).toBeGreaterThanOrEqual(0);
|
||||
expect(stored.right).toBeLessThanOrEqual(1);
|
||||
expect(stored.bottom).toBeLessThanOrEqual(1);
|
||||
const shown = fromLightroomEdges(stored, 2.64, width, height);
|
||||
const got = sides(shown);
|
||||
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
|
||||
expect(got.w).toBeLessThan(0.98);
|
||||
});
|
||||
|
||||
it("leaves a level crop untouched", () => {
|
||||
const rect = { left: 0.1, top: 0.1, right: 0.8, bottom: 0.8 };
|
||||
expect(toLightroomEdges(rect, 0, width, height)).toEqual(rect);
|
||||
expect(fromLightroomEdges(rect, 0, width, height)).toEqual(rect);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Lightroom stores a crop as two opposite corners plus an angle. It then turns those corners
|
||||
* back around the crop centre, and the levelled rectangle is what the crop tool shows.
|
||||
* The app's crop is already that levelled rectangle (the photograph's own aspect: equal
|
||||
* width and height in frame fractions). Writing it straight through makes the levelled
|
||||
* result a different proportion, which the crop tool labels Custom.
|
||||
*/
|
||||
|
||||
export interface CropEdges {
|
||||
left: number;
|
||||
top: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
}
|
||||
|
||||
export interface PhotoFrame {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
const frames = new Map<string, PhotoFrame>();
|
||||
|
||||
/** Pixel size of a local original, so a later read can turn Lightroom's corners back into the levelled crop. */
|
||||
export function rememberPhotoFrame(sha256: string, width: number | null | undefined, height: number | null | undefined): void {
|
||||
if (!sha256) return;
|
||||
if (typeof width !== "number" || typeof height !== "number") return;
|
||||
if (!(width > 0) || !(height > 0)) return;
|
||||
frames.set(sha256, { width, height });
|
||||
}
|
||||
|
||||
export function photoFrame(sha256: string): PhotoFrame | null {
|
||||
return frames.get(sha256) ?? null;
|
||||
}
|
||||
|
||||
function turn(x: number, y: number, cx: number, cy: number, deg: number): [number, number] {
|
||||
const th = (deg * Math.PI) / 180;
|
||||
const dx = x - cx;
|
||||
const dy = y - cy;
|
||||
const c = Math.cos(th);
|
||||
const s = Math.sin(th);
|
||||
return [dx * c - dy * s + cx, dx * s + dy * c + cy];
|
||||
}
|
||||
|
||||
/** Top-left frame fractions as pixels with y growing up, the space the corner rotation is defined in. */
|
||||
function pixel(x: number, yTop: number, width: number, height: number): [number, number] {
|
||||
return [x * width, (1 - yTop) * height];
|
||||
}
|
||||
|
||||
function shrunk(rect: CropEdges, scale: number): CropEdges {
|
||||
const cx = (rect.left + rect.right) / 2;
|
||||
const cy = (rect.top + rect.bottom) / 2;
|
||||
const halfW = ((rect.right - rect.left) / 2) * scale;
|
||||
const halfH = ((rect.bottom - rect.top) / 2) * scale;
|
||||
return {
|
||||
left: cx - halfW,
|
||||
top: cy - halfH,
|
||||
right: cx + halfW,
|
||||
bottom: cy + halfH,
|
||||
};
|
||||
}
|
||||
|
||||
function cornersFit(rect: CropEdges, angle: number, width: number, height: number): boolean {
|
||||
const ul = pixel(rect.left, rect.top, width, height);
|
||||
const lr = pixel(rect.right, rect.bottom, width, height);
|
||||
const cx = (ul[0] + lr[0]) / 2;
|
||||
const cy = (ul[1] + lr[1]) / 2;
|
||||
const a = -angle;
|
||||
const pts: Array<[number, number]> = [
|
||||
pixel(rect.left, rect.top, width, height),
|
||||
pixel(rect.right, rect.top, width, height),
|
||||
pixel(rect.right, rect.bottom, width, height),
|
||||
pixel(rect.left, rect.bottom, width, height),
|
||||
];
|
||||
const eps = 0.5;
|
||||
for (const [x, y] of pts) {
|
||||
const [rx, ry] = turn(x, y, cx, cy, a);
|
||||
if (rx < -eps || ry < -eps || rx > width + eps || ry > height + eps) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function storedEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
|
||||
const ul = pixel(rect.left, rect.top, width, height);
|
||||
const lr = pixel(rect.right, rect.bottom, width, height);
|
||||
const cx = (ul[0] + lr[0]) / 2;
|
||||
const cy = (ul[1] + lr[1]) / 2;
|
||||
const a = -angle;
|
||||
const sul = turn(ul[0], ul[1], cx, cy, a);
|
||||
const slr = turn(lr[0], lr[1], cx, cy, a);
|
||||
return {
|
||||
left: sul[0] / width,
|
||||
top: 1 - sul[1] / height,
|
||||
right: slr[0] / width,
|
||||
bottom: 1 - slr[1] / height,
|
||||
};
|
||||
}
|
||||
|
||||
function ordered(rect: CropEdges): boolean {
|
||||
if (!(rect.left < rect.right && rect.top < rect.bottom)) return false;
|
||||
if (rect.left < -0.000001 || rect.top < -0.000001) return false;
|
||||
if (rect.right > 1.000001 || rect.bottom > 1.000001) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Corners to write for `crs:Crop*`. `rect` is the levelled crop (what the tool should show).
|
||||
* A non-zero angle turns those corners about the crop centre, then shrinks until they stay on the photo.
|
||||
*/
|
||||
export function toLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
|
||||
if (!(width > 0) || !(height > 0)) return rect;
|
||||
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
|
||||
let scale = 1;
|
||||
let fitted = rect;
|
||||
for (let i = 0; i < 80; i++) {
|
||||
fitted = shrunk(rect, scale);
|
||||
const stored = storedEdges(fitted, angle, width, height);
|
||||
if (cornersFit(fitted, angle, width, height) && ordered(stored)) return stored;
|
||||
scale -= 0.012;
|
||||
if (scale < 0.08) break;
|
||||
}
|
||||
return storedEdges(fitted, angle, width, height);
|
||||
}
|
||||
|
||||
/** The levelled crop Lightroom shows for corners it stored. Inverse of `toLightroomEdges` when nothing was shrunk. */
|
||||
export function fromLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
|
||||
if (!(width > 0) || !(height > 0)) return rect;
|
||||
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
|
||||
const ul = pixel(rect.left, rect.top, width, height);
|
||||
const lr = pixel(rect.right, rect.bottom, width, height);
|
||||
const cx = (ul[0] + lr[0]) / 2;
|
||||
const cy = (ul[1] + lr[1]) / 2;
|
||||
const a = -angle;
|
||||
const uul = turn(ul[0], ul[1], cx, cy, -a);
|
||||
const ulr = turn(lr[0], lr[1], cx, cy, -a);
|
||||
return {
|
||||
left: uul[0] / width,
|
||||
top: 1 - uul[1] / height,
|
||||
right: ulr[0] / width,
|
||||
bottom: 1 - ulr[1] / height,
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,23 @@ describe("Lightroom sidecar", () => {
|
||||
expect(xml).not.toContain("crs:Shadows2012");
|
||||
});
|
||||
|
||||
it("turns a straightened crop so Lightroom still shows the photograph's aspect", () => {
|
||||
const xml = lightroomXmp(
|
||||
JSON.stringify({
|
||||
crop: {
|
||||
geometry: {
|
||||
angle: -5.9,
|
||||
rect: { x0: 0.024609, y0: 0.078821, x1: 0.799609, y1: 0.853821 },
|
||||
aspect: [6000, 4000],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(xml).toContain('crs:CropAngle="-5.90"');
|
||||
expect(xml).not.toContain('crs:CropLeft="0.024609"');
|
||||
expect(xml).not.toContain('crs:CropTop="0.078821"');
|
||||
});
|
||||
|
||||
it("writes a soft crop in the same crs fields Lightroom and Photo Mechanic read", () => {
|
||||
const xml = lightroomXmp(JSON.stringify({ crop: { geometry: { angle: -1.91, rect: { x0: 0, y0: 0.126385, x1: 0.861387, y1: 0.926887 } } } }));
|
||||
expect(xml).toContain('crs:HasCrop="True"');
|
||||
@@ -60,6 +77,7 @@ describe("Lightroom sidecar", () => {
|
||||
creator: "Fotógrafo / PhotoReport.pt",
|
||||
},
|
||||
);
|
||||
expect(xml).toContain("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Pavlidis</rdf:li></rdf:Alt></dc:title>");
|
||||
expect(xml).toContain('dc:title="Pavlidis"');
|
||||
expect(xml).toContain("Águas Santas Milaneza x SL Benfica, em Maia");
|
||||
expect(xml).toContain('photoshop:City="Maia"');
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { DevelopState, EditCommand } from "@photoreport/contracts";
|
||||
import { cropFromXmp } from "@photoreport/metadata";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { fromLightroomEdges, photoFrame, toLightroomEdges, type PhotoFrame } from "./lightroomCrop.js";
|
||||
|
||||
/** Soft crop written as crs:Crop* (same numbers SoftCropGuide / Photo Mechanic draw). */
|
||||
/** Soft crop in the app: the levelled rectangle. The file stores Lightroom's turned corners. */
|
||||
export interface SoftCrop {
|
||||
left: number;
|
||||
top: number;
|
||||
@@ -150,9 +153,12 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
|
||||
const caption = text("caption");
|
||||
const creator = text("creator");
|
||||
const keywords = Array.isArray(iptc.keywords) ? iptc.keywords.map((k) => k.trim()).filter(Boolean) : [];
|
||||
let children = "";
|
||||
if (title) {
|
||||
need("dc", "http://purl.org/dc/elements/1.1/");
|
||||
// Attribute: shells that only copy attributes onto the camera description. Element: Lightroom's Read Metadata.
|
||||
attrs.push(`dc:title="${xmlAttr(title)}"`);
|
||||
children += `<dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlText(title)}</rdf:li></rdf:Alt></dc:title>`;
|
||||
}
|
||||
if (headline) {
|
||||
need("photoshop", "http://ns.adobe.com/photoshop/1.0/");
|
||||
@@ -182,7 +188,6 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
|
||||
need("photoshop", "http://ns.adobe.com/photoshop/1.0/");
|
||||
attrs.push(`photoshop:Source="${xmlAttr(source)}"`);
|
||||
}
|
||||
let children = "";
|
||||
if (caption) {
|
||||
need("dc", "http://purl.org/dc/elements/1.1/");
|
||||
children += `<dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlText(caption)}</rdf:li></rdf:Alt></dc:description>`;
|
||||
@@ -199,7 +204,7 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
|
||||
}
|
||||
|
||||
/** Only the sliders that are actually set. Missing ones stay out of the sidecar, so Lightroom is not given a preset. */
|
||||
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc): string | null {
|
||||
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc, frame?: PhotoFrame | null): string | null {
|
||||
let doc: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = JSON.parse(settings) as unknown;
|
||||
@@ -241,12 +246,14 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
|
||||
if (sharpen !== undefined) attrs.push(`crs:Sharpness="${crsNumber(sharpen, 0)}"`);
|
||||
if (nr !== undefined) attrs.push(`crs:ColorNoiseReduction="${crsNumber(nr, 0)}"`);
|
||||
if (crop) {
|
||||
const size = frameOf(doc) ?? frame ?? null;
|
||||
const edges = size ? toLightroomEdges(crop, crop.angle, size.width, size.height) : crop;
|
||||
attrs.push(
|
||||
`crs:HasCrop="True"`,
|
||||
`crs:CropLeft="${crop.left.toFixed(6)}"`,
|
||||
`crs:CropTop="${crop.top.toFixed(6)}"`,
|
||||
`crs:CropRight="${crop.right.toFixed(6)}"`,
|
||||
`crs:CropBottom="${crop.bottom.toFixed(6)}"`,
|
||||
`crs:CropLeft="${edges.left.toFixed(6)}"`,
|
||||
`crs:CropTop="${edges.top.toFixed(6)}"`,
|
||||
`crs:CropRight="${edges.right.toFixed(6)}"`,
|
||||
`crs:CropBottom="${edges.bottom.toFixed(6)}"`,
|
||||
`crs:CropAngle="${crsNumber(crop.angle, 2)}"`,
|
||||
`crs:CropConstrainToUnitSquare="1"`,
|
||||
`crs:AlreadyApplied="False"`,
|
||||
@@ -276,7 +283,15 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
|
||||
|
||||
function foldEdit(doc: Record<string, unknown>, command: EditCommand): void {
|
||||
if (command.command === "develop.set") Object.assign(doc, command.params.values);
|
||||
else if (command.command === "crop.set") doc.crop = { geometry: { rect: command.params.rect, angle: command.params.angle ?? 0 } };
|
||||
else if (command.command === "crop.set") {
|
||||
const geometry: { rect: typeof command.params.rect; angle: number; aspect?: [number, number] } = {
|
||||
rect: command.params.rect,
|
||||
angle: command.params.angle ?? 0,
|
||||
};
|
||||
const aspect = command.params.aspect;
|
||||
if (aspect && aspect[0] > 0 && aspect[1] > 0) geometry.aspect = [aspect[0], aspect[1]];
|
||||
doc.crop = { geometry };
|
||||
}
|
||||
else if (command.command === "develop.merge") Object.assign(doc, command.params.partial);
|
||||
else if (command.command === "develop.reset") {
|
||||
for (const key of Object.keys(doc)) delete doc[key];
|
||||
@@ -297,6 +312,56 @@ export function settingsFromDevelop(state: DevelopState): string {
|
||||
return JSON.stringify(doc);
|
||||
}
|
||||
|
||||
function frameOf(doc: Record<string, unknown>): PhotoFrame | null {
|
||||
const crop = doc.crop;
|
||||
if (!crop || typeof crop !== "object") return null;
|
||||
const geometry = (crop as { geometry?: unknown }).geometry;
|
||||
if (!geometry || typeof geometry !== "object") return null;
|
||||
const aspect = (geometry as { aspect?: unknown }).aspect;
|
||||
if (!Array.isArray(aspect) || aspect.length < 2) return null;
|
||||
const width = aspect[0];
|
||||
const height = aspect[1];
|
||||
if (typeof width !== "number" || typeof height !== "number") return null;
|
||||
if (!(width > 0) || !(height > 0)) return null;
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function docOf(settings: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parsed = JSON.parse(settings) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
return parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Pixel size for this file: the crop's own aspect, then a size learned from the library. */
|
||||
export function frameForPhoto(sha256: string, settings: string): PhotoFrame | null {
|
||||
const doc = docOf(settings);
|
||||
if (doc) {
|
||||
const fromCrop = frameOf(doc);
|
||||
if (fromCrop) return fromCrop;
|
||||
}
|
||||
const known = photoFrame(sha256);
|
||||
if (known) return known;
|
||||
const local = localPhotos.bySha(sha256);
|
||||
if (local && local.width && local.height && local.width > 0 && local.height > 0) {
|
||||
return { width: local.width, height: local.height };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A straighten with no pixel size would be written as a different aspect. Hold the file until the size is known. */
|
||||
export function cropWaitsForFrame(settings: string, frame: PhotoFrame | null): boolean {
|
||||
const doc = docOf(settings);
|
||||
if (!doc) return false;
|
||||
const crop = cropOf(doc);
|
||||
if (!crop || Math.abs(crop.angle) < 0.05) return false;
|
||||
if (frameOf(doc) || frame) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function cropOf(doc: Record<string, unknown>): SoftCrop | null {
|
||||
const crop = doc.crop;
|
||||
if (!crop || typeof crop !== "object") return null;
|
||||
@@ -326,31 +391,82 @@ interface RememberedFile {
|
||||
iptc: FileIptc;
|
||||
}
|
||||
|
||||
/** Rows this session must write even when the stored history no longer fits. */
|
||||
const rememberedNow = new Map<string, RememberedFile>();
|
||||
|
||||
function loadRemembered(): Record<string, RememberedFile> {
|
||||
let all: Record<string, RememberedFile> = {};
|
||||
try {
|
||||
const raw = localStorage.getItem(FILE_MARKS_KEY);
|
||||
const parsed = raw ? (JSON.parse(raw) as unknown) : {};
|
||||
if (!parsed || typeof parsed !== "object") return {};
|
||||
return parsed as Record<string, RememberedFile>;
|
||||
if (parsed && typeof parsed === "object") all = parsed as Record<string, RememberedFile>;
|
||||
} catch {
|
||||
return {};
|
||||
all = {};
|
||||
}
|
||||
for (const [sha, row] of rememberedNow) {
|
||||
all[sha] = row;
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
function saveRemembered(all: Record<string, RememberedFile>): void {
|
||||
// Each row carries the develop JSON. A few thousand of them exceed what the web view will store,
|
||||
// and a failed save used to drop the write of the file Lightroom imports.
|
||||
const keys = Object.keys(all);
|
||||
if (keys.length > 4000) {
|
||||
for (const key of keys.slice(0, keys.length - 4000)) delete all[key];
|
||||
const kept = 400;
|
||||
if (keys.length > kept) {
|
||||
for (const key of keys.slice(0, keys.length - kept)) {
|
||||
if (rememberedNow.has(key)) continue;
|
||||
delete all[key];
|
||||
}
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(all));
|
||||
return;
|
||||
} catch {
|
||||
// A full localStorage must not stop the edit itself.
|
||||
// Still over the quota. Keep only what this session is writing.
|
||||
}
|
||||
const slim: Record<string, RememberedFile> = {};
|
||||
for (const [sha, row] of rememberedNow) {
|
||||
slim[sha] = row;
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(slim));
|
||||
} catch {
|
||||
// flushPhotoFile reads rememberedNow, so the file is still written this session.
|
||||
}
|
||||
}
|
||||
|
||||
const flushTimers = new Map<string, number>();
|
||||
let flushChain = Promise.resolve();
|
||||
const flushFailed = new Set<string>();
|
||||
const flushSoon: string[] = [];
|
||||
let flushRunning = false;
|
||||
|
||||
const FLUSH_TIMEOUT_MS = 20_000;
|
||||
|
||||
function enqueueFlush(sha256: string): void {
|
||||
if (!sha256) return;
|
||||
if (flushSoon.includes(sha256)) return;
|
||||
flushSoon.push(sha256);
|
||||
void runFlushQueue();
|
||||
}
|
||||
|
||||
async function runFlushQueue(): Promise<void> {
|
||||
if (flushRunning) return;
|
||||
flushRunning = true;
|
||||
try {
|
||||
while (flushSoon.length > 0) {
|
||||
const sha256 = flushSoon.shift();
|
||||
if (!sha256) break;
|
||||
await flushPhotoFile(sha256);
|
||||
}
|
||||
} finally {
|
||||
flushRunning = false;
|
||||
if (flushSoon.length > 0) {
|
||||
void runFlushQueue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleFlush(sha256: string): void {
|
||||
const pending = flushTimers.get(sha256);
|
||||
@@ -359,27 +475,60 @@ function scheduleFlush(sha256: string): void {
|
||||
sha256,
|
||||
window.setTimeout(() => {
|
||||
flushTimers.delete(sha256);
|
||||
flushChain = flushChain.then(() => flushPhotoFile(sha256)).catch(() => {});
|
||||
enqueueFlush(sha256);
|
||||
}, 400),
|
||||
);
|
||||
}
|
||||
|
||||
function invokeWithTimeout(command: string, args: Record<string, unknown>): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
reject(new Error("timeout"));
|
||||
}, FLUSH_TIMEOUT_MS);
|
||||
desktopInvoke(command, args).then(
|
||||
(value) => {
|
||||
window.clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
(err: unknown) => {
|
||||
window.clearTimeout(timer);
|
||||
reject(err);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function flushPhotoFile(sha256: string): Promise<void> {
|
||||
const row = loadRemembered()[sha256];
|
||||
const row = rememberedNow.get(sha256) ?? loadRemembered()[sha256];
|
||||
if (!row) return;
|
||||
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc));
|
||||
const frame = frameForPhoto(sha256, row.settings);
|
||||
// Without the pixel size a straighten is written as another aspect. Wait, and retry.
|
||||
if (cropWaitsForFrame(row.settings, frame)) {
|
||||
flushFailed.add(sha256);
|
||||
return;
|
||||
}
|
||||
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc), frame);
|
||||
if (!xml) return;
|
||||
// Write the file first. Soft-crop bookkeeping must not block or abort the Lightroom packet.
|
||||
try {
|
||||
await desktopInvoke("ftp_write_xmp", { sha256, xml });
|
||||
await invokeWithTimeout("ftp_write_xmp", { sha256, xml });
|
||||
flushFailed.delete(sha256);
|
||||
} catch (err) {
|
||||
// The original is often still in the ingest folder. Retry once it has been filed.
|
||||
flushFailed.add(sha256);
|
||||
console.error("ftp_write_xmp", sha256.slice(0, 12), err);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { noteOwnSoftCropWrite } = await import("./softCropWatch.js");
|
||||
const writtenFlag = row.sent || row.flag === "PICK" ? "PICK" : row.flag === "REJECT" ? "REJECT" : row.flag === "NONE" ? "NONE" : undefined;
|
||||
noteOwnSoftCropWrite(sha256, softCropFromSettings(row.settings), writtenFlag);
|
||||
const raw = cropFromXmp(xml);
|
||||
let noted = softCropFromSettings(row.settings);
|
||||
if (raw && frame && Math.abs(raw.angle) >= 0.05) {
|
||||
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
|
||||
noted = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
|
||||
}
|
||||
noteOwnSoftCropWrite(sha256, noted, writtenFlag);
|
||||
} catch {
|
||||
// Watcher is optional; the file already has the marks.
|
||||
}
|
||||
@@ -391,6 +540,35 @@ export function flushAllPhotoFiles(): void {
|
||||
for (const sha256 of Object.keys(loadRemembered())) scheduleFlush(sha256);
|
||||
}
|
||||
|
||||
/** Writes that failed (file still in ingest, or the shell was busy) — not the whole library. */
|
||||
export function flushFailedPhotoFiles(): void {
|
||||
if (!isDesktop()) return;
|
||||
for (const sha256 of flushFailed) scheduleFlush(sha256);
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos remembered most recently (today's event is at the end of the list). Written first,
|
||||
* so a catch-up that has not reached the server yet still updates the files Lightroom imports.
|
||||
*/
|
||||
export function flushRecentPhotoFiles(): void {
|
||||
if (!isDesktop()) return;
|
||||
const keys = Object.keys(loadRemembered());
|
||||
const start = Math.max(0, keys.length - 120);
|
||||
const recent = keys.slice(start);
|
||||
for (let index = recent.length - 1; index >= 0; index -= 1) {
|
||||
const sha256 = recent[index];
|
||||
if (!sha256) continue;
|
||||
scheduleFlush(sha256);
|
||||
}
|
||||
}
|
||||
|
||||
/** The original just moved into the work folder. Write the marks already waiting for it. */
|
||||
export function retryPhotoFile(sha256: string): void {
|
||||
if (!isDesktop() || !sha256) return;
|
||||
if (!loadRemembered()[sha256]) return;
|
||||
scheduleFlush(sha256);
|
||||
}
|
||||
|
||||
export interface FileMarkUpdate {
|
||||
settings?: string;
|
||||
flag?: string | null;
|
||||
@@ -433,6 +611,7 @@ export function writePhotoFile(sha256: string, update: FileMarkUpdate): void {
|
||||
iptc: "iptc" in update ? iptcOf(update.iptc) : prev.iptc,
|
||||
};
|
||||
all[sha256] = next;
|
||||
rememberedNow.set(sha256, next);
|
||||
saveRemembered(all);
|
||||
scheduleFlush(sha256);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { cullPatchFromMarks, hasDiskMarks, marksFromXmpText } from "./readFileMarks.js";
|
||||
|
||||
describe("marksFromXmpText", () => {
|
||||
it("reads pick without stars", () => {
|
||||
const marks = marksFromXmpText(`<xmpDM:pick>1</xmpDM:pick><xmp:Rating>0</xmp:Rating>`);
|
||||
expect(marks.flag).toBe("PICK");
|
||||
expect(marks.rating).toBe(0);
|
||||
expect(hasDiskMarks(marks)).toBe(true);
|
||||
expect(cullPatchFromMarks(marks)).toEqual({ flag: "PICK" });
|
||||
});
|
||||
|
||||
it("turns stars into a pick when the flag is absent", () => {
|
||||
const marks = marksFromXmpText(`<xmp:Rating>4</xmp:Rating>`);
|
||||
expect(cullPatchFromMarks(marks)).toEqual({ flag: "PICK", rating: 4 });
|
||||
});
|
||||
|
||||
it("reads soft crop edges", () => {
|
||||
const marks = marksFromXmpText(
|
||||
`crs:HasCrop="True" crs:CropLeft="0.1" crs:CropTop="0.05" crs:CropRight="0.9" crs:CropBottom="0.95" crs:CropAngle="1.5"`,
|
||||
);
|
||||
expect(marks.crop).toEqual({ left: 0.1, top: 0.05, right: 0.9, bottom: 0.95, angle: 1.5 });
|
||||
expect(hasDiskMarks(marks)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import {
|
||||
colorClassFromXmp,
|
||||
cropFromXmp,
|
||||
libraryMarksFromXmp,
|
||||
xmpPacketFromJpeg,
|
||||
type SoftCrop,
|
||||
type XmpColor,
|
||||
} from "@photoreport/metadata";
|
||||
import type { ColorLabel, PhotoFlag } from "@photoreport/contracts";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { localXmpText } from "./softCrop.js";
|
||||
|
||||
/** Cull marks and soft crop read from a JPEG / XMP packet on disk. */
|
||||
export interface DiskFileMarks {
|
||||
flag: PhotoFlag;
|
||||
rating: number;
|
||||
colorLabel: ColorLabel;
|
||||
crop: SoftCrop | null;
|
||||
}
|
||||
|
||||
const EMPTY: DiskFileMarks = {
|
||||
flag: "NONE",
|
||||
rating: 0,
|
||||
colorLabel: "NONE",
|
||||
crop: null,
|
||||
};
|
||||
|
||||
/** Parse cull marks and soft crop from an XMP packet (embedded or sidecar text). */
|
||||
export function marksFromXmpText(xmp: string | null | undefined): DiskFileMarks {
|
||||
if (!xmp) return { ...EMPTY };
|
||||
const marks = libraryMarksFromXmp(xmp);
|
||||
const color = colorClassFromXmp(xmp);
|
||||
let flag: PhotoFlag = "NONE";
|
||||
if (marks.flag === "PICK" || marks.flag === "REJECT") flag = marks.flag;
|
||||
let rating = 0;
|
||||
if (typeof marks.rating === "number" && marks.rating > 0) rating = Math.min(5, marks.rating);
|
||||
let colorLabel: ColorLabel = "NONE";
|
||||
if (color && color !== "NONE") colorLabel = color;
|
||||
else if (
|
||||
marks.colorLabel === "RED" ||
|
||||
marks.colorLabel === "YELLOW" ||
|
||||
marks.colorLabel === "GREEN" ||
|
||||
marks.colorLabel === "BLUE" ||
|
||||
marks.colorLabel === "PURPLE"
|
||||
) {
|
||||
colorLabel = marks.colorLabel;
|
||||
}
|
||||
return {
|
||||
flag,
|
||||
rating,
|
||||
colorLabel,
|
||||
crop: cropFromXmp(xmp),
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse marks from JPEG bytes (hand import / FTP original). */
|
||||
export function marksFromJpegBytes(bytes: ArrayBuffer | Uint8Array): DiskFileMarks {
|
||||
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
||||
return marksFromXmpText(xmpPacketFromJpeg(view));
|
||||
}
|
||||
|
||||
/** True when the packet carries something the library should keep. */
|
||||
export function hasDiskMarks(marks: DiskFileMarks): boolean {
|
||||
if (marks.flag !== "NONE") return true;
|
||||
if (marks.rating > 0) return true;
|
||||
if (marks.colorLabel !== "NONE") return true;
|
||||
if (marks.crop) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Library patch for cull fields only (crop is a develop op). */
|
||||
export function cullPatchFromMarks(marks: DiskFileMarks): {
|
||||
flag?: PhotoFlag;
|
||||
rating?: number;
|
||||
colorLabel?: ColorLabel;
|
||||
} {
|
||||
const patch: { flag?: PhotoFlag; rating?: number; colorLabel?: ColorLabel } = {};
|
||||
if (marks.flag !== "NONE") patch.flag = marks.flag;
|
||||
else if (marks.rating > 0) patch.flag = "PICK";
|
||||
if (marks.rating > 0) patch.rating = marks.rating;
|
||||
if (marks.colorLabel !== "NONE") patch.colorLabel = marks.colorLabel;
|
||||
return patch;
|
||||
}
|
||||
|
||||
/** Soft crop as the develop command Revelar / the offline queue already understand. */
|
||||
export function cropCommandFromMarks(marks: DiskFileMarks): {
|
||||
command: "crop.set";
|
||||
params: {
|
||||
rect: { x0: number; y0: number; x1: number; y1: number };
|
||||
angle: number;
|
||||
aspect: null;
|
||||
};
|
||||
} | null {
|
||||
if (!marks.crop) return null;
|
||||
return {
|
||||
command: "crop.set",
|
||||
params: {
|
||||
rect: {
|
||||
x0: marks.crop.left,
|
||||
y0: marks.crop.top,
|
||||
x1: marks.crop.right,
|
||||
y1: marks.crop.bottom,
|
||||
},
|
||||
angle: marks.crop.angle,
|
||||
aspect: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Read marks for a work-folder original already known by SHA (catalog / local index). */
|
||||
export async function marksFromLocalSha(sha256: string): Promise<DiskFileMarks> {
|
||||
if (!isDesktop() || !sha256) return { ...EMPTY };
|
||||
const xmp = await localXmpText(sha256);
|
||||
return marksFromXmpText(xmp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read marks from a JPEG still in the local FTP ingest tree (path from `ftp_take`).
|
||||
* Prefer `marksFromLocalSha` after `ftp_info` (sidecar + embedded). This path only sees the embedded packet.
|
||||
*/
|
||||
export async function marksFromFtpPath(path: string): Promise<DiskFileMarks> {
|
||||
if (!isDesktop() || !path) return { ...EMPTY };
|
||||
try {
|
||||
const raw = await desktopInvoke<number[] | Uint8Array>("ftp_read", { path });
|
||||
const bytes = raw instanceof Uint8Array ? raw : new Uint8Array(raw);
|
||||
return marksFromJpegBytes(bytes);
|
||||
} catch {
|
||||
return { ...EMPTY };
|
||||
}
|
||||
}
|
||||
|
||||
export type { SoftCrop, XmpColor };
|
||||
@@ -1,5 +1,6 @@
|
||||
import { cropFromXmp, type SoftCrop, xmpPacketFromJpeg } from "@photoreport/metadata";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
|
||||
|
||||
const cache = new Map<string, SoftCrop | null>();
|
||||
const inflight = new Map<string, Promise<SoftCrop | null>>();
|
||||
@@ -39,7 +40,16 @@ export async function softCropFor(sha256: string): Promise<SoftCrop | null> {
|
||||
const work = (async () => {
|
||||
try {
|
||||
const xmp = await localXmpText(sha256);
|
||||
const crop = xmp ? cropFromXmp(xmp) : null;
|
||||
const raw = xmp ? cropFromXmp(xmp) : null;
|
||||
if (!raw || Math.abs(raw.angle) < 0.05) {
|
||||
cache.set(sha256, raw);
|
||||
return raw;
|
||||
}
|
||||
const frame = photoFrame(sha256);
|
||||
// The file stores turned corners. Without the photo size they are not the crop to draw.
|
||||
if (!frame) return raw;
|
||||
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
|
||||
const crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
|
||||
cache.set(sha256, crop);
|
||||
return crop;
|
||||
} catch {
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { colorClassFromXmp, cropFromXmp, type SoftCrop, type XmpColor } from "@photoreport/metadata";
|
||||
import { colorClassFromXmp, cropFromXmp, libraryMarksFromXmp, type SoftCrop, type XmpColor } from "@photoreport/metadata";
|
||||
import type { ColorLabel, PhotoFlag } from "@photoreport/contracts";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { offlineQueue } from "../offline/queue.js";
|
||||
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
|
||||
import { forgetSoftCrop, localXmpText } from "./softCrop.js";
|
||||
|
||||
/**
|
||||
* Watch local originals for soft-crop changes written outside this app (Lightroom / Photo Mechanic).
|
||||
* When the XMP crop changes, apply the same rectangle as a develop `crop.set` so Revelar, export and
|
||||
* the autopilot learner all see it — the same path as cropping inside the app.
|
||||
* Watch local originals for soft-crop and cull-mark changes written outside this app (Lightroom /
|
||||
* Photo Mechanic). Crop → develop `crop.set`; pick / stars / colour → library patch. Same path as
|
||||
* editing inside the app, including the autopilot learner.
|
||||
*/
|
||||
const STORE_KEY = "softcrop:watch";
|
||||
/** v2: re-read every watched file once after JPEG-sidecar + cull fixes (BIT-33124). */
|
||||
const STORE_KEY = "softcrop:watch:v2";
|
||||
const MAX_WATCH = 800;
|
||||
const OWN_WRITE_GRACE_MS = 4_000;
|
||||
|
||||
@@ -26,6 +29,8 @@ export interface WatchedSoftCrop {
|
||||
color?: string | undefined;
|
||||
/** Pick last written or read. A later change in Lightroom is applied once. */
|
||||
flag?: string | undefined;
|
||||
/** Stars last read from the file. */
|
||||
rating?: number | undefined;
|
||||
}
|
||||
|
||||
/** Return true when the crop was applied into an open develop session (skip a second queue write). */
|
||||
@@ -105,12 +110,21 @@ function cropsEqual(a: SoftCrop, b: SoftCrop): boolean {
|
||||
/** Apply a colour Photo Mechanic wrote into the original. */
|
||||
export type ApplyExternalColor = (orgId: string, photoId: string, color: XmpColor) => Promise<void>;
|
||||
|
||||
/** Apply pick / stars / colour from the file into the library. */
|
||||
export type ApplyExternalMarks = (
|
||||
orgId: string,
|
||||
photoId: string,
|
||||
patch: { flag?: PhotoFlag; rating?: number; colorLabel?: ColorLabel },
|
||||
) => Promise<void>;
|
||||
|
||||
/**
|
||||
* One pass: re-read soft crops whose file (or sidecar) mtime moved, apply as develop crop when the
|
||||
* rectangle changed, and copy a colour class Photo Mechanic wrote onto the library photo.
|
||||
* Returns how many photos received a new crop.
|
||||
* One pass: re-read soft crops and cull marks whose file (or sidecar) mtime moved.
|
||||
* Crop → develop; pick / stars / colour → library. Returns how many photos got a new crop.
|
||||
*/
|
||||
export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promise<number> {
|
||||
export async function reconcileSoftCrops(
|
||||
applyColor?: ApplyExternalColor,
|
||||
applyMarks?: ApplyExternalMarks,
|
||||
): Promise<number> {
|
||||
if (!isDesktop()) return 0;
|
||||
const rows = load();
|
||||
if (!rows.length) return 0;
|
||||
@@ -123,9 +137,9 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
|
||||
next.push(row);
|
||||
continue;
|
||||
}
|
||||
// A row saved before colours were copied has no `color`. Read it once even if the mtime is already known,
|
||||
// so a colour painted earlier still arrives. "" means we looked and the file names no colour.
|
||||
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs && row.color !== undefined) {
|
||||
// First pass (no color/flag yet) always re-reads; later only when the file moves.
|
||||
const seenCull = row.color !== undefined && row.flag !== undefined;
|
||||
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs && seenCull) {
|
||||
next.push(row);
|
||||
continue;
|
||||
}
|
||||
@@ -135,10 +149,70 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
|
||||
}
|
||||
forgetSoftCrop(row.sha256);
|
||||
const xmp = await localXmpText(row.sha256);
|
||||
const crop = xmp ? cropFromXmp(xmp) : null;
|
||||
const color = xmp ? colorClassFromXmp(xmp) : null;
|
||||
if (!xmp) {
|
||||
// No packet yet (sidecar still writing). Remember mtime; a later sidecar bumps it via local_stat.
|
||||
next.push({
|
||||
...row,
|
||||
mtimeMs: stat.mtimeMs || row.mtimeMs,
|
||||
color: row.color !== undefined ? row.color : "",
|
||||
flag: row.flag !== undefined ? row.flag : "NONE",
|
||||
rating: row.rating !== undefined ? row.rating : 0,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const rawCrop = cropFromXmp(xmp);
|
||||
// A straighten is stored as turned corners. Without the photo size those corners are not the crop we show.
|
||||
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05 && !photoFrame(row.sha256)) {
|
||||
next.push(row);
|
||||
continue;
|
||||
}
|
||||
let crop = rawCrop;
|
||||
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05) {
|
||||
const frame = photoFrame(row.sha256);
|
||||
if (frame) {
|
||||
const back = fromLightroomEdges(rawCrop, rawCrop.angle, frame.width, frame.height);
|
||||
crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: rawCrop.angle };
|
||||
}
|
||||
}
|
||||
const color = colorClassFromXmp(xmp);
|
||||
const marks = libraryMarksFromXmp(xmp);
|
||||
let colorApplied = color ? row.color : (row.color ?? "");
|
||||
if (color && color !== row.color && applyColor) {
|
||||
let flagApplied = row.flag ?? "NONE";
|
||||
let ratingApplied = row.rating ?? 0;
|
||||
const patch: { flag?: PhotoFlag; rating?: number; colorLabel?: ColorLabel } = {};
|
||||
if (color && color !== "NONE" && color !== row.color) {
|
||||
patch.colorLabel = color;
|
||||
colorApplied = color;
|
||||
}
|
||||
let nextFlag: PhotoFlag = "NONE";
|
||||
if (marks.flag === "PICK" || marks.flag === "REJECT") nextFlag = marks.flag;
|
||||
if (nextFlag !== (row.flag ?? "NONE") && nextFlag !== "NONE") {
|
||||
patch.flag = nextFlag;
|
||||
flagApplied = nextFlag;
|
||||
}
|
||||
const nextRating = typeof marks.rating === "number" && marks.rating > 0 ? marks.rating : 0;
|
||||
if (nextRating > 0 && nextRating !== (row.rating ?? 0)) {
|
||||
patch.rating = nextRating;
|
||||
ratingApplied = nextRating;
|
||||
if (!patch.flag && nextFlag === "NONE") patch.flag = "PICK";
|
||||
}
|
||||
if (Object.keys(patch).length && applyMarks) {
|
||||
try {
|
||||
await applyMarks(row.orgId, row.photoId, patch);
|
||||
} catch {
|
||||
if (applyColor && patch.colorLabel) {
|
||||
try {
|
||||
await applyColor(row.orgId, row.photoId, patch.colorLabel as XmpColor);
|
||||
} catch {
|
||||
next.push(row);
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
next.push(row);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else if (color && color !== row.color && applyColor) {
|
||||
try {
|
||||
await applyColor(row.orgId, row.photoId, color);
|
||||
colorApplied = color;
|
||||
@@ -149,7 +223,14 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
|
||||
}
|
||||
const fingerprint = softCropFingerprint(crop);
|
||||
if (!crop || fingerprint === row.fingerprint) {
|
||||
next.push({ ...row, mtimeMs: stat.mtimeMs || row.mtimeMs, fingerprint, color: colorApplied });
|
||||
next.push({
|
||||
...row,
|
||||
mtimeMs: stat.mtimeMs || row.mtimeMs,
|
||||
fingerprint,
|
||||
color: colorApplied,
|
||||
flag: flagApplied,
|
||||
rating: ratingApplied,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const command = {
|
||||
@@ -171,6 +252,8 @@ export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promi
|
||||
mtimeMs: stat.mtimeMs || row.mtimeMs,
|
||||
fingerprint,
|
||||
color: colorApplied,
|
||||
flag: flagApplied,
|
||||
rating: ratingApplied,
|
||||
ownWriteUntil: now + OWN_WRITE_GRACE_MS,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -42,6 +42,8 @@ export const t = {
|
||||
label: "sem ligação",
|
||||
waiting: (n: number) => (n === 1 ? "1 alteração à espera de ligação" : `${n} alterações à espera de ligação`),
|
||||
waitingHelp: "Feito sem ligação ao servidor: fica guardado neste computador e é enviado sozinho quando a ligação voltar.",
|
||||
pending: (n: number) => (n === 1 ? "1 alteração por enviar" : `${n} alterações por enviar`),
|
||||
pendingHelp: "A ligação está feita. Estas alterações seguem para o servidor.",
|
||||
queuedDelivery: "Sem ligação: o envio fica à espera e sai sozinho quando a ligação voltar.",
|
||||
editingOffline: "Sem ligação: as edições ficam guardadas neste computador e são enviadas quando a ligação voltar.",
|
||||
},
|
||||
@@ -1337,6 +1339,7 @@ export const t = {
|
||||
level: "Nivelar",
|
||||
autoCropHelp: "Recorte automático à volta de quem a foto é: a bola e quem a disputa, ou o grupo principal, sem cortar corpos a meio.",
|
||||
autoCropNone: "Não encontrei um assunto claro nesta foto para recortar.",
|
||||
autoCropKept: "A foto já está enquadrada à volta de quem está nela.",
|
||||
autoCropMissing: "O recorte automático ainda não está instalado neste servidor.",
|
||||
levelHelp: "Endireita a foto pelo horizonte ou pelas linhas verticais.",
|
||||
levelNone: "Não encontrei horizonte nem linhas verticais claras nesta foto: endireita com o ângulo.",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { SoftCrop } from "@photoreport/metadata";
|
||||
import type { ColorLabel, PhotoSummary } from "@photoreport/contracts";
|
||||
import { memo, useEffect, useRef, useState } from "react";
|
||||
import { fileShaForPhoto } from "../desktop/fileMarks.js";
|
||||
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
|
||||
import { softCropFor } from "../desktop/softCrop.js";
|
||||
import { watchSoftCropPhoto } from "../desktop/softCropWatch.js";
|
||||
import { t } from "../i18n.js";
|
||||
@@ -41,19 +43,23 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
|
||||
const [softCrop, setSoftCrop] = useState<SoftCrop | null>(null);
|
||||
useEffect(() => setImgFailed(false), [shown]);
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !photo.sha256) {
|
||||
const sha = fileShaForPhoto(photo.id, photo.sha256);
|
||||
if (!isDesktop() || !sha) {
|
||||
setSoftCrop(null);
|
||||
return;
|
||||
}
|
||||
if (orgId) watchSoftCropPhoto(orgId, photo.id, photo.sha256);
|
||||
if (orgId) {
|
||||
rememberPhotoFrame(sha, photo.width, photo.height);
|
||||
watchSoftCropPhoto(orgId, photo.id, sha);
|
||||
}
|
||||
let alive = true;
|
||||
void softCropFor(photo.sha256).then((crop) => {
|
||||
void softCropFor(sha).then((crop) => {
|
||||
if (alive) setSoftCrop(crop);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [orgId, photo.id, photo.sha256]);
|
||||
}, [orgId, photo.id, photo.sha256, photo.width, photo.height]);
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { localId, offlineQueue } from "../offline/queue.js";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { SnapshotMenu } from "./SnapshotMenu.js";
|
||||
import { retryPhotoFile } from "../desktop/lightroomSidecar.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
|
||||
|
||||
@@ -185,9 +186,43 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
} catch {
|
||||
/* no blob URLs here (tests): shown without a thumbnail */
|
||||
}
|
||||
localPhotos.put(localPhoto({ sha256: info.sha256, name: f.name, width: info.width, height: info.height, capturedAt, eventId, url }));
|
||||
// Preview strips XMP — read pick / stars / colour / soft crop from the indexed original (sidecar or embedded).
|
||||
const { marksFromLocalSha, cullPatchFromMarks, cropCommandFromMarks, hasDiskMarks } = await import(
|
||||
"../desktop/readFileMarks.js"
|
||||
);
|
||||
const disk = await marksFromLocalSha(info.sha256);
|
||||
const cull = cullPatchFromMarks(disk);
|
||||
localPhotos.put(
|
||||
localPhoto({
|
||||
sha256: info.sha256,
|
||||
name: f.name,
|
||||
width: info.width,
|
||||
height: info.height,
|
||||
capturedAt,
|
||||
eventId,
|
||||
url,
|
||||
...cull,
|
||||
}),
|
||||
);
|
||||
if (orgId) {
|
||||
const id = localId(info.sha256);
|
||||
if (hasDiskMarks(disk)) {
|
||||
if (Object.keys(cull).length) {
|
||||
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
|
||||
}
|
||||
const cropOp = cropCommandFromMarks(disk);
|
||||
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
|
||||
}
|
||||
// Always watch: marks written later in Photo Mechanic / Lightroom still land in the library.
|
||||
const { watchSoftCropPhoto } = await import("../desktop/softCropWatch.js");
|
||||
watchSoftCropPhoto(orgId, id, info.sha256);
|
||||
}
|
||||
// Culled before a restart (still offline): it comes back as it was left.
|
||||
for (const op of orgId ? offlineQueue(orgId).pending : []) if (op.kind === "patch" && op.ids.includes(localId(info.sha256))) localPhotos.patch(localId(info.sha256), op.patch as Partial<PhotoSummary>);
|
||||
for (const op of orgId ? offlineQueue(orgId).pending : []) {
|
||||
if (op.kind === "patch" && op.ids.includes(localId(info.sha256))) {
|
||||
localPhotos.patch(localId(info.sha256), op.patch as Partial<PhotoSummary>);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The preview is on screen. The next photo does not wait for this one's upload: a slow network must
|
||||
// not stop the grid or Revelar.
|
||||
@@ -208,7 +243,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
sentEvent = to.title;
|
||||
sentDate = to.date;
|
||||
}
|
||||
invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate }).catch(() => {});
|
||||
invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate })
|
||||
.then(() => {
|
||||
retryPhotoFile(info.sha256);
|
||||
})
|
||||
.catch(() => {});
|
||||
// Changes made to it meanwhile now go to the server's copy.
|
||||
if (photo && orgId) {
|
||||
offlineQueue(orgId).uploaded(info.sha256, photo.id);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js";
|
||||
import { retryPhotoFile } from "../desktop/lightroomSidecar.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
|
||||
import type { PreviewOf, UploadStatus } from "./uploads.js";
|
||||
@@ -112,7 +113,11 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
|
||||
path: f.path,
|
||||
event: filed ? eventLabel(filed) : (to?.title ?? ""),
|
||||
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
|
||||
}).catch(() => {});
|
||||
})
|
||||
.then(() => {
|
||||
retryPhotoFile(original.sha256);
|
||||
})
|
||||
.catch(() => {});
|
||||
} else {
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
|
||||
import { localId, offlineQueue } from "../offline/queue.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import type { DesktopOrigin } from "./uploads.js";
|
||||
|
||||
/** SHA-256 hex of the bytes (same fingerprint the desktop shell uses for the original). */
|
||||
@@ -74,6 +75,19 @@ export async function showLocalJpeg(args: {
|
||||
}
|
||||
const capturedAt = lisbonInstant(exifDateTime(previewBytes));
|
||||
const eventId = events ? eventForArrival(args.eventId ?? null, events, capturedAt) : (args.eventId ?? null);
|
||||
// Hand-dropped JPEGs keep embedded XMP. Desktop previews strip it — read the indexed original by SHA.
|
||||
const {
|
||||
marksFromJpegBytes,
|
||||
marksFromLocalSha,
|
||||
cullPatchFromMarks,
|
||||
cropCommandFromMarks,
|
||||
hasDiskMarks,
|
||||
} = await import("../desktop/readFileMarks.js");
|
||||
let disk = marksFromJpegBytes(previewBytes);
|
||||
if (!hasDiskMarks(disk) && origin && origin !== "original" && origin.sha256) {
|
||||
disk = await marksFromLocalSha(origin.sha256);
|
||||
}
|
||||
const cull = cullPatchFromMarks(disk);
|
||||
localPhotos.put(
|
||||
localPhoto({
|
||||
sha256,
|
||||
@@ -83,8 +97,23 @@ export async function showLocalJpeg(args: {
|
||||
capturedAt,
|
||||
eventId,
|
||||
url,
|
||||
...cull,
|
||||
}),
|
||||
);
|
||||
if (orgId) {
|
||||
const id = localId(sha256);
|
||||
if (hasDiskMarks(disk)) {
|
||||
if (Object.keys(cull).length) {
|
||||
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
|
||||
}
|
||||
const cropOp = cropCommandFromMarks(disk);
|
||||
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
|
||||
}
|
||||
if (isDesktop()) {
|
||||
const { watchSoftCropPhoto } = await import("../desktop/softCropWatch.js");
|
||||
watchSoftCropPhoto(orgId, id, sha256);
|
||||
}
|
||||
}
|
||||
if (orgId) {
|
||||
for (const op of offlineQueue(orgId).pending) {
|
||||
if (op.kind === "patch" && op.ids.includes(localId(sha256))) {
|
||||
|
||||
@@ -6,10 +6,24 @@ import { io } from "socket.io-client";
|
||||
export type LiveState = "connecting" | "live" | "offline";
|
||||
|
||||
const liveListeners = new Set<() => void>();
|
||||
let liveSockets = 0;
|
||||
|
||||
/** At least one library socket is connected. Several screens each open their own. */
|
||||
export function isSocketLive(): boolean {
|
||||
return liveSockets > 0;
|
||||
}
|
||||
|
||||
function noteSocket(up: boolean): void {
|
||||
if (up) liveSockets += 1;
|
||||
else liveSockets = Math.max(0, liveSockets - 1);
|
||||
if (!up) return;
|
||||
for (const fn of [...liveListeners]) fn();
|
||||
}
|
||||
|
||||
/** The library socket connected. Waiting edits go out on this, not on a timer. */
|
||||
export function onSocketLive(fn: () => void): () => void {
|
||||
liveListeners.add(fn);
|
||||
if (liveSockets > 0) fn();
|
||||
return () => liveListeners.delete(fn);
|
||||
}
|
||||
|
||||
@@ -33,17 +47,33 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa
|
||||
);
|
||||
},
|
||||
});
|
||||
let connected = false;
|
||||
const mark = (up: boolean) => {
|
||||
if (up === connected) return;
|
||||
connected = up;
|
||||
noteSocket(up);
|
||||
};
|
||||
socket.on("connect", () => {
|
||||
setState("live");
|
||||
for (const fn of liveListeners) fn();
|
||||
mark(true);
|
||||
});
|
||||
socket.on("disconnect", () => {
|
||||
setState("offline");
|
||||
mark(false);
|
||||
});
|
||||
socket.on("connect_error", () => {
|
||||
setState("offline");
|
||||
mark(false);
|
||||
});
|
||||
socket.on("disconnect", () => setState("offline"));
|
||||
socket.on("connect_error", () => setState("offline"));
|
||||
socket.on(LIBRARY_CHANNEL, (message: LibraryMessage) => handler.current(message));
|
||||
socket.on("desk", (command: DeskCommand) => {
|
||||
window.dispatchEvent(new CustomEvent("photoreport-desk", { detail: command }));
|
||||
});
|
||||
return () => {
|
||||
socket.off("connect");
|
||||
socket.off("disconnect");
|
||||
socket.off("connect_error");
|
||||
mark(false);
|
||||
socket.close();
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Detections } from "../../../api/src/composition/compose.js";
|
||||
import { YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf, PERSON, BALL } from "../../../api/src/composition/yolox.js";
|
||||
import { BACKPACK, BALL, HANDBAG, PERSON, SUITCASE, YOLOX_SIZE, decodeYolox, nmsKeep, sharpnessOf } from "../../../api/src/composition/yolox.js";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { kv } from "./kv.js";
|
||||
|
||||
@@ -96,7 +96,8 @@ export async function detectPreview(api: ApiClient, orgId: string, jpeg: ArrayBu
|
||||
const grey = new Uint8Array(greyW * greyH);
|
||||
for (let i = 0; i < grey.length; i++) grey[i] = Math.round(0.299 * rgba[i * 4]! + 0.587 * rgba[i * 4 + 1]! + 0.114 * rgba[i * 4 + 2]!);
|
||||
sharpnessOf(grey, greyW, greyH, people);
|
||||
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)) };
|
||||
const carried = nmsKeep(all.filter((d) => d.cls === BACKPACK || d.cls === HANDBAG || d.cls === SUITCASE));
|
||||
return { width, height, people, balls: nmsKeep(all.filter((d) => d.cls === BALL)), carried };
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
|
||||
@@ -156,7 +156,26 @@ export function eventForArrival(pinnedId: string | null, events: RoutedEvent[],
|
||||
if (Date.parse(pinned.ingestFrom) <= t && t <= Date.parse(pinned.ingestUntil)) return pinnedId;
|
||||
return routeLocally(events, at);
|
||||
}
|
||||
export function localPhoto(p: { sha256: string; name: string; width: number; height: number; capturedAt: string | null; eventId: string | null; url: string }): PhotoSummary {
|
||||
export function localPhoto(p: {
|
||||
sha256: string;
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
capturedAt: string | null;
|
||||
eventId: string | null;
|
||||
url: string;
|
||||
/** Cull marks already on the file (XMP pick / stars / colour). */
|
||||
flag?: PhotoSummary["flag"];
|
||||
rating?: number;
|
||||
colorLabel?: PhotoSummary["colorLabel"];
|
||||
}): PhotoSummary {
|
||||
let flag: PhotoSummary["flag"] = "NONE";
|
||||
if (p.flag) flag = p.flag;
|
||||
let rating = 0;
|
||||
if (typeof p.rating === "number" && p.rating > 0) rating = Math.min(5, Math.round(p.rating));
|
||||
if (flag === "NONE" && rating > 0) flag = "PICK";
|
||||
let colorLabel: PhotoSummary["colorLabel"] = "NONE";
|
||||
if (p.colorLabel) colorLabel = p.colorLabel;
|
||||
return {
|
||||
id: localId(p.sha256),
|
||||
eventId: p.eventId,
|
||||
@@ -175,9 +194,9 @@ export function localPhoto(p: { sha256: string; name: string; width: number; hei
|
||||
aperture: null,
|
||||
exposureTime: null,
|
||||
iso: null,
|
||||
rating: 0,
|
||||
flag: "NONE",
|
||||
colorLabel: "NONE",
|
||||
rating,
|
||||
flag,
|
||||
colorLabel,
|
||||
players: [],
|
||||
uploader: null,
|
||||
developSeq: 0,
|
||||
|
||||
@@ -86,6 +86,29 @@ describe("offline queue", () => {
|
||||
expect(q.size).toBe(0);
|
||||
});
|
||||
|
||||
it("sends a pick queued after the photo is already on the server", async () => {
|
||||
const q = new OfflineQueue("o1", store);
|
||||
q.uploaded("abc", "server-1");
|
||||
q.enqueueEdit(localId("abc"), { command: "develop.set", params: { values: { "light.exposure": 0.4 } } });
|
||||
q.add({ kind: "patch", ids: [localId("abc")], patch: { flag: "PICK" } });
|
||||
const sent: string[][] = [];
|
||||
const edits: string[] = [];
|
||||
const api = {
|
||||
updatePhotos: vi.fn(async (_org: string, ids: string[]) => {
|
||||
sent.push(ids);
|
||||
return { updated: ids.length };
|
||||
}),
|
||||
postEdits: vi.fn(async (photoId: string) => {
|
||||
edits.push(photoId);
|
||||
return { developSeq: 1, ops: [] };
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
await q.flush(api);
|
||||
expect(sent).toEqual([["server-1"]]);
|
||||
expect(edits).toEqual(["server-1"]);
|
||||
expect(q.size).toBe(0);
|
||||
});
|
||||
|
||||
it("drops what the server refuses for good", async () => {
|
||||
const q = new OfflineQueue("o1", store);
|
||||
q.add({ kind: "patch", ids: ["gone"], patch: { flag: "PICK" } });
|
||||
|
||||
@@ -202,34 +202,51 @@ export class OfflineQueue {
|
||||
|
||||
/** Develop edits made offline on photos no longer open (or uploaded since). Repeated ops are ignored by the server. */
|
||||
private async flushOutboxes(api: ApiClient): Promise<void> {
|
||||
let changed = false;
|
||||
const notify = () => {
|
||||
if (!changed) return;
|
||||
changed = false;
|
||||
for (const fn of this.listeners) fn();
|
||||
};
|
||||
for (const key of this.outboxKeys()) {
|
||||
const photoId = key.slice(OUTBOX.length);
|
||||
let photoId = key.slice(OUTBOX.length);
|
||||
if (isLocalId(photoId)) {
|
||||
// Edited in Revelar before (and after) the upload: those edits follow the photo.
|
||||
// Edited before the upload finished: those edits follow the photo, then go out in this same pass.
|
||||
const id = this.serverId(photoId);
|
||||
if (id) this.uploaded(photoId.slice(LOCAL.length), id);
|
||||
continue;
|
||||
if (!id) continue;
|
||||
this.uploaded(photoId.slice(LOCAL.length), id);
|
||||
photoId = id;
|
||||
changed = true;
|
||||
}
|
||||
const storeKey = `${OUTBOX}${photoId}`;
|
||||
let ops: { opId: string; command: unknown }[];
|
||||
try {
|
||||
ops = JSON.parse(this.store.get(key) ?? "[]") as { opId: string; command: unknown }[];
|
||||
ops = JSON.parse(this.store.get(storeKey) ?? "[]") as { opId: string; command: unknown }[];
|
||||
} catch {
|
||||
this.store.remove(key);
|
||||
this.store.remove(storeKey);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if (!ops.length) {
|
||||
this.store.remove(key);
|
||||
this.store.remove(storeKey);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await api.postEdits(photoId, { clientId: "offline-queue", ops } as unknown as Parameters<ApiClient["postEdits"]>[1]);
|
||||
} catch (err) {
|
||||
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
|
||||
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) {
|
||||
notify();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Sent (or refused for good). An editor still open on the photo keeps its own copy and resends harmlessly.
|
||||
if (this.store.get(key) === JSON.stringify(ops)) this.store.remove(key);
|
||||
if (this.store.get(storeKey) === JSON.stringify(ops)) {
|
||||
this.store.remove(storeKey);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const fn of this.listeners) fn();
|
||||
notify();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { PhotoPatch } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { onSocketLive } from "../library/realtime.js";
|
||||
import { isSocketLive, onSocketLive } from "../library/realtime.js";
|
||||
import { localPhotos } from "./local.js";
|
||||
import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./queue.js";
|
||||
|
||||
@@ -9,23 +9,44 @@ import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./qu
|
||||
* Sends what was kept while the socket was down, the moment it is live again. A change made while the socket is
|
||||
* already live goes out in `patchPhotos` itself. The socket is the clock: down, keep it; live, send it.
|
||||
*/
|
||||
const SEND_DELAY_MS = 40;
|
||||
const SEND_AGAIN_MS = 1500;
|
||||
const SEND_TRIES = 5;
|
||||
|
||||
export function useOfflineSync(api: ApiClient, orgId: string): void {
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
const queue = offlineQueue(orgId);
|
||||
return onSocketLive(() => {
|
||||
let tries = 0;
|
||||
const send = () => {
|
||||
let tries = 0;
|
||||
let timer = 0;
|
||||
const send = () => {
|
||||
if (!isSocketLive()) return;
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(() => {
|
||||
void queue.flush(api).then(() => {
|
||||
// Still waiting (the link dropped mid-send): try again while this connection stays up.
|
||||
if (queue.size > 0 && tries < 5) {
|
||||
// Still waiting (the link dropped mid-send, or a photo was still uploading): try again.
|
||||
if (queue.size > 0 && isSocketLive() && tries < SEND_TRIES) {
|
||||
tries += 1;
|
||||
window.setTimeout(send, 1500);
|
||||
window.setTimeout(send, SEND_AGAIN_MS);
|
||||
}
|
||||
if (queue.size === 0) tries = 0;
|
||||
});
|
||||
};
|
||||
}, SEND_DELAY_MS);
|
||||
};
|
||||
// A pick made while the socket is already up never sees another "connect". Send those too.
|
||||
const stopLive = onSocketLive(() => {
|
||||
tries = 0;
|
||||
send();
|
||||
});
|
||||
const stopQueue = queue.subscribe(() => {
|
||||
tries = 0;
|
||||
send();
|
||||
});
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
stopLive();
|
||||
stopQueue();
|
||||
};
|
||||
}, [api, orgId]);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ import { ALL_PHOTOS, applyPatch, isMac, type LibraryFilter, matchesFilter, patch
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { forgetSoftCrop, softCropFor } from "../desktop/softCrop.js";
|
||||
import { fileShaForPhoto } from "../desktop/fileMarks.js";
|
||||
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
|
||||
import { onSoftCropApplied, watchSoftCropPhoto } from "../desktop/softCropWatch.js";
|
||||
import { writeLightroomSidecar } from "../desktop/lightroomSidecar.js";
|
||||
import { isDesktop, localOriginalToView, prefs } from "../platform.js";
|
||||
@@ -235,25 +237,29 @@ export function DevelopPage() {
|
||||
|
||||
// Embed the develop crop into the JPEG as crs:Crop* (AlreadyApplied=False), the same Soft Crop Photo Mechanic reads.
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !current?.sha256) return;
|
||||
const sha = current.sha256;
|
||||
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
|
||||
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !sha) return;
|
||||
const settings = session.settings;
|
||||
const timer = setTimeout(() => {
|
||||
forgetSoftCrop(sha);
|
||||
void writeLightroomSidecar(sha, settings);
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [session, version, current?.sha256]);
|
||||
}, [session, version, current?.id, current?.sha256]);
|
||||
|
||||
// Watch the local file while this photo is open: Lightroom / Photo Mechanic crop changes become develop crops.
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !orgId || !current?.id || !current.sha256) return;
|
||||
watchSoftCropPhoto(orgId, current.id, current.sha256);
|
||||
}, [orgId, current?.id, current?.sha256]);
|
||||
if (!isDesktop() || !orgId || !current?.id) return;
|
||||
const sha = fileShaForPhoto(current.id, current.sha256);
|
||||
if (!sha) return;
|
||||
rememberPhotoFrame(sha, current.width, current.height);
|
||||
watchSoftCropPhoto(orgId, current.id, sha);
|
||||
}, [orgId, current?.id, current?.sha256, current?.width, current?.height]);
|
||||
|
||||
// A file that already has a Lightroom soft crop and no develop crop yet: start from that rectangle.
|
||||
useEffect(() => {
|
||||
if (!isDesktop() || !session?.loaded || !current?.sha256 || session.hasPending || session.seq > 0) return;
|
||||
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
|
||||
if (!isDesktop() || !session?.loaded || !sha || session.hasPending || session.seq > 0) return;
|
||||
const currentCrop = cropOf(session.settings);
|
||||
const full =
|
||||
currentCrop.rect.x0 <= 0.001 &&
|
||||
@@ -263,7 +269,7 @@ export function DevelopPage() {
|
||||
Math.abs(currentCrop.angle) < 0.05;
|
||||
if (!full) return;
|
||||
let alive = true;
|
||||
void softCropFor(current.sha256).then((soft) => {
|
||||
void softCropFor(sha).then((soft) => {
|
||||
if (!alive || !soft || !session) return;
|
||||
session.edit(
|
||||
{
|
||||
@@ -280,7 +286,7 @@ export function DevelopPage() {
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [session, version, current?.sha256]);
|
||||
}, [session, version, current?.id, current?.sha256]);
|
||||
|
||||
// Soft crop applied by the file watcher while this session is open: paint it immediately.
|
||||
useEffect(() => {
|
||||
@@ -577,8 +583,15 @@ export function DevelopPage() {
|
||||
const c0 = cropOf(session.settings);
|
||||
const aspect: [number, number] | null = c0.aspect ?? (choice === "original" || choice === null ? null : choice);
|
||||
try {
|
||||
const { crop } = await api.request<{ crop: { rect: Crop["rect"]; reason: string } | null }>("POST", `/v1/photos/${current.id}/auto-crop`, { aspect });
|
||||
if (!crop) return setNote(t.dev.autoCropNone);
|
||||
const answer = await api.request<{
|
||||
crop: { rect: Crop["rect"]; reason: string } | null;
|
||||
found?: boolean;
|
||||
}>("POST", `/v1/photos/${current.id}/auto-crop`, { aspect });
|
||||
if (!answer.crop) {
|
||||
if (answer.found) return setNote(t.dev.autoCropKept);
|
||||
return setNote(t.dev.autoCropNone);
|
||||
}
|
||||
const crop = answer.crop;
|
||||
const c = cropOf(session.settings);
|
||||
const rect = constrainRotated(crop.rect, c.angle, sourceSize.w, sourceSize.h);
|
||||
session.edit({ command: "crop.set", params: { rect, angle: c.angle, aspect: c.aspect ?? (aspect ?? [sourceSize.w, sourceSize.h]) } });
|
||||
|
||||
@@ -902,8 +902,8 @@ export function LibraryPage() {
|
||||
)}
|
||||
<span className="ml-auto flex items-center gap-3 font-mono text-[11px] text-faint">
|
||||
{waitingChanges > 0 && (
|
||||
<span className="text-star" title={t.offline.waitingHelp}>
|
||||
{t.offline.waiting(waitingChanges)}
|
||||
<span className="text-star" title={live === "live" ? t.offline.pendingHelp : t.offline.waitingHelp}>
|
||||
{live === "live" ? t.offline.pending(waitingChanges) : t.offline.waiting(waitingChanges)}
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
|
||||
@@ -32,6 +32,7 @@ fn main() {
|
||||
"ftp_retry",
|
||||
"ftp_read",
|
||||
"ftp_sent",
|
||||
"ftp_write_xmp",
|
||||
"ftp_open_folder",
|
||||
"ftp_save_settings",
|
||||
"local_original",
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"allow-ftp-retry",
|
||||
"allow-ftp-read",
|
||||
"allow-ftp-sent",
|
||||
"allow-ftp-write-xmp",
|
||||
"allow-ftp-open-folder",
|
||||
"allow-ftp-save-settings",
|
||||
"allow-local-original",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-ftp-write-xmp"
|
||||
description = "Enables the ftp_write_xmp command without any pre-configured scope."
|
||||
commands.allow = ["ftp_write_xmp"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ftp-write-xmp"
|
||||
description = "Denies the ftp_write_xmp command without any pre-configured scope."
|
||||
commands.deny = ["ftp_write_xmp"]
|
||||
@@ -568,8 +568,13 @@ impl FtpState {
|
||||
|
||||
/// JPEG or the RAW beside it, still inside the ingest tree. `ftp_read` stays JPEG-only.
|
||||
fn inside_kept(&self, path: &str) -> Result<PathBuf, String> {
|
||||
let root = self.ingest_dir().canonicalize().map_err(|e| e.to_string())?;
|
||||
let p = Path::new(path).canonicalize().map_err(|_| "not_found".to_string())?;
|
||||
let root = self
|
||||
.ingest_dir()
|
||||
.canonicalize()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let p = Path::new(path)
|
||||
.canonicalize()
|
||||
.map_err(|_| "not_found".to_string())?;
|
||||
if p.starts_with(&root) && (is_photo(&p) || is_raw(&p)) {
|
||||
Ok(p)
|
||||
} else {
|
||||
@@ -705,10 +710,7 @@ impl FtpState {
|
||||
finished.remove(&f.name);
|
||||
seen.remove(&f.path);
|
||||
taken.insert(f.path.clone());
|
||||
ready.push(IncomingFile {
|
||||
login,
|
||||
..f
|
||||
});
|
||||
ready.push(IncomingFile { login, ..f });
|
||||
} else {
|
||||
seen.insert(f.path.clone(), (f.size, f.modified_ms));
|
||||
}
|
||||
@@ -894,6 +896,7 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String {
|
||||
// A later pick must not wipe a crop already written, and a later crop must not wipe the pick.
|
||||
let combined = combine_descriptions(our_description(existing).as_deref(), &incoming_desc);
|
||||
let mut base = strip_our_description(existing);
|
||||
let had_camera = base.contains("<rdf:Description");
|
||||
// Lightroom reads the camera's lowercase `xmpDM:pick` and ignores a second description. Stamp that one.
|
||||
if let Some(pick) = attr_of(&combined, "xmpDM:pick") {
|
||||
let good = if pick == "1" { "True" } else { "False" };
|
||||
@@ -903,11 +906,26 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String {
|
||||
for (key, xmlns_key, xmlns) in [
|
||||
("xmp:Rating", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/"),
|
||||
("xmp:Label", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/"),
|
||||
("dc:title", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
|
||||
("photoshop:Headline", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
|
||||
("photoshop:City", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
|
||||
("photoshop:Credit", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
|
||||
("photoshop:Source", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"),
|
||||
(
|
||||
"photoshop:Headline",
|
||||
"xmlns:photoshop",
|
||||
"http://ns.adobe.com/photoshop/1.0/",
|
||||
),
|
||||
(
|
||||
"photoshop:City",
|
||||
"xmlns:photoshop",
|
||||
"http://ns.adobe.com/photoshop/1.0/",
|
||||
),
|
||||
(
|
||||
"photoshop:Credit",
|
||||
"xmlns:photoshop",
|
||||
"http://ns.adobe.com/photoshop/1.0/",
|
||||
),
|
||||
(
|
||||
"photoshop:Source",
|
||||
"xmlns:photoshop",
|
||||
"http://ns.adobe.com/photoshop/1.0/",
|
||||
),
|
||||
(
|
||||
"iptcCore:Location",
|
||||
"xmlns:iptcCore",
|
||||
@@ -919,10 +937,39 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String {
|
||||
base = stamp_attr(&base, key, &value, xmlns_key, xmlns);
|
||||
}
|
||||
}
|
||||
// Caption, title, keywords and creator are RDF elements. Lightroom reads them from the first
|
||||
// description and ignores the same elements on the packet this app appends afterwards.
|
||||
for (tag, xmlns_key, xmlns) in [
|
||||
(
|
||||
"dc:description",
|
||||
"xmlns:dc",
|
||||
"http://purl.org/dc/elements/1.1/",
|
||||
),
|
||||
("dc:title", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
|
||||
("dc:creator", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
|
||||
("dc:subject", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
|
||||
] {
|
||||
let Some(block) = structured_block(&combined, tag) else {
|
||||
continue;
|
||||
};
|
||||
if had_camera {
|
||||
base = upsert_first_child(&base, tag, &block, xmlns_key, xmlns);
|
||||
}
|
||||
}
|
||||
if let Some(idx) = base.rfind("</rdf:RDF>") {
|
||||
// Moved onto the camera description. Leave them off the second packet so a rescan
|
||||
// does not list the keywords twice. A file with no camera packet keeps them here.
|
||||
let mut appended = combined.clone();
|
||||
if had_camera {
|
||||
for tag in ["dc:description", "dc:title", "dc:creator", "dc:subject"] {
|
||||
if let Some((start, end)) = find_element(&appended, tag) {
|
||||
appended.replace_range(start..end, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
out.push_str(&base[..idx]);
|
||||
out.push_str(&combined);
|
||||
out.push_str(&appended);
|
||||
out.push('\n');
|
||||
out.push_str(&base[idx..]);
|
||||
return out;
|
||||
@@ -1137,6 +1184,100 @@ fn inject_after_about(xml: &str, extra: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// One element (`<dc:description>…</dc:description>` or a self-closing tag), not a longer name that shares the prefix.
|
||||
fn find_element(xml: &str, tag: &str) -> Option<(usize, usize)> {
|
||||
let needle = format!("<{tag}");
|
||||
let mut from = 0;
|
||||
while let Some(rel) = xml[from..].find(&needle) {
|
||||
let start = from + rel;
|
||||
let boundary = xml.as_bytes().get(start + needle.len()).copied();
|
||||
let is_tag = boundary == Some(b'>')
|
||||
|| boundary == Some(b' ')
|
||||
|| boundary == Some(b'/')
|
||||
|| boundary == Some(b'\n')
|
||||
|| boundary == Some(b'\t');
|
||||
if !is_tag {
|
||||
from = start + needle.len();
|
||||
continue;
|
||||
}
|
||||
let rest = &xml[start..];
|
||||
let Some(gt) = rest.find('>') else {
|
||||
return None;
|
||||
};
|
||||
if gt > 0 && rest.as_bytes()[gt - 1] == b'/' {
|
||||
return Some((start, start + gt + 1));
|
||||
}
|
||||
let close = format!("</{tag}>");
|
||||
let Some(close_at) = rest.find(&close) else {
|
||||
return None;
|
||||
};
|
||||
return Some((start, start + close_at + close.len()));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn element_block(xml: &str, tag: &str) -> Option<String> {
|
||||
let (start, end) = find_element(xml, tag)?;
|
||||
Some(xml[start..end].to_string())
|
||||
}
|
||||
|
||||
/// The element Lightroom reads, or a title that arrived as an attribute turned into `rdf:Alt`.
|
||||
fn structured_block(xml: &str, tag: &str) -> Option<String> {
|
||||
if let Some(block) = element_block(xml, tag) {
|
||||
return Some(block);
|
||||
}
|
||||
if tag != "dc:title" {
|
||||
return None;
|
||||
}
|
||||
let title = attr_of(xml, "dc:title")?;
|
||||
Some(format!(
|
||||
"<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">{title}</rdf:li></rdf:Alt></dc:title>"
|
||||
))
|
||||
}
|
||||
|
||||
/// Puts `block` inside the first `rdf:Description` (the camera packet Lightroom reads on rescan).
|
||||
fn upsert_first_child(xml: &str, tag: &str, block: &str, xmlns_key: &str, xmlns: &str) -> String {
|
||||
let Some(start) = xml.find("<rdf:Description") else {
|
||||
return xml.to_string();
|
||||
};
|
||||
let len = description_len(&xml[start..]);
|
||||
let mut desc = xml[start..start + len].to_string();
|
||||
if let Some((child_start, child_end)) = find_element(&desc, tag) {
|
||||
desc.replace_range(child_start..child_end, "");
|
||||
}
|
||||
if !desc.contains(xmlns_key) {
|
||||
desc = inject_after_about(&desc, &format!("{xmlns_key}=\"{xmlns}\""));
|
||||
}
|
||||
desc = insert_child_block(&desc, block);
|
||||
let mut out = String::new();
|
||||
out.push_str(&xml[..start]);
|
||||
out.push_str(&desc);
|
||||
out.push_str(&xml[start + len..]);
|
||||
out
|
||||
}
|
||||
|
||||
fn insert_child_block(desc: &str, block: &str) -> String {
|
||||
let Some(gt) = desc.find('>') else {
|
||||
return desc.to_string();
|
||||
};
|
||||
if gt > 0 && desc.as_bytes()[gt - 1] == b'/' {
|
||||
let mut out = String::new();
|
||||
out.push_str(&desc[..gt - 1]);
|
||||
out.push('>');
|
||||
out.push_str(block);
|
||||
out.push_str("</rdf:Description>");
|
||||
return out;
|
||||
}
|
||||
let Some(close) = desc.rfind("</rdf:Description>") else {
|
||||
return desc.to_string();
|
||||
};
|
||||
let mut out = String::new();
|
||||
out.push_str(&desc[..close]);
|
||||
out.push_str(block);
|
||||
out.push_str(&desc[close..]);
|
||||
out
|
||||
}
|
||||
|
||||
fn xmp_app1(packet: &str) -> Result<Vec<u8>, String> {
|
||||
let body = packet.as_bytes();
|
||||
let size = 2 + XMP_HEADER.len() + body.len();
|
||||
@@ -1186,7 +1327,10 @@ fn find_xmp_app1(data: &[u8]) -> Result<Option<(usize, usize)>, String> {
|
||||
}
|
||||
let start = i - 2;
|
||||
let end = i + len;
|
||||
if marker == 0xE1 && len >= 2 + XMP_HEADER.len() && &data[i + 2..i + 2 + XMP_HEADER.len()] == XMP_HEADER {
|
||||
if marker == 0xE1
|
||||
&& len >= 2 + XMP_HEADER.len()
|
||||
&& &data[i + 2..i + 2 + XMP_HEADER.len()] == XMP_HEADER
|
||||
{
|
||||
return Ok(Some((start, end)));
|
||||
}
|
||||
i = end;
|
||||
@@ -1232,7 +1376,9 @@ fn embed_xmp_jpeg(path: &Path, xml: &str) -> Result<(), String> {
|
||||
};
|
||||
let tmp = path.with_file_name(format!(
|
||||
"{}.photoreport-part",
|
||||
path.file_name().and_then(|s| s.to_str()).unwrap_or("photo.jpg")
|
||||
path.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("photo.jpg")
|
||||
));
|
||||
std::fs::write(&tmp, &next).map_err(|e| e.to_string())?;
|
||||
std::fs::rename(&tmp, path).map_err(|e| {
|
||||
@@ -1593,7 +1739,10 @@ mod tests {
|
||||
member_user_id: String::new(),
|
||||
}],
|
||||
ingest: dir.join("ingest").to_string_lossy().into_owned(),
|
||||
work_folder: dir.join("work/{date} - {event}").to_string_lossy().into_owned(),
|
||||
work_folder: dir
|
||||
.join("work/{date} - {event}")
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
auto_start: false,
|
||||
upload_originals: false,
|
||||
})
|
||||
@@ -1618,11 +1767,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(PathBuf::from(&again), moved);
|
||||
assert!(!ingest.join("IMG_0001.JPG").exists());
|
||||
assert!(!moved
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("IMG_0001-1.JPG")
|
||||
.exists());
|
||||
assert!(!moved.parent().unwrap().join("IMG_0001-1.JPG").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -1886,10 +2031,30 @@ mod tests {
|
||||
assert!(both.contains("<xmp:Rating>4</xmp:Rating>"));
|
||||
assert!(!both.contains("<xmp:Rating>0</xmp:Rating>"));
|
||||
assert!(both.contains("xmpDM:pick=\"1\""));
|
||||
assert!(both.contains("dc:title=\"Jogador\""));
|
||||
let first_end = both.find("</rdf:Description>").expect("camera description");
|
||||
let first = &both[..first_end];
|
||||
assert!(first.contains("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Jogador</rdf:li></rdf:Alt></dc:title>"));
|
||||
assert!(!first.contains("photoreport:embed"));
|
||||
assert!(both.contains("photoreport:embed=\"1\""));
|
||||
}
|
||||
|
||||
/// Lightroom's Read Metadata uses the first description. Caption, keywords and creator have to be there.
|
||||
#[test]
|
||||
fn caption_lands_on_the_camera_description() {
|
||||
let camera = r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"><xmp:Rating>0</xmp:Rating></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let incoming = r#"<?xml version="1.0"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" photoshop:City="Maia" xmpDM:pick="1" xmpDM:good="True"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">SNAF</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">Concentração no Hotel</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>Peter Spark</rdf:li></rdf:Seq></dc:creator><dc:subject><rdf:Bag><rdf:li>ANDEBOL</rdf:li></rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let both = merge_xmp_packet(camera, incoming);
|
||||
let first_end = both.find("</rdf:Description>").expect("camera description");
|
||||
let first = &both[..first_end];
|
||||
assert!(first.contains("Concentração no Hotel"));
|
||||
assert!(first.contains(">SNAF<"));
|
||||
assert!(first.contains("Peter Spark"));
|
||||
assert!(first.contains("ANDEBOL"));
|
||||
assert!(first.contains("photoshop:City=\"Maia\""));
|
||||
assert!(first.contains("xmpDM:pick=\"1\""));
|
||||
assert!(!first.contains("photoreport:embed"));
|
||||
}
|
||||
|
||||
/// A JPEG with no camera XMP must still get a full packet Lightroom can parse.
|
||||
#[test]
|
||||
fn empty_camera_packet_is_wrapped() {
|
||||
|
||||
@@ -195,45 +195,57 @@ pub async fn local_stat(
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0);
|
||||
// JPEG carries its XMP inside the file, so only a raw's sidecar moves the mtime.
|
||||
let sidecar = path.with_extension("xmp");
|
||||
let jpeg = path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(crate::ftp::is_jpeg_name);
|
||||
if !jpeg && let Ok(side) = tokio::fs::metadata(&sidecar).await {
|
||||
size = size.saturating_add(side.len());
|
||||
if let Some(ms) = side
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
{
|
||||
mtime_ms = mtime_ms.max(ms);
|
||||
// Sidecar next to the file (RAW always; JPEG when Photo Mechanic / Bridge wrote one).
|
||||
for side in xmp_sidecar_paths(&path) {
|
||||
if let Ok(meta) = tokio::fs::metadata(&side).await {
|
||||
size = size.saturating_add(meta.len());
|
||||
if let Some(ms) = meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
{
|
||||
mtime_ms = mtime_ms.max(ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(LocalStat { size, mtime_ms })
|
||||
}
|
||||
|
||||
/// `photo.xmp` and `photo.jpg.xmp` beside an original — Photo Mechanic writes both forms for JPEG.
|
||||
fn xmp_sidecar_paths(path: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::with_capacity(2);
|
||||
out.push(path.with_extension("xmp"));
|
||||
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
||||
if let Some(parent) = path.parent() {
|
||||
out.push(parent.join(format!("{name}.xmp")));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The XMP packet (or the head of the file) for a local original, so the app can draw Lightroom's soft crop
|
||||
/// without loading a 12 MB JPEG. Also tries `name.xmp` beside a raw. `not_found` when this computer lacks it.
|
||||
/// without loading a 12 MB JPEG. Sidecar first (RAW and JPEG), then the packet embedded in a JPEG.
|
||||
/// `not_found` when this computer lacks the file.
|
||||
#[tauri::command]
|
||||
pub async fn local_xmp(
|
||||
index: tauri::State<'_, LocalIndex>,
|
||||
sha256: String,
|
||||
) -> Result<tauri::ipc::Response, String> {
|
||||
let path = index.find_changed(&sha256).ok_or("not_found")?;
|
||||
for side in xmp_sidecar_paths(&path) {
|
||||
if side.is_file() {
|
||||
let bytes = tokio::fs::read(&side).await.map_err(|e| e.to_string())?;
|
||||
if !bytes.is_empty() {
|
||||
return Ok(tauri::ipc::Response::new(bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
let jpeg = path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(crate::ftp::is_jpeg_name);
|
||||
// JPEG: the packet embedded in the file. RAW: the .xmp beside it. Lightroom does not use a JPEG sidecar.
|
||||
if !jpeg {
|
||||
let sidecar = path.with_extension("xmp");
|
||||
if sidecar.is_file() {
|
||||
let bytes = tokio::fs::read(&sidecar).await.map_err(|e| e.to_string())?;
|
||||
return Ok(tauri::ipc::Response::new(bytes));
|
||||
}
|
||||
return Ok(tauri::ipc::Response::new(Vec::<u8>::new()));
|
||||
}
|
||||
let bytes = tokio::task::spawn_blocking(move || read_jpeg_xmp_head(&path))
|
||||
|
||||
+32
-5
@@ -396,8 +396,9 @@ A match does not stop when the venue's internet does. The desktop app keeps work
|
||||
photo in the event of its capture time (the same rule as the server), with id `local:<sha256>`. It can be culled,
|
||||
named and edited before it is uploaded; the server's copy replaces it when the upload is done, keeping what was done.
|
||||
- **Changes wait, in order** (`offline/queue.ts`, localStorage): culling, players, IPTC and "send to" made without a
|
||||
network are kept and sent when the server answers (every 10 s and on `online`); changes to a photo not uploaded yet
|
||||
wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the photo to its server id.
|
||||
network are kept and sent when the socket is up, including a change made while it was already up. Changes to a
|
||||
photo not uploaded yet wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the
|
||||
photo to its server id.
|
||||
- **Uploads wait instead of failing**: the queue pauses on a network error and resumes when the connection is back.
|
||||
- The autopilot runs on the server when the photo arrives, and never over a person's edit (made offline first).
|
||||
|
||||
@@ -485,9 +486,35 @@ credentials, another name and folder).
|
||||
**Cull marks and IPTC on the work-folder original.** While the desktop app is open it writes into the local
|
||||
original Lightroom imports (JPEG: embedded XMP; RAW: `.xmp` beside it): pick / reject / stars / colour
|
||||
(`xmpDM:pick`, `xmp:Rating`, `xmp:Label`), develop soft crop (`crs:Crop*`), and the resolved IPTC (caption,
|
||||
title, city, keywords, creator…). The camera's XMP stays; PhotoReport stamps the flag onto that first
|
||||
description so Lightroom Classic ≥ 13.2 Attribute filters see it. A catch-up pass covers photos already
|
||||
picked before this screen was open.
|
||||
title, city, keywords, creator…). The camera's XMP stays. PhotoReport stamps the flag and the newsroom
|
||||
fields onto that first description — caption and title as `rdf:Alt`, keywords as `rdf:Bag`, creator as
|
||||
`rdf:Seq` — because Lightroom Classic reads that description on import and on Read Metadata from Files and
|
||||
ignores the same fields on a second packet. A write that fails while the file is still in the ingest folder
|
||||
is retried once the original is filed, and again while the app stays open. A catch-up pass covers photos
|
||||
already picked before this screen was open, without rewriting every older original first. The write addresses
|
||||
the original by the hash recorded when that file was uploaded (`pr.localmap`), not by the preview hash the
|
||||
server may store on the photo.
|
||||
|
||||
**Cull marks from disk into the library (XMP → library).** On local FTP arrival, hand import, and server
|
||||
ingest, PhotoReport reads the same XMP fields back into the library (pick / reject / stars / colour). Soft
|
||||
crop becomes a develop `crop.set`. The desktop watcher re-reads work-folder originals while the app is open
|
||||
(every few seconds, for photos on screen and photos that arrived on this computer), so a pick, a star, a colour
|
||||
or a crop painted in Lightroom / Photo Mechanic lands without another import and is sent to the server. The
|
||||
2048 px FTP preview is never the source of marks — the original JPEG is, found by the hash recorded at upload
|
||||
(`pr.localmap`), not by the preview hash the server may store.
|
||||
|
||||
What comes back from the file: the crop, the pick or reject, the stars and the colour. Exposure, white balance
|
||||
and the other develop sliders are written out for Lightroom, and are not read back. Lightroom has to write the
|
||||
change into the file (automatically write changes into XMP, or save metadata to the file). A change that stays
|
||||
only in the Lightroom catalog is invisible.
|
||||
|
||||
A straightened crop is stored as the corners Lightroom turns back around the crop centre. Writing the levelled
|
||||
rectangle plus the angle makes Lightroom show another proportion (Custom). The levelled result is always the
|
||||
photograph's own aspect. The autopilot never chooses another one (`docs/photo-editing-rules.md`).
|
||||
|
||||
A photo that was already delivered is sent again to that same destination about a minute after the edit
|
||||
settles, under the same file name, replacing the previous file. A destination that takes the untouched
|
||||
original is not sent again: it has no edit to carry.
|
||||
|
||||
**Cull marks on delivery.** The same pick / reject / stars / colour are written into the delivered JPEG
|
||||
(plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic). When the desktop app is open it watches local
|
||||
|
||||
+63
-32
@@ -19,12 +19,17 @@ Following the AP and NPPA codes:
|
||||
|
||||
## 2. Crop
|
||||
|
||||
- **Best effort, original aspect:** every crop rule below is "when possible". The autopilot **never** changes the
|
||||
photograph's aspect ratio. Lead room, cleaning edges, and tightening stay inside that ratio; if they cannot be
|
||||
met without another format, keep the best crop in the original aspect (or leave the photo as shot).
|
||||
- **Who:** the subject is the person the camera focused on, when the file has a focus point (EXIF SubjectArea:
|
||||
the autofocus point, shown by Photo Mechanic) **and that person is sharp with a fully visible face**. A soft or
|
||||
faceless body in the foreground (AF landed on the jump in front) is scenery — never the crop — when a sharp
|
||||
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.
|
||||
faceless body in the foreground or background (AF landed on the jump in front, or a blur behind) is scenery —
|
||||
never the crop's subject and never used to expand the framing — when a sharp face sits in focus. 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 the
|
||||
**sharp** people contesting it come along (soft bodies near the ball stay out of the subject box). 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 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
|
||||
@@ -36,9 +41,18 @@ Following the AP and NPPA codes:
|
||||
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
|
||||
that stays. A spare ball that nobody is playing never wins, in either sport.
|
||||
- **Shape:** the autopilot keeps the photograph's own aspect. The crop may move anywhere across the frame,
|
||||
including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a portrait
|
||||
crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect.
|
||||
- **Shape:** the autopilot keeps the photograph's own aspect (non-negotiable). The crop may move anywhere across
|
||||
the frame, including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a
|
||||
portrait crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect.
|
||||
A file written for Lightroom stores a straightened crop as the corners Lightroom turns back around the crop
|
||||
centre, so the crop tool still shows this aspect. Writing the levelled rectangle together with the angle makes
|
||||
Lightroom call it Custom.
|
||||
- **Lead room (sport):** leave space in the direction the player looks or runs; put their back nearer the opposite
|
||||
edge. Dead space behind the facing direction is wrong. Without a reliable facing signal (face on the body, or
|
||||
the ball in play), keep the subject centred as before. Reportage and open team frames do not force lead room.
|
||||
- **Wide end of a zoom:** when the file shows a zoom and the focal length is at (or very near) the wide end
|
||||
(e.g. 15–35 mm at 15 mm), the wide plan is intentional. Do not reframe aggressively — typically only straighten.
|
||||
A tele zoom (70–200 at 135 mm) may still be cropped; the photographer could have zoomed in.
|
||||
- **Context:** a generic event (no opponent, no fixture) is reportage. A match is sport, and a photo of that
|
||||
match with no ball in play is cropped as a person. Reportage does not use the handball cut.
|
||||
- **Framing** (per event, sport only):
|
||||
@@ -47,12 +61,12 @@ 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** 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
|
||||
- **Reportage** reads the shot the way a picture editor does. One clear person is the subject — someone
|
||||
walking in the middle, a suitcase or a bag beside them — even when they take less than half the frame.
|
||||
The crop keeps the whole body and what they carry, cuts empty floor and edge clutter, and keeps the
|
||||
photograph's aspect. It does not say there is no subject. It is not a sports fill. A conversation (several
|
||||
people whose bodies are whole) stays as framed. A distant figure, under about a fifth of the frame, is the
|
||||
place and stays. A figure that already fills the height stays. A zoom at its wide end stays. 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
|
||||
@@ -66,10 +80,12 @@ Following the AP and NPPA codes:
|
||||
ground under the sole. Cutting the shoe, the ankle or a hand just to fill the frame is not allowed. When the
|
||||
foot already leaves the photo, the crop ends mid-shin or mid-thigh. It does not stop on the sock. Never at a
|
||||
joint, and never through the ball.
|
||||
- **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and
|
||||
background people don't count. In reportage this is absolute for anyone still reasonably sharp: the crop
|
||||
keeps their head, and the primary crop keeps their feet when those feet are in the photo. A half or a
|
||||
three-quarter may end at the waist, and it still starts above the head. A band through the chest is never a crop.
|
||||
- **Edges:** no slivers of other people at the crop edge: either in, or out — including soft / out-of-focus
|
||||
fragments and a finger or tiny body part of another athlete. Prefer a tighter clean frame to leaving that scrap
|
||||
in. Soft people are scenery to remove when possible, not framing anchors. In reportage this is absolute for
|
||||
anyone still reasonably sharp: the crop keeps their head, and the primary crop keeps their feet when those feet
|
||||
are in the photo. A half or a three-quarter may end at the waist, and it still starts above the head. A band
|
||||
through the chest is never a crop.
|
||||
- **A bust is not the subject.** A head in a window, or a torso the detector stopped at the chest, does not
|
||||
beat a whole figure standing in the same photo. The taller person, closer to the camera, stays in the frame
|
||||
even when someone behind them is a little sharper.
|
||||
@@ -80,14 +96,19 @@ Following the AP and NPPA codes:
|
||||
- **Vertical placement:** the upper body (chest, faces) a little above the middle of the crop, never the knees.
|
||||
Little or no empty pitch or floor under the feet: when the crop is taller than the subject, the spare height
|
||||
goes above them (crowd, stands), not below.
|
||||
- **Distractions:** prefer the crop that leaves out half-bodies, empty floor and bright clutter at the edges,
|
||||
as long as nothing that matters goes with them.
|
||||
- **Distracted:** prefer the crop that leaves out half-bodies, empty floor, advertising boards and bright clutter
|
||||
at the edges, as long as nothing that matters goes with them (same aspect). A cleaner alternative wins.
|
||||
- **Level vs subject:** prefer not to straighten (or reduce the angle) if leveling would chop a foot, hand or
|
||||
head of the subject that the crop had kept. The subject intact beats a perfectly level horizon.
|
||||
- **Resolution:** never crop below what the delivery needs. Default: the crop keeps at least 2400 px on its long
|
||||
edge of the original (configurable per organisation; agencies often ask for more). On a large file the floor
|
||||
is 3000 px, not 35% of the frame (that held a modern body near 4000 px). An export at 4000 px enlarges
|
||||
that crop, and only that far (at most a third). A smaller file is not blown up.
|
||||
- **Not too much:** if the only crop that works is tighter than the resolution allows, keep the wider frame. A good
|
||||
photo uncropped beats a bad crop.
|
||||
photo uncropped beats a bad crop. The floor is the organisation's `minLongEdge` (default 2400 px on the long
|
||||
edge of the original, and never below the 3000 px large-file floor). A crop that only clears that floor by a
|
||||
few percent is refused: needing a super-reframe or that much cut means the subject or the moment was misread.
|
||||
Prefer another frame of the burst, or leave the photograph as shot.
|
||||
- **Not for nothing:** a crop of more than 92% of the width is not made: the photo stays as shot. The agencies
|
||||
send a fifth to a half of their photos uncropped (Getty, AFP, Paris 2024).
|
||||
|
||||
@@ -97,13 +118,17 @@ A camera at 10–30 frames per second sends several photos of the same moment.
|
||||
|
||||
- **A burst** is a run of photos from the same camera with less than 1 s between frames (configurable; was 1.5 s).
|
||||
- **Score** of each frame: sharpness of the subject (focus landed on them, no motion blur), subject size, ball in
|
||||
frame and near the subject, faces visible. Ties go to the earliest frame (usually the peak of the action).
|
||||
frame and near the subject (peak contact preferred: ball closest to the body), 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, 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.
|
||||
- **Clear face:** prefer a frame whose subject's face is sharp and unobstructed. When the same burst has one with
|
||||
a clear focused face, do not pick a frame where an arm, another player or the ball covers that face. Only the
|
||||
occluded / soft-face frame may stay when it is the only picture of that moment.
|
||||
- **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
|
||||
@@ -130,12 +155,13 @@ 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 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;
|
||||
The level prefers the camera's own electronic level (Canon LevelInfo / RollAngle — the viewfinder level,
|
||||
including when it lives on the original CR3 rather than the JPEG). A level camera stays level: a brick wall
|
||||
must not tilt the frame. Straightening must not chop a foot, hand or head the crop had kept — reduce or skip
|
||||
the angle first. 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.
|
||||
|
||||
@@ -161,15 +187,18 @@ in Revelar.
|
||||
|
||||
### Learning from corrections
|
||||
|
||||
When someone changes a photo the autopilot edited, the difference (final minus autopilot, per control; and the
|
||||
crop area against the autopilot's) is kept, one per photo, latest state wins (`develop_corrections`,
|
||||
`apps/api/src/autopilot/learning.ts`). For the next photos of the same photographer the autopilot adds, to its own
|
||||
measurement, the median of the last 60 corrections, at the same venue when there are at least 5 there:
|
||||
This runs already — it is not a future wish. When someone changes a photo the autopilot edited (in Revelar, or by
|
||||
writing a soft crop into the file in Lightroom / Photo Mechanic on the desktop), the difference (final minus
|
||||
autopilot, per control; and the crop area against the autopilot's) is kept, one per photo, latest state wins
|
||||
(`develop_corrections`, `apps/api/src/autopilot/learning.ts`). The desktop and the server both apply that style on
|
||||
the next picks (desktop caches it for offline; it refreshes when the network is up). For the next photos of the
|
||||
same photographer the autopilot adds, to its own measurement, the median of the last 60 corrections, at the same
|
||||
venue when there are at least 5 there:
|
||||
|
||||
- only the controls it sets itself (tone, white balance) and crop tightness, never a creative look;
|
||||
- only with 5 or more corrections, and only when at least 70% of them go the same way (one odd photo changes
|
||||
nothing); tiny differences are noise and very large ones creative choices, both ignored;
|
||||
- the crop is read on the person, not only as a ratio: where the bottom cuts the body (chest, waist, mid-leg, feet), space above the head, and whether the sides take the arms. When those agree, the next crop is placed the same way on the next person. A plain tighter or looser frame is only the fallback when the body position was not known. A learnt crop still may not slice a ball the frame had kept whole.
|
||||
- the crop is read on the person, not only as a ratio: where the bottom cuts the body (chest, waist, mid-leg, feet), space above the head, and whether the sides take the arms. When those agree, the next crop is placed the same way on the next person. A plain tighter or looser frame is only the fallback when the body position was not known. Opening a crop the autopilot made too tight teaches it to leave more room next time. A learnt crop still may not slice a ball the frame had kept whole.
|
||||
|
||||
The autopilot's panel in the app shows what it has learnt and has "Esquecer". The burst picks are not learnt yet.
|
||||
|
||||
@@ -205,5 +234,7 @@ the best frames left when the windows' shares fall short); without the autopilot
|
||||
- AP and NPPA codes, summarised by the CUNY Newmark J-School: https://photo.journalism.cuny.edu/?p=201
|
||||
- Cropping at mid-limb, not at joints; keep meaning; avoid clutter: https://www.walsworthyearbooks.com/top-10-essential-rules-for-good-photo-cropping/
|
||||
- Burst culling criteria (subject sharpness, eyes, ball, peak action, 1–3 per burst): https://filterpixel.com/blog/sports-photography-burst-mode-culling
|
||||
- Sports composition (lead room, face, fill the frame): https://www.ttlsports.com/composition-techniques-for-sport-photography
|
||||
- Sports burst culling (occlusion, peak contact, clear face): https://imagen-ai.com/valuable-tips/how-to-do-photo-culling-for-sports-photographers/
|
||||
- Peter's own Lightroom crops (65 picked photos, handball, October 2026): crops in the photo's aspect, often
|
||||
exactly two thirds of the frame, straightening of 0.5–3.3°.
|
||||
+10
-3
@@ -12,7 +12,14 @@ unset PORT DEPLOY_WEBHOOK_SECRET DEPLOY_SERVICE DEPLOY_SCRIPT DEPLOY_LOG
|
||||
REPO_DIR="${DEPLOY_REPO_DIR:-/srv/photoreport}"
|
||||
API_PORT="${API_PORT:-3000}"
|
||||
SITE_PORT="${SITE_PORT:-3100}"
|
||||
HEALTH_TRIES="${BOOT_HEALTH_TRIES:-90}"
|
||||
# Bound the post-start health poll by wall-clock, not by a try count. A count of 90 (sleep 2 +
|
||||
# max-time 3) could run ~450s and exceed photoreport-boot.service's TimeoutStartSec, at which
|
||||
# point systemd kills the whole cgroup — including the PM2 daemon this script just launched —
|
||||
# and leaves the port closed with no self-heal (BIT-32855: pr-site turned a transient pr-api
|
||||
# reboot into a persistent 502 this way). PM2 (autorestart) and the next-env watchdog handle
|
||||
# real recovery; this poll only confirms the boot, so a 150s budget fits under both the
|
||||
# deployed 300s and the repo's 420s TimeoutStartSec with margin for the pm2_start retry path.
|
||||
HEALTH_BUDGET_SEC="${BOOT_HEALTH_BUDGET_SEC:-150}"
|
||||
|
||||
log() { printf '[%s] boot %s: %s\n' "$(date -u +%FT%TZ)" "$SERVICE" "$*"; }
|
||||
|
||||
@@ -31,8 +38,8 @@ cd "$REPO_DIR"
|
||||
SHA="$(git rev-parse HEAD)"
|
||||
|
||||
wait_for() {
|
||||
local url="$1" i
|
||||
for ((i = 1; i <= HEALTH_TRIES; i++)); do
|
||||
local url="$1" start=$SECONDS
|
||||
while (( SECONDS - start < HEALTH_BUDGET_SEC )); do
|
||||
curl -fsS --max-time 3 -o /dev/null "$url" 2>/dev/null && return 0
|
||||
sleep 2
|
||||
done
|
||||
|
||||
Reference in new issue
Block a user