Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9d89eae19 | ||
|
|
3db365452f | ||
|
|
88cd74f5ff | ||
|
|
52fe4b67db | ||
|
|
c922e21cc6 | ||
|
|
e77bbfcf53 |
No files matched your search
@@ -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 {
|
||||
@@ -344,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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -562,14 +590,15 @@ 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;
|
||||
@@ -620,9 +649,10 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo
|
||||
if (cut) return finish(cut);
|
||||
}
|
||||
// Whole bodies, feet included. A little headroom gives way before a complete foot does.
|
||||
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter)
|
||||
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter)
|
||||
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter);
|
||||
// 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, false, lead, edgeClutter));
|
||||
}
|
||||
@@ -662,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, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number): (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;
|
||||
@@ -705,7 +735,8 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
|
||||
// A player the photographer left in the picture stays in it. Cutting them out, or through the body,
|
||||
// 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, lead, edgeClutter, minWidth) + 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 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,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,
|
||||
@@ -71,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", () => {
|
||||
@@ -98,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,
|
||||
@@ -113,7 +125,15 @@ describe("planFrame", () => {
|
||||
angle: 0,
|
||||
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.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", () => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -94,22 +94,21 @@ export function cullFromCameraRating(rating: number | undefined): { rating: numb
|
||||
* 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 function cullFromXmpPacket(xmp: string | null | undefined): {
|
||||
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: {
|
||||
rating?: number;
|
||||
flag?: "PICK" | "REJECT";
|
||||
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
|
||||
} = {};
|
||||
const out: XmpCull = {};
|
||||
if (marks.flag === "REJECT") out.flag = "REJECT";
|
||||
else if (marks.flag === "PICK") out.flag = "PICK";
|
||||
if (marks.rating > 0) {
|
||||
out.rating = marks.rating;
|
||||
const rating = marks.rating;
|
||||
if (typeof rating === "number" && rating > 0) {
|
||||
out.rating = rating;
|
||||
if (!out.flag) out.flag = "PICK";
|
||||
}
|
||||
const color = marks.colorLabel;
|
||||
|
||||
@@ -181,9 +181,12 @@ 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.
|
||||
const xmpCull = await readFile(file)
|
||||
.then((buf) => cullFromJpegBytes(buf))
|
||||
.catch(() => ({}));
|
||||
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
|
||||
@@ -365,29 +368,33 @@ export class IngestService {
|
||||
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;
|
||||
const xmpCull = needCull
|
||||
? await readFile(file)
|
||||
.then((buf) => cullFromJpegBytes(buf))
|
||||
.catch(() => ({}))
|
||||
: {};
|
||||
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 } });
|
||||
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 } : {}),
|
||||
...("colorLabel" in cull && existing?.colorLabel === "NONE" ? { colorLabel: cull.colorLabel } : {}),
|
||||
...(needCull ? { 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.
|
||||
@@ -503,24 +510,35 @@ export class IngestService {
|
||||
for (const row of rows) {
|
||||
const file = storage.resolve(row.storage_key);
|
||||
const camera = await readCameraInfo(file).catch(() => null);
|
||||
const xmpCull = await readFile(file)
|
||||
.then((buf) => cullFromJpegBytes(buf))
|
||||
.catch(() => ({}));
|
||||
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,
|
||||
};
|
||||
const patch: {
|
||||
rating?: number;
|
||||
flag?: "PICK" | "REJECT";
|
||||
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
|
||||
} = {};
|
||||
let changed = false;
|
||||
if ("rating" in cull && cull.rating) {
|
||||
if (typeof cull.rating === "number" && cull.rating > 0) {
|
||||
data.rating = cull.rating;
|
||||
patch.rating = cull.rating;
|
||||
changed = true;
|
||||
}
|
||||
if ("flag" in cull && row.flag === "NONE") {
|
||||
if (cull.flag && row.flag === "NONE") {
|
||||
data.flag = cull.flag;
|
||||
patch.flag = cull.flag;
|
||||
changed = true;
|
||||
}
|
||||
if ("colorLabel" in cull) {
|
||||
if (cull.colorLabel) {
|
||||
data.colorLabel = cull.colorLabel;
|
||||
patch.colorLabel = cull.colorLabel;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) applied++;
|
||||
@@ -529,11 +547,7 @@ export class IngestService {
|
||||
broadcaster.library(row.organization_id, {
|
||||
type: "photo.updated",
|
||||
ids: [row.id],
|
||||
patch: {
|
||||
...("rating" in cull ? { rating: cull.rating } : {}),
|
||||
...("flag" in cull && row.flag === "NONE" ? { flag: cull.flag } : {}),
|
||||
...("colorLabel" in cull ? { colorLabel: cull.colorLabel } : {}),
|
||||
},
|
||||
patch,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,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();
|
||||
});
|
||||
@@ -216,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] } })!;
|
||||
@@ -225,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;
|
||||
@@ -294,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", () => {
|
||||
@@ -308,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", () => {
|
||||
@@ -347,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", () => {
|
||||
|
||||
@@ -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();
|
||||
@@ -21,9 +23,19 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
|
||||
try {
|
||||
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);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 { flushFailedPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
|
||||
|
||||
const LOCAL = "local:";
|
||||
const idToSha = new Map<string, string>();
|
||||
@@ -161,8 +161,9 @@ 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();
|
||||
let events: EventSummary[] = [];
|
||||
try {
|
||||
events = (await api.listEvents(orgId)).events.filter((event) => eventIsCurrent(event, Date.now()));
|
||||
@@ -202,13 +203,20 @@ export function FileMarksSync({ api, orgId }: { api: ApiClient; orgId: string })
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
void catchUpFileMarks(api, orgId);
|
||||
// A write often fails because the JPEG is still in the ingest folder. Retry those, not the whole library.
|
||||
const retry = window.setInterval(() => {
|
||||
flushFailedPhotoFiles();
|
||||
}, 30 * 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;
|
||||
}
|
||||
@@ -60,7 +60,8 @@ describe("Lightroom sidecar", () => {
|
||||
creator: "Fotógrafo / PhotoReport.pt",
|
||||
},
|
||||
);
|
||||
expect(xml).toContain('dc:title="Pavlidis"');
|
||||
expect(xml).toContain("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Pavlidis</rdf:li></rdf:Alt></dc:title>");
|
||||
expect(xml).not.toContain('dc:title="Pavlidis"');
|
||||
expect(xml).toContain("Águas Santas Milaneza x SL Benfica, em Maia");
|
||||
expect(xml).toContain('photoshop:City="Maia"');
|
||||
expect(xml).toContain("<rdf:li>ANDEBOL</rdf:li>");
|
||||
|
||||
@@ -150,9 +150,10 @@ 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/");
|
||||
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 +183,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>`;
|
||||
@@ -350,7 +350,35 @@ function saveRemembered(all: Record<string, RememberedFile>): void {
|
||||
}
|
||||
|
||||
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,11 +387,29 @@ 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];
|
||||
if (!row) return;
|
||||
@@ -371,8 +417,11 @@ async function flushPhotoFile(sha256: string): Promise<void> {
|
||||
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;
|
||||
}
|
||||
@@ -391,6 +440,19 @@ 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 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;
|
||||
|
||||
@@ -116,7 +116,7 @@ export async function marksFromLocalSha(sha256: string): Promise<DiskFileMarks>
|
||||
|
||||
/**
|
||||
* Read marks from a JPEG still in the local FTP ingest tree (path from `ftp_take`).
|
||||
* The 2048 px preview strips XMP — always read the original.
|
||||
* 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 };
|
||||
|
||||
@@ -9,7 +9,8 @@ import { forgetSoftCrop, localXmpText } from "./softCrop.js";
|
||||
* 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;
|
||||
|
||||
@@ -147,9 +148,20 @@ export async function reconcileSoftCrops(
|
||||
}
|
||||
forgetSoftCrop(row.sha256);
|
||||
const xmp = await localXmpText(row.sha256);
|
||||
const crop = xmp ? cropFromXmp(xmp) : null;
|
||||
const color = xmp ? colorClassFromXmp(xmp) : null;
|
||||
const marks = xmp ? libraryMarksFromXmp(xmp) : { flag: "NONE" as const, rating: 0, colorLabel: "NONE" as const };
|
||||
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 crop = cropFromXmp(xmp);
|
||||
const color = colorClassFromXmp(xmp);
|
||||
const marks = libraryMarksFromXmp(xmp);
|
||||
let colorApplied = color ? row.color : (row.color ?? "");
|
||||
let flagApplied = row.flag ?? "NONE";
|
||||
let ratingApplied = row.rating ?? 0;
|
||||
|
||||
@@ -1337,6 +1337,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.",
|
||||
|
||||
@@ -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,11 +186,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
} catch {
|
||||
/* no blob URLs here (tests): shown without a thumbnail */
|
||||
}
|
||||
// Preview strips XMP — read pick / stars / colour / soft crop from the original on disk.
|
||||
const { marksFromFtpPath, cullPatchFromMarks, cropCommandFromMarks, hasDiskMarks } = await import(
|
||||
// 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 marksFromFtpPath(f.path);
|
||||
const disk = await marksFromLocalSha(info.sha256);
|
||||
const cull = cullPatchFromMarks(disk);
|
||||
localPhotos.put(
|
||||
localPhoto({
|
||||
@@ -203,13 +204,16 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
...cull,
|
||||
}),
|
||||
);
|
||||
if (orgId && hasDiskMarks(disk)) {
|
||||
if (orgId) {
|
||||
const id = localId(info.sha256);
|
||||
if (Object.keys(cull).length) {
|
||||
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -239,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 }));
|
||||
}
|
||||
|
||||
@@ -75,11 +75,18 @@ 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: pick / stars / colour / soft crop must land in the library.
|
||||
const { marksFromJpegBytes, cullPatchFromMarks, cropCommandFromMarks, hasDiskMarks } = await import(
|
||||
"../desktop/readFileMarks.js"
|
||||
);
|
||||
const disk = marksFromJpegBytes(previewBytes);
|
||||
// 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({
|
||||
@@ -93,13 +100,15 @@ export async function showLocalJpeg(args: {
|
||||
...cull,
|
||||
}),
|
||||
);
|
||||
if (orgId && hasDiskMarks(disk)) {
|
||||
if (orgId) {
|
||||
const id = localId(sha256);
|
||||
if (Object.keys(cull).length) {
|
||||
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
|
||||
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);
|
||||
}
|
||||
const cropOp = cropCommandFromMarks(disk);
|
||||
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
|
||||
if (isDesktop()) {
|
||||
const { watchSoftCropPhoto } = await import("../desktop/softCropWatch.js");
|
||||
watchSoftCropPhoto(orgId, id, sha256);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -577,8 +577,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]) } });
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -485,9 +485,12 @@ 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.
|
||||
|
||||
**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
|
||||
|
||||
@@ -58,12 +58,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
|
||||
|
||||
Reference in new issue
Block a user