Compare commits

..
Author SHA1 Message Date
spark ac88d2445d Recognize a player from the club they were at that season.
ci / rust (pull_request) Successful in 12m25s
ci / typescript (pull_request) Failing after 14m4s
The same person keeps one record when they change club, and the shirt number stays the one worn that season. Liga squads are read for every season still published, and face processes grow until the CPU is about 99% full.
2026-10-21 20:37:41 +01:00
spark 81faa115ec Merge pull request 'Clear wrong face names without re-scoring every game' (#98) from task/faces-roster into main
ci / rust (push) Successful in 12m14s
ci / typescript (push) Failing after 15m56s
2026-10-21 20:19:00 +01:00
spark 7d5efc76b8 Clear wrong face names without re-scoring every game.
ci / rust (pull_request) Successful in 12m46s
ci / typescript (pull_request) Failing after 15m54s
Naming each game again on startup walks every person and stalls the photo analysis. The wrong names are removed; the next read of that game uses the roster.
2026-10-21 20:18:49 +01:00
spark 528666c13c Merge pull request 'Name a face only from the clubs of that game' (#97) from task/faces-roster into main
ci / rust (push) Successful in 11m48s
ci / typescript (push) Failing after 14m50s
Name a face only from the clubs of that game.
2026-10-21 20:12:54 +01:00
spark 17e5ff4bee Name a face only from the clubs of that game.
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Failing after 14m22s
A weak likeness was compared with every person in the organisation when the match sheet did not explain it, so a player of one club could be named as a player of another. A known game now stays on its roster, and a past season's squad is stored with the calendar.
2026-10-21 20:12:20 +01:00
spark a44850baa1 Merge pull request 'Merge exposures into a linear DNG in the collection, and stop a card copy before a day that does not fit.' (#89) from task/merge-collection into main
ci / rust (push) Successful in 11m16s
ci / typescript (push) Failing after 13m3s
Merge exposures into a linear DNG in the collection, and stop a card copy before a day that does not fit.
2026-10-21 13:43:25 +01:00
spark b3df241fdf Merge exposures into a linear DNG in the collection, and stop a card copy before a day that does not fit.
ci / rust (pull_request) Successful in 11m32s
ci / typescript (pull_request) Failing after 13m26s
2026-10-21 13:40:07 +01:00
spark ff1df42195 Merge pull request 'Confirm a person in one step, and fuse one angle at a time' (#87) from task/86-confirm-fuse into main
ci / rust (push) Successful in 9m29s
ci / typescript (push) Failing after 11m23s
Confirm a person in one step, and fuse one angle at a time.
2026-10-21 05:36:11 +01:00
spark efa9256c87 Confirm a person in one step, and fuse one angle at a time.
ci / rust (pull_request) Successful in 9m31s
ci / typescript (pull_request) Failing after 11m19s
A click waited on every game and each one rescored the library, so the card stayed and the API stopped answering. A property shoot was reading every raw at once, so the first angle never appeared.
2026-10-21 05:35:52 +01:00
spark 7fdbc9237b Merge pull request 'Show the whole card copy, finish a fused angle, and open a tournament under its tile' (#85) from task/84-progress-export into main
ci / rust (push) Successful in 9m36s
ci / typescript (push) Failing after 11m40s
Show the whole card copy, finish a fused angle, and open a tournament under its tile.
2026-10-21 05:13:33 +01:00
spark fd846ac68e Show the whole card copy, finish a fused angle, and open a tournament under its tile.
ci / rust (pull_request) Successful in 9m43s
ci / typescript (pull_request) Failing after 11m37s
The progress bar is the copy as a whole. A fused property angle can take a finish and be saved. A tournament's galleries open on the next row instead of below the list.
2026-10-21 05:12:53 +01:00
spark ff6d28064f Merge pull request 'Confirm a face without rescoring every other group first.' (#83) from task/faces-confirm into main
ci / rust (push) Successful in 12m7s
ci / typescript (push) Failing after 13m45s
Confirm a face without rescoring every other group first.
2026-10-21 04:56:43 +01:00
57 changed files with 2104 additions and 729 deletions

No files matched your search

+5
View File
@@ -474,6 +474,11 @@ export const isVariantSide = (s: string) =>
s.normalize("NFD").replace(/[\u0300-\u036f]/g, ""),
);
/** Every team this side names. One hit is that club; several is ambiguous (the caller does not guess). */
export function teamsNamed<T extends { name: string; abbreviation: string | null; slug: string }>(name: string, teams: T[]): T[] {
return teams.filter((t) => isTeam(name, t));
}
export function isTeam(name: string, team: { name: string; abbreviation: string | null; slug: string }): boolean {
const n = fold(name);
if (!n) return false;
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { teamsNamed } from "./match.js";
const team = (name: string, slug = name) => ({ id: slug, name, abbreviation: null as string | null, slug });
describe("teamsNamed", () => {
const clubs = [team("CD Feirense", "cd-feirense"), team("SC Farense", "sc-farense"), team("Sporting CP", "sporting-cp"), team("Sporting CP B", "sporting-cp-b")];
it("names Feirense and not Farense", () => {
expect(teamsNamed("CD Feirense", clubs).map((t) => t.name)).toEqual(["CD Feirense"]);
expect(teamsNamed("SC Farense", clubs).map((t) => t.name)).toEqual(["SC Farense"]);
});
it("keeps a senior side off its B team", () => {
expect(teamsNamed("Sporting CP", clubs).map((t) => t.name)).toEqual(["Sporting CP"]);
expect(teamsNamed("Sporting CP B", clubs).map((t) => t.name)).toEqual(["Sporting CP B"]);
});
});
+5 -5
View File
@@ -160,13 +160,13 @@ export class FaceLookup {
/**
* Named people like the face (their centroid: confirmed faces and reference photo).
* `prefer`, when set, is the whole search when anyone there matches: the game's players and officials.
* Only a face none of them match is compared with the rest of the organization.
* `prefer`, when it is a list, is a known game's roster and the whole search: a face none of them
* match stays unnamed. Null means the event is not a bounded game, so the whole organization is asked.
*/
async people(orgId: string, embedding: number[], model: string, limit = 5, prefer: string[] | null = null) {
if (prefer?.length) {
const inGame = await this.matchPeople(orgId, embedding, model, limit, prefer);
if (inGame.length) return inGame;
if (prefer) {
if (!prefer.length) return [];
return this.matchPeople(orgId, embedding, model, limit, prefer);
}
return this.matchPeople(orgId, embedding, model, limit, null);
}
+5 -5
View File
@@ -124,8 +124,8 @@ export async function registerLookupRoutes(
/**
* One photo from a folder, not imported: the clear faces, the shirt number under each, and the known person.
* A game is asked first (its players and officials). Anyone it does not know is looked up in the whole
* organization. The file is read and thrown away. Nothing is written to the library.
* A known game is only its players and officials. A face none of them match stays unnamed. The file is
* read and thrown away. Nothing is written to the library.
*/
app.post("/v1/orgs/:orgId/faces/scan", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
@@ -139,7 +139,7 @@ export async function registerLookupRoutes(
const ctx = eventId ? await numberContext(db, eventId) : null;
const ids = eventId ? await roster(eventId) : null;
const hits = await Promise.all(
read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids && ids.length ? ids : null))[0] ?? null) : null)),
read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids))[0] ?? null) : null)),
);
const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>();
return {
@@ -158,7 +158,7 @@ export async function registerLookupRoutes(
/**
* Names for faces already read on the photographer's computer. The photo stays there; only the embeddings
* (and nothing else) are compared, first with the game and then with everyone else.
* (and nothing else) are compared with the game's roster, or with the whole organization when it has none.
*/
app.post("/v1/orgs/:orgId/faces/identify", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
@@ -174,7 +174,7 @@ export async function registerLookupRoutes(
if (!org.biometricsEnabled) throw conflict("biometrics_disabled");
const ctx = body.eventId ? await numberContext(db, body.eventId) : null;
const ids = body.eventId ? await roster(body.eventId) : null;
const prefer = ids && ids.length ? ids : null;
const prefer = ids;
const hits = await Promise.all(body.faces.map(async (f) => (await lookup.people(orgId, f.embedding, body.model, 1, prefer))[0] ?? null));
const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>();
return {
+7
View File
@@ -52,6 +52,13 @@ export const THRESHOLDS: Record<string, { match: number; group: number; margin:
"sface-2021dec": { match: 0.55, group: 0.6, margin: 0.05 },
};
/** No roster (a session, a name that is not a club): a barely-there likeness is not a name. */
export const OPEN_EXTRA = 0.12;
export const OPEN_MARGIN = 0.08;
export function openFloor(match: number): number {
return Math.min(0.9, match + OPEN_EXTRA);
}
/**
* Faces softer than this (variance of the Laplacian of the 112 px aligned face, grey levels) are kept, boxed
* in the loupe, but never grouped: out-of-focus faces (crowd, background) all look alike to the embedder.
+60 -2
View File
@@ -1,6 +1,7 @@
import { isNationalSide, seasonOf } from "../archive/match.js";
import { isExhibition, isNationalSide, seasonOf, teamsNamed } from "../archive/match.js";
import type { Db } from "../db.js";
import { normLabel } from "../jersey/service.js";
import { eventSport } from "./sport.js";
import { JERSEY_MIN_SCORE, majorityNumber } from "./votes.js";
/**
@@ -19,6 +20,8 @@ export interface NumberContext {
national: boolean;
/** The season now: only then does the number typed on the person (with no season of its own) apply. */
current: boolean;
/** Linked to an official fixture: that competition's squad numbers come before what other shirts read. */
official: boolean;
teamIds: string[];
}
@@ -55,10 +58,52 @@ export async function numberContext(db: Db, eventId: string, now = new Date()):
competition: competitionKey(e),
national: isNationalEvent(e),
current: season === seasonOf(day(now)),
official: !!e.fixture,
teamIds: [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t),
};
}
/**
* Fills a game's missing clubs from the teams of its sport, when the side names exactly one of them.
* A session, a national team, or an exhibition is left alone. Idempotent.
*/
export async function bindEventTeams(db: Db, eventId: string): Promise<void> {
const e = await db.event.findUnique({
where: { id: eventId },
select: { home: true, away: true, competition: true, homeTeamId: true, awayTeamId: true, startsAt: true, fixture: { select: { season: true } } },
});
if (!e?.away?.trim() || (e.homeTeamId && e.awayTeamId)) return;
if (isNationalEvent(e) || isExhibition({ home: e.home, away: e.away, parents: e.competition ? [e.competition] : [] })) return;
const sport = await eventSport(db, eventId);
if (!sport) return;
const season = e.fixture?.season ?? seasonOf(day(e.startsAt));
const teams = await db.sportsTeam.findMany({
where: { sport: { equals: sport, mode: "insensitive" } },
select: { id: true, name: true, abbreviation: true, slug: true },
});
const homeId = e.homeTeamId ?? (await oneTeam(db, e.home, teams, season));
const awayId = e.awayTeamId ?? (await oneTeam(db, e.away, teams, season));
// One side resolved is still that club's squad. Both sides resolving to the same club is a bad guess.
if (homeId && awayId && homeId === awayId) return;
const data: { homeTeamId?: string; awayTeamId?: string } = {};
if (!e.homeTeamId && homeId && homeId !== awayId) data.homeTeamId = homeId;
if (!e.awayTeamId && awayId && awayId !== homeId) data.awayTeamId = awayId;
if (Object.keys(data).length) await db.event.update({ where: { id: eventId }, data });
}
/** The one team this side names, or the one of several that actually has a squad that season. */
async function oneTeam(db: Db, name: string, teams: { id: string; name: string; abbreviation: string | null; slug: string }[], season: string): Promise<string | null> {
const hits = teamsNamed(name, teams);
if (hits.length === 1) return hits[0]!.id;
if (hits.length < 2) return null;
const withSquad: typeof hits = [];
for (const h of hits) {
const n = await db.sportsPlayer.count({ where: { teamId: h.id, season } });
if (n > 0) withSquad.push(h);
}
return withSquad.length === 1 ? withSquad[0]!.id : null;
}
/**
* The number each person wears in this context, when it is known: the squad of that season (the official list)
* and what the shirts clearly read in their confirmed photos of the same season and competition (`learned`; first
@@ -128,7 +173,7 @@ export async function numbersIn(db: Db, ctx: NumberContext, personIds: string[],
// An official match: its season's squad first. A game not linked to one (a cup, a friendly, a tournament with
// its own numbering): what the shirts read in that competition first, then the season's squad.
const order = ctx.teamIds.length ? [squadOf, learnedOf] : [learnedOf, squadOf];
const order = ctx.official ? [squadOf, learnedOf] : [learnedOf, squadOf];
for (const p of people) {
const n = order[0]!.get(p.id) ?? order[1]!.get(p.id);
if (n) out.set(p.id, n);
@@ -152,6 +197,13 @@ interface FixtureOfficial {
externalId?: string | null;
}
/** The people a suggestion may name. Null: this event has no roster, so the caller uses the whole list. An empty list is a known squad that has no face on file yet. */
export function peopleOnRoster<T extends { id: string }>(people: T[], roster: string[] | null): T[] | null {
if (!roster) return null;
const ids = new Set(roster);
return people.filter((p) => ids.has(p.id));
}
/**
* Who this game should be asked first: the season's squad of the two teams (the same player, even when their
* person row points at another season) and the match officials who already have a face (referees, table).
@@ -159,6 +211,7 @@ interface FixtureOfficial {
* means the squad is known and none of them have a face on file yet.
*/
export async function rosterOf(db: Db, eventId: string): Promise<string[] | null> {
await bindEventTeams(db, eventId);
const ctx = await numberContext(db, eventId);
if (!ctx) return null;
const ids = new Set<string>();
@@ -179,6 +232,11 @@ export async function rosterOf(db: Db, eventId: string): Promise<string[] | null
AND (
squad.id = mine.id
OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id)
OR (
squad.birth_date IS NOT NULL AND squad.full_name IS NOT NULL
AND mine.birth_date = squad.birth_date
AND lower(mine.full_name) = lower(squad.full_name)
)
OR (squad.team_id = mine.team_id AND squad.name = mine.name)
)
)`;
+2 -2
View File
@@ -1,8 +1,8 @@
import { cpus } from "node:os";
import { LeastBusy, LineProcess } from "../lib/line-process.js";
/** Stop adding face processes once the machine is this full. */
const CPU_TARGET = 0.97;
/** Stop adding face processes once the machine is this full. One percent stays free for the rest of the system. */
const CPU_TARGET = 0.99;
interface CpuTimes {
idle: number;
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { openFloor } from "./math.js";
import { peopleOnRoster } from "./numbers.js";
describe("peopleOnRoster", () => {
const people = [{ id: "a" }, { id: "b" }, { id: "c" }];
it("uses the whole list only when the event has no roster", () => {
expect(peopleOnRoster(people, null)).toBeNull();
});
it("names nobody when the squad is known and none of them have a face yet", () => {
expect(peopleOnRoster(people, [])).toEqual([]);
});
it("keeps only the people on the sheet", () => {
expect(peopleOnRoster(people, ["b", "missing"]).map((p) => p.id)).toEqual(["b"]);
});
});
describe("openFloor", () => {
it("asks more of a face when the game has no roster", () => {
expect(openFloor(0.4)).toBeCloseTo(0.52);
expect(openFloor(0.55)).toBeCloseTo(0.67);
});
});
+19
View File
@@ -18,6 +18,10 @@ const PhotoParams = z.object({ photoId: z.uuid() });
const OrgParams = z.object({ orgId: z.uuid() });
const MergeBody = z.object({ into: z.uuid() });
const IgnoreBody = z.object({ ignored: z.boolean() });
const ConfirmPileBody = z.object({
personId: z.uuid(),
groupIds: z.array(z.uuid()).min(1).max(80),
});
const BiometricsBody = z.object({
enabled: z.boolean(),
/** Required to switch on: why the organization may process faces (e.g. consent, contract, legitimate interest). */
@@ -148,6 +152,21 @@ export async function registerFaceRoutes(
};
});
/** One click names every game of that person. Separate requests were rescored in parallel until the API stopped. */
app.post("/v1/orgs/:orgId/face-review/confirm", { preHandler: authenticate }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
await requireMembership(db, req, orgId, "INGESTER");
const body = ConfirmPileBody.parse(req.body);
const groups = await db.faceGroup.findMany({ where: { id: { in: body.groupIds } }, select: { id: true, organizationId: true } });
if (groups.length !== new Set(body.groupIds).size || groups.some((group) => group.organizationId !== orgId)) throw notFound("group_not_found");
try {
const person = await faces.confirmPile(body.groupIds, body.personId, currentUserId(req));
return { person: personOut(person) };
} catch (err) {
return fail(err);
}
});
app.post("/v1/face-groups/:groupId/confirm", { preHandler: authenticate }, async (req) => {
const { groupId } = GroupParams.parse(req.params);
const body = ConfirmFaceGroup.parse(req.body);
+187 -68
View File
@@ -15,11 +15,13 @@ import { normLabel } from "../jersey/service.js";
/** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */
const STRONG_SUGGESTION = 0.85;
export { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
export { eventSport, normSport } from "./sport.js";
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
import { numberContext, numbersIn, rosterOf, type NumberContext } from "./numbers.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
import { numberContext, numbersIn, peopleOnRoster, rosterOf, type NumberContext } from "./numbers.js";
import { eventSport, normSport } from "./sport.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, OPEN_MARGIN, THRESHOLDS, openFloor } from "./math.js";
import type { FaceEngine } from "./process.js";
import { FaceFollower } from "./track.js";
import { randomUUID } from "node:crypto";
@@ -62,6 +64,10 @@ export class FaceRejected extends Error {
* confirms a group, name every photo in it, including photos that arrive later.
*/
export class FaceService {
/** Events waiting to be rescored. One run at a time: a burst of Confirmar was starting dozens and the API stopped answering. */
private readonly pendingRefresh = new Set<string>();
private refreshRunning = false;
constructor(
private readonly deps: {
db: Db;
@@ -118,6 +124,12 @@ export class FaceService {
(n) => void (n && this.deps.log.warn({ groups: n }, "faces: suggestions of another sport taken away")),
(err) => this.deps.log.warn({ err }, "faces: cross-sport suggestions not checked"),
);
// A name from outside a known game (made when a weak face was compared with the whole organization).
// Cleared only. Naming the game again here walks every person of every event and stalls photo analysis.
void dropOffRosterSuggestions(this.deps.db).then(
(n) => void (n && this.deps.log.warn({ groups: n }, "faces: suggestions from outside the game taken away")),
(err) => this.deps.log.warn({ err }, "faces: roster suggestions not checked"),
);
const r = await this.deps.db.photo.updateMany({
where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } },
data: { facesStatus: "PENDING" },
@@ -540,12 +552,13 @@ export class FaceService {
const sport = await eventSport(db, eventId);
const sports = sport ? await peopleSports(db, everyone) : new Map<string, string>();
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
// A game whose clubs are known is named only from that squad. A session (no roster) is compared with
// everyone of the sport, and only a clearly stronger face: a weak likeness is not a name.
const sheet = await rosterOf(db, eventId);
const bounded = sheet !== null;
const pool = peopleOnRoster(people, sheet) ?? people;
// Numbers as worn in this event's season and competition (another season, a cup, the national team: another).
const ctx = await numberContext(db, eventId);
// A game: the match sheet first (players, coaches, referees who already have a face). A session has no sheet,
// so the face is compared with everyone of that sport. The wider list is only for a face the sheet does not explain.
const sheet = await rosterOf(db, eventId);
const onSheet = sheet && sheet.length ? new Set(sheet) : null;
const worn = new Map<string, string | null>();
const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => {
const missing = ids.filter((id) => !worn.has(id));
@@ -555,15 +568,18 @@ export class FaceService {
}
return worn;
};
const pick = async (pool: typeof people, g: (typeof groups)[number], allowNumber: boolean) => {
const pick = async (candidates: typeof people, g: (typeof groups)[number], allowNumber: boolean) => {
const { match, margin } = this.thresholds(g.model);
// No roster: 0.40 is enough for two bald faces of different clubs to trade names. Ask for a clearer gap.
const floor = bounded ? match : openFloor(match);
const gap = bounded ? margin : Math.max(margin, OPEN_MARGIN);
const rejected = notThem.get(g.id);
const ranked = pool
const ranked = candidates
.filter((p) => p.model === g.model && !rejected?.has(p.id))
.map((p) => ({ p, s: cosine(p.centroid, g.centroid) }))
.sort((a, b) => b.s - a.s);
const [first, second] = ranked;
const ok = first && first.s >= match && (!second || first.s - second.s >= margin);
const ok = first && first.s >= floor && (!second || first.s - second.s >= gap);
let suggestedPersonId = ok ? first.p.id : null;
let suggestionScore = ok ? first.s : null;
const read = await this.groupNumber(g.id);
@@ -577,7 +593,7 @@ export class FaceService {
} else if (!ok && read && allowNumber) {
// The face alone is not sure (too weak, or two people too close): the number decides among the near ones,
// and when two of them wear it (one per team), the kit colour.
const close = ranked.filter((r) => r.s >= match * 0.8);
const close = ranked.filter((r) => r.s >= (bounded ? match * 0.8 : floor));
const nums = await numberOf(close.map((r) => r.p.id));
let near = close.filter((r) => nums.get(r.p.id) === read.number);
if (near.length > 1) {
@@ -601,10 +617,7 @@ export class FaceService {
return { suggestedPersonId, suggestionScore };
};
for (const g of groups) {
const first = onSheet ? people.filter((p) => onSheet.has(p.id)) : people;
let { suggestedPersonId, suggestionScore } = await pick(first, g, true);
// Nobody on the sheet: only then a face from outside it. The shirt stays with the two clubs.
if (!suggestedPersonId && onSheet) ({ suggestedPersonId, suggestionScore } = await pick(people, g, false));
const { suggestedPersonId, suggestionScore } = await pick(pool, g, true);
if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) {
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
}
@@ -629,7 +642,9 @@ export class FaceService {
select: { organizationId: true, home: true, away: true, homeShort: true, awayShort: true, homeTeamId: true, awayTeamId: true },
});
if (!event) return null;
// Linked to the official match: that season's squads say who wears the number (not today's squad).
// The two clubs are known: that season's squads say who wears the number (not today's squad).
// A cup whose shirts use another numbering still wins when the face is already close to someone
// (`numbersIn` reads that competition first, unless this event is the official fixture).
const teamIds = ctx.teamIds;
if (teamIds.length) {
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, season: ctx.season, number: read.number }, select: { id: true, teamId: true, name: true, externalId: true } });
@@ -730,17 +745,50 @@ export class FaceService {
where: { id: { in: photoIds } },
select: { id: true, organizationId: true, players: true, faces: { select: { group: { select: { person: { select: { name: true } } } } } } },
});
const pending: { id: string; organizationId: string; players: string[] }[] = [];
for (const photo of photos) {
const names = photo.faces.map((f) => f.group?.person?.name).filter((n): n is string => !!n);
const players = [...new Set([...photo.players, ...names])];
if (players.length === photo.players.length) continue;
await db.photo.update({ where: { id: photo.id }, data: { players } });
broadcaster.library(photo.organizationId, { type: "photo.updated", ids: [photo.id], patch: { players } });
pending.push({ id: photo.id, organizationId: photo.organizationId, players });
}
if (!pending.length) return;
await db.$transaction(pending.map((photo) => db.photo.update({ where: { id: photo.id }, data: { players: photo.players } })));
for (const photo of pending) {
broadcaster.library(photo.organizationId, { type: "photo.updated", ids: [photo.id], patch: { players: photo.players } });
}
}
/** Names a group: an existing person, or a new one. Every photo with a face in the group gets the name. */
async confirm(groupId: string, who: { personId: string } | { name: string; club?: string | undefined; number?: string | undefined }, userId: string | null): Promise<Person> {
const named = await this.writeConfirmation(groupId, who, userId);
await this.finishConfirmation(named.person.id, [named.eventId], named.organizationId);
return named.person;
}
/**
* Names every selected group as one person, then rescores once. The queue used to confirm each game as its own
* request, and each request rescored the library, so one click sat there and a few clicks stopped the API.
*/
async confirmPile(groupIds: string[], personId: string, userId: string | null): Promise<Person> {
const unique = [...new Set(groupIds)];
if (unique.length === 0) throw new FaceRejected("group_not_found");
let named: { person: Person; eventId: string; organizationId: string } | null = null;
const events = new Set<string>();
for (const groupId of unique) {
named = await this.writeConfirmation(groupId, { personId }, userId);
events.add(named.eventId);
}
if (!named) throw new FaceRejected("group_not_found");
await this.finishConfirmation(personId, [...events], named.organizationId);
return named.person;
}
private async writeConfirmation(
groupId: string,
who: { personId: string } | { name: string; club?: string | undefined; number?: string | undefined },
userId: string | null,
): Promise<{ person: Person; eventId: string; organizationId: string }> {
const { db } = this.deps;
const group = await db.faceGroup.findUnique({ where: { id: groupId } });
if (!group) throw new FaceRejected("group_not_found");
@@ -763,43 +811,64 @@ export class FaceService {
person = await this.recomputePerson(person.id);
const photoIds = (await db.face.findMany({ where: { groupId }, select: { photoId: true } })).map((f) => f.photoId);
await this.nameConfirmedPhotos([...new Set(photoIds)]);
// Same-event cards of this person collapse before the answer. Rescoring every other open face (this match
// and up to 25 others) used to run inside the request, so Confirmar sat there until the proxy gave up.
await this.joinSamePerson(group.eventId);
const others = await db.faceGroup.findMany({
where: { suggestedPersonId: person.id, personId: null, ignoredAt: null, eventId: { not: group.eventId } },
return { person, eventId: group.eventId, organizationId: group.organizationId };
}
/** Collapse same-event cards, then rescore. The rescore does not hold the click. */
private async finishConfirmation(personId: string, eventIds: string[], organizationId: string): Promise<void> {
for (const eventId of eventIds) await this.joinSamePerson(eventId);
const others = await this.deps.db.faceGroup.findMany({
where: { suggestedPersonId: personId, personId: null, ignoredAt: null, eventId: { notIn: eventIds } },
select: { eventId: true },
distinct: ["eventId"],
take: 25,
});
await this.scheduleRefresh([group.eventId, ...others.map((other) => other.eventId)]);
this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId });
return person;
await this.scheduleRefresh([...eventIds, ...others.map((other) => other.eventId)]);
for (const eventId of eventIds) {
this.deps.broadcaster.library(organizationId, { type: "faces.updated", eventId });
}
}
/**
* Rescore open faces after the name is saved. The click must not wait on it: a match with hundreds of
* unnamed faces was holding the request until the proxy gave up, and the button looked dead.
* Tests share one database, so there the refresh finishes before the response (a late write would land in the next test).
* One queue for the process. Tests share one database, so there the refresh finishes before the response.
*/
private async scheduleRefresh(eventIds: string[]): Promise<void> {
const ids = [...new Set(eventIds)];
const inline = process.env.NODE_ENV === "test";
const run = async () => {
for (const eventId of ids) {
try {
await this.refreshSuggestions(eventId);
} catch (err) {
if (inline) throw err;
this.deps.log.warn({ eventId, err: err instanceof Error ? err.message : String(err) }, "faces: suggestion refresh failed");
}
}
};
if (inline) {
await run();
for (const eventId of eventIds) this.pendingRefresh.add(eventId);
if (process.env.NODE_ENV === "test") {
await this.drainRefresh();
return;
}
void run();
this.kickRefresh();
}
private kickRefresh(): void {
if (this.refreshRunning) return;
this.refreshRunning = true;
void this.drainRefresh()
.catch((err) => {
this.deps.log.warn({ err: err instanceof Error ? err.message : String(err) }, "faces: suggestion refresh failed");
})
.finally(() => {
this.refreshRunning = false;
if (this.pendingRefresh.size > 0) this.kickRefresh();
});
}
private async drainRefresh(): Promise<void> {
const inline = process.env.NODE_ENV === "test";
while (this.pendingRefresh.size > 0) {
const eventId = this.pendingRefresh.values().next().value;
if (!eventId) return;
this.pendingRefresh.delete(eventId);
try {
await this.refreshSuggestions(eventId);
} catch (err) {
if (inline) throw err;
this.deps.log.warn({ eventId, err: err instanceof Error ? err.message : String(err) }, "faces: suggestion refresh failed");
}
}
}
/** A name typed as a code (\v7\) becomes the name in the organization's code list. */
@@ -835,6 +904,35 @@ export class FaceService {
return rows.map((r) => r.id);
}
/**
* Games to look at again after a new headshot. A player is only compared with games of clubs they have
* played for. Someone typed by hand (no squad row) is still compared with the last 45 days.
*/
private async eventsForReference(person: { organizationId: string; sportsPlayerId: string | null }, since: Date) {
const { db } = this.deps;
const recent = () => db.event.findMany({ where: { organizationId: person.organizationId, startsAt: { gte: since } }, select: { id: true } });
if (!person.sportsPlayerId) return recent();
const mine = await db.sportsPlayer.findUnique({
where: { id: person.sportsPlayerId },
select: { teamId: true, externalId: true, birthDate: true, fullName: true },
});
if (!mine) return recent();
const match: ({ teamId: string } | { externalId: string } | { birthDate: string; fullName: string })[] = [{ teamId: mine.teamId }];
if (mine.externalId) match.push({ externalId: mine.externalId });
if (mine.birthDate && mine.fullName) match.push({ birthDate: mine.birthDate, fullName: mine.fullName });
const mates = await db.sportsPlayer.findMany({ where: { OR: match }, select: { teamId: true } });
const teamIds = [...new Set(mates.map((m) => m.teamId))];
if (!teamIds.length) return recent();
return db.event.findMany({
where: {
organizationId: person.organizationId,
startsAt: { gte: since },
OR: [{ homeTeamId: { in: teamIds } }, { awayTeamId: { in: teamIds } }],
},
select: { id: true },
});
}
/** Reads a reference photo: the largest face becomes the person's reference. Never throws. */
async processReference(personId: string): Promise<void> {
const { db, storage, engine, log } = this.deps;
@@ -859,7 +957,7 @@ export class FaceService {
await this.recomputePerson(personId);
// Open groups of the last weeks may now have a suggestion.
const since = new Date(Date.now() - 45 * 86_400_000);
const events = await db.event.findMany({ where: { organizationId: person.organizationId, startsAt: { gte: since } }, select: { id: true } });
const events = await this.eventsForReference(person, since);
for (const e of events) {
await this.refreshSuggestions(e.id);
this.deps.broadcaster.library(person.organizationId, { type: "faces.updated", eventId: e.id });
@@ -1019,28 +1117,6 @@ export class FaceService {
}
}
/** Keeps `processes` face engines busy. */
/** "Futebol", "football" → "futebol"; "Andebol", "handball" → "andebol". */
export function normSport(s: string | null | undefined): string | null {
const v = (s ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
if (!v) return null;
if (/futebol|football|soccer/.test(v)) return "futebol";
if (/andebol|handball/.test(v)) return "andebol";
return v;
}
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
const rows = await db.$queryRaw<{ sport: string | null }[]>`
SELECT COALESCE(e.sport, c.sport, CASE s.look WHEN 'liga' THEN 'futebol' WHEN 'fpa' THEN 'andebol' END) AS sport
FROM events e
LEFT JOIN sports_fixtures f ON f.id = e.fixture_id
LEFT JOIN sports_competitions c ON c.id = f.competition_id
LEFT JOIN LATERAL (SELECT cs.look FROM cloud_folders cf JOIN cloud_sources cs ON cs.id = cf.source_id WHERE cf.event_id = e.id LIMIT 1) s ON true
WHERE e.id = ${eventId}::uuid`;
return normSport(rows[0]?.sport);
}
/** Each person's sport, from the team of the squad they came from (people typed by hand have none). */
export async function peopleSports(db: Db, people: { id: string; sportsPlayerId: string | null }[]): Promise<Map<string, string>> {
const ids = [...new Set(people.map((p) => p.sportsPlayerId).filter((x): x is string => !!x))];
@@ -1073,6 +1149,42 @@ export async function dropCrossSportSuggestions(db: Db): Promise<number> {
return n;
}
/**
* Suggestions of someone who is not on the game's roster (a weak face compared with the whole organization)
* taken away; names confirmed by a person stay. The game is named again the next time its photos are read.
* Returns how many suggestions were cleared.
*/
export async function dropOffRosterSuggestions(db: Db, refresh?: (eventId: string) => Promise<void>): Promise<number> {
const events = await db.faceGroup.findMany({
where: { personId: null, suggestedPersonId: { not: null }, event: { away: { not: "" } } },
select: { eventId: true },
distinct: ["eventId"],
});
let n = 0;
for (const { eventId } of events) {
const roster = await rosterOf(db, eventId);
const groups = await db.faceGroup.findMany({
where: { eventId, personId: null, suggestedPersonId: { not: null } },
select: { id: true, suggestedPersonId: true, suggestionScore: true, model: true },
});
const allowed = roster ? new Set(roster) : null;
const drop = groups
.filter((g) => {
if (!g.suggestedPersonId) return false;
if (allowed) return !allowed.has(g.suggestedPersonId);
const match = THRESHOLDS[g.model]?.match ?? 0.4;
return (g.suggestionScore ?? 0) < openFloor(match);
})
.map((g) => g.id);
if (!drop.length) continue;
await db.faceGroup.updateMany({ where: { id: { in: drop } }, data: { suggestedPersonId: null, suggestionScore: null } });
n += drop.length;
if (refresh) await refresh(eventId).catch(() => undefined);
}
return n;
}
/** Keeps `processes` face engines busy. */
export class FaceWorker {
private inFlight = 0;
private videosInFlight = 0;
@@ -1084,9 +1196,15 @@ export class FaceWorker {
constructor(
private readonly service: FaceService,
private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger; heartbeat?: () => void },
private readonly opts: { concurrency: number | (() => number); intervalMs: number; log: IngestLogger; heartbeat?: () => void },
) {}
/** Places to keep busy. A function follows a pool that grows as the CPU stays under its limit. */
private places(): number {
const n = typeof this.opts.concurrency === "function" ? this.opts.concurrency() : this.opts.concurrency;
return Math.max(1, n);
}
/** Lets the API tell a dead worker from a long queue. Throttled: the tick itself is every second. */
private beat(): void {
if (!this.opts.heartbeat) return;
@@ -1136,9 +1254,10 @@ export class FaceWorker {
});
}
};
const shared = this.opts.concurrency > 1;
if (shared && this.videosInFlight === 0 && this.inFlight < this.opts.concurrency) await startVideo();
const ids = await this.service.claim(this.opts.concurrency - this.inFlight - (shared ? this.videosInFlight : 0));
const places = this.places();
const shared = places > 1;
if (shared && this.videosInFlight === 0 && this.inFlight < places) await startVideo();
const ids = await this.service.claim(places - this.inFlight - (shared ? this.videosInFlight : 0));
for (const id of ids) {
this.inFlight++;
void this.service.process(id).finally(() => {
+22
View File
@@ -0,0 +1,22 @@
import type { Db } from "../db.js";
/** "Futebol", "football" → "futebol"; "Andebol", "handball" → "andebol". */
export function normSport(s: string | null | undefined): string | null {
const v = (s ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
if (!v) return null;
if (/futebol|football|soccer/.test(v)) return "futebol";
if (/andebol|handball/.test(v)) return "andebol";
return v;
}
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
const rows = await db.$queryRaw<{ sport: string | null }[]>`
SELECT COALESCE(e.sport, c.sport, CASE s.look WHEN 'liga' THEN 'futebol' WHEN 'fpa' THEN 'andebol' END) AS sport
FROM events e
LEFT JOIN sports_fixtures f ON f.id = e.fixture_id
LEFT JOIN sports_competitions c ON c.id = f.competition_id
LEFT JOIN LATERAL (SELECT cs.look FROM cloud_folders cf JOIN cloud_sources cs ON cs.id = cf.source_id WHERE cf.event_id = e.id LIMIT 1) s ON true
WHERE e.id = ${eventId}::uuid`;
return normSport(rows[0]?.sport);
}
+84 -10
View File
@@ -129,6 +129,10 @@ export class IngestService {
eventId?: string | undefined;
/** `file` is a preview made by the desktop app; the original (described here) stays on that computer. */
original?: PreviewOf | undefined;
/** Stay in the inbox. A capture time must not pull a merge into whatever event is open today. */
inbox?: boolean;
/** A preview held until its linear original replaces it: no broadcast, no autopilot, no arrival copy. */
held?: boolean;
},
): Promise<Exclude<IngestOutcome, { status: "skipped" }>> {
const { db, storage, log } = this.deps;
@@ -159,10 +163,13 @@ export class IngestService {
const at = capturedAt ?? new Date();
// Archive imports name their own event. A file with no camera time, or a time outside that event's window,
// must not fall through onto whatever is live today.
const eventId =
origin.source === "CLOUD"
? await this.namedEvent(orgId, origin.eventId)
: (await this.requestedEvent(orgId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at));
const eventId = origin.inbox
? null
: origin.held && origin.eventId
? origin.eventId
: origin.source === "CLOUD"
? await this.namedEvent(orgId, origin.eventId)
: (await this.requestedEvent(orgId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at));
const storageKey = storage.originalKey(orgId, sha256, ext === ".jpeg" ? ".jpg" : ext);
const size = (await stat(file)).size;
await storage.adopt(file, storageKey);
@@ -210,15 +217,16 @@ export class IngestService {
// The event's autopilot edits what arrives by FTP, the desktop app, or a hand upload (a second photographer's
// photos added by hand count too); only archive re-imports (CLOUD) are left as they were.
const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true } }) : null;
const autopilot = origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true;
const autopilot = !origin.held && origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true;
const readFaces = !origin.held && org?.biometricsEnabled === true;
photo = await db.photo.update({
where: { id: photo.id },
data: {
status: "READY",
width,
height,
facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE",
...(org?.biometricsEnabled && event?.faceBoostedAt && { facesBoostedAt: event.faceBoostedAt }),
facesStatus: readFaces ? "PENDING" : "NONE",
...(readFaces && event?.faceBoostedAt && { facesBoostedAt: event.faceBoostedAt }),
...(autopilot && { autopilotStatus: "PENDING" }),
},
});
@@ -227,7 +235,7 @@ export class IngestService {
outcome = { status: "ingested", photoId: photo.id, eventId };
log.info({ photoId: photo.id, eventId, source: origin.source }, "ingest: photo ready");
// A copy of every arrival where one asked for it (one's own backup, a client taking everything).
if (eventId && origin.source !== "CLOUD" && this.arrivals) await this.arrivals({ id: photo.id, organizationId: orgId, uploaderId: photo.uploaderId }).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: arrival not sent on"));
if (!origin.held && eventId && origin.source !== "CLOUD" && this.arrivals) await this.arrivals({ id: photo.id, organizationId: orgId, uploaderId: photo.uploaderId }).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: arrival not sent on"));
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
photo = await db.photo.update({ where: { id: photo.id }, data: { status: "FAILED", error } });
@@ -235,11 +243,77 @@ export class IngestService {
log.warn({ photoId: photo.id, error }, "ingest: could not process photo");
}
const full = await db.photo.findUniqueOrThrow({ where: { id: photo.id }, include: photoInclude });
this.deps.broadcaster.library(orgId, { type: "photo.added", photo: toSummary(full, this.deps.signer) });
if (!origin.held) {
const full = await db.photo.findUniqueOrThrow({ where: { id: photo.id }, include: photoInclude });
this.deps.broadcaster.library(orgId, { type: "photo.added", photo: toSummary(full, this.deps.signer) });
}
return outcome;
}
/**
* Replaces a held JPEG preview with the linear DNG of a merge. Derivatives stay (they are the preview).
* The photo is announced once, as the DNG. A second copy of the same DNG drops the preview and returns
* the one already in the library.
*/
async attachLinearDng(
photo: { id: string; organizationId: string; sha256: string; storageKey: string; originalName: string },
dngFile: string,
meta: { width: number; height: number; capturedAt: Date | null },
): Promise<{ status: "ingested" | "duplicate"; photoId: string }> {
const { db, storage, log } = this.deps;
const sha = await sha256File(dngFile);
const existing = await db.photo.findUnique({ where: { organizationId_sha256: { organizationId: photo.organizationId, sha256: sha } }, select: { id: true } });
if (existing && existing.id !== photo.id) {
await rm(dngFile, { force: true });
await this.discardHeld(photo.id);
return { status: "duplicate", photoId: existing.id };
}
const size = (await stat(dngFile)).size;
if (size > 2_000_000_000) throw new Error("file_too_large");
if (sha !== photo.sha256) {
for (const variant of ["thumb", "preview"] as const) {
const from = storage.derivedKey(photo.organizationId, photo.sha256, variant);
if (await storage.exists(from)) await storage.adopt(storage.resolve(from), storage.derivedKey(photo.organizationId, sha, variant));
}
}
const key = storage.originalKey(photo.organizationId, sha, ".dng");
await storage.adopt(dngFile, key);
if (photo.storageKey !== key) await storage.remove(photo.storageKey);
const dot = photo.originalName.lastIndexOf(".");
const stem = dot > 0 ? photo.originalName.slice(0, dot) : photo.originalName;
const updated = await db.photo.update({
where: { id: photo.id },
data: {
sha256: sha,
storageKey: key,
byteSize: size,
originalName: `${stem}.dng`,
originalStored: true,
status: "READY",
error: null,
width: meta.width,
height: meta.height,
facesStatus: "NONE",
autopilotStatus: "NONE",
...(meta.capturedAt && { capturedAt: meta.capturedAt, takenAt: meta.capturedAt }),
},
});
const full = await db.photo.findUniqueOrThrow({ where: { id: updated.id }, include: photoInclude });
this.deps.broadcaster.library(photo.organizationId, { type: "photo.added", photo: toSummary(full, this.deps.signer) });
log.info({ photoId: photo.id }, "ingest: linear merge stored");
return { status: "ingested", photoId: photo.id };
}
/** Drops a preview that was held for a merge and then not kept (bad file, or the DNG was already here). */
async discardHeld(photoId: string): Promise<void> {
const photo = await this.deps.db.photo.findUnique({ where: { id: photoId }, select: { id: true, organizationId: true, sha256: true, storageKey: true } });
if (!photo) return;
await this.deps.db.photo.delete({ where: { id: photoId } }).catch(() => {});
await this.deps.storage.remove(photo.storageKey);
await this.deps.storage.remove(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "thumb"));
await this.deps.storage.remove(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "preview"));
}
/** The full original of a photo that so far only had the desktop's preview (moved into place: `file` is consumed). */
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
const { db, storage, log } = this.deps;
+3 -4
View File
@@ -45,10 +45,9 @@ export function planCapacity(
return {
cpus,
memoryGb: Math.round(memoryGb * 10) / 10,
// Face binaries use the cores and wait idle when there is nothing to analyse. Their results are committed
// by this one Node thread, which also uploads to ZeroZero. Dozens at once stall that thread: deliveries
// fail with "fetch failed" and face transactions expire. FACES_PROCESSES in the environment still overrides.
faces: set.faces ?? clamp(Math.min(cpus * 0.9, byMemory("faces", 0.5)), 2, 6),
// One face process per core, added while the CPU is under about 99% (GrowingFacePool). The model is
// about 0.8 GB, so a small container stops sooner. FACES_PROCESSES in the environment still overrides.
faces: set.faces ?? Math.max(1, Math.min(Math.max(1, Math.floor(cpus * 0.99)), byMemory("faces", 0.7))),
ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32),
archive: set.archive ?? clamp(Math.min(cpus * 0.3, byMemory("archive", 0.2)), 2, 32),
// A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share.
+2 -1
View File
@@ -186,7 +186,8 @@ export async function registerPhotoRoutes(
}
return reply.code(409).send({ error: "original_not_here" });
}
return reply.header("content-type", "image/jpeg").header("cache-control", "private, max-age=3600").send(createReadStream(storage.resolve(photo.storageKey)));
const type = photo.storageKey.toLowerCase().endsWith(".dng") ? "image/x-adobe-dng" : "image/jpeg";
return reply.header("content-type", type).header("cache-control", "private, max-age=3600").send(createReadStream(storage.resolve(photo.storageKey)));
});
/** Asks the desktop app that keeps this photo's original to send it (it listens on the live channel). */
+69 -4
View File
@@ -1,7 +1,7 @@
import multipart from "@fastify/multipart";
import { randomUUID } from "node:crypto";
import { createWriteStream } from "node:fs";
import { appendFile, mkdir, rm, stat } from "node:fs/promises";
import { appendFile, mkdir, open, rm, stat } from "node:fs/promises";
import path from "node:path";
import { pipeline } from "node:stream/promises";
import type { FastifyInstance } from "fastify";
@@ -16,7 +16,12 @@ import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { photoInclude, toSummary } from "./serialize.js";
const OrgParams = z.object({ orgId: z.uuid() });
const UploadQuery = z.object({ eventId: z.uuid().optional() });
const UploadQuery = z.object({ eventId: z.uuid().optional(), silent: z.string().optional(), inbox: z.string().optional() });
const LinearQuery = z.object({
capturedAt: z.string().optional(),
width: z.coerce.number().int().positive().max(100_000),
height: z.coerce.number().int().positive().max(100_000),
});
const PhotoParams = z.object({ photoId: z.uuid() });
export const MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
@@ -35,7 +40,8 @@ export async function registerUploadRoutes(
app.post("/v1/orgs/:orgId/uploads", { preHandler: authenticate }, async (req, reply) => {
const { orgId } = OrgParams.parse(req.params);
const { eventId } = UploadQuery.parse(req.query);
const query = UploadQuery.parse(req.query);
const { eventId } = query;
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) {
throw badRequest("event_not_in_organization");
@@ -53,7 +59,15 @@ export async function registerUploadRoutes(
try {
await pipeline(part.file, createWriteStream(tmp));
if (part.file.truncated) throw new AppError(413, "file_too_large");
const outcome = await ingest.ingest(tmp, { organizationId: orgId, userId: currentUserId(req), source: "UPLOAD", originalName: name, eventId });
const outcome = await ingest.ingest(tmp, {
organizationId: orgId,
userId: currentUserId(req),
source: "UPLOAD",
originalName: name,
eventId,
...(query.inbox === "1" && { inbox: true }),
...(query.silent === "1" && { held: true }),
});
const photo = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude });
return reply.code(outcome.status === "duplicate" ? 200 : 201).send({ status: outcome.status, photo: toSummary(photo, signer) });
} finally {
@@ -61,6 +75,42 @@ export async function registerUploadRoutes(
}
});
/**
* The linear DNG of a merge, replacing the JPEG preview uploaded just before (held, not announced).
* One announcement goes out, for the DNG, so the collection shows it once.
*/
app.post("/v1/photos/:photoId/linear-dng", { preHandler: authenticate }, async (req) => {
const { photoId } = PhotoParams.parse(req.params);
const query = LinearQuery.parse(req.query);
const capturedAt = query.capturedAt ? new Date(query.capturedAt) : null;
if (query.capturedAt && (capturedAt === null || Number.isNaN(capturedAt.getTime()))) throw badRequest("bad_date");
const photo = await db.photo.findUnique({
where: { id: photoId },
select: { id: true, organizationId: true, sha256: true, storageKey: true, originalName: true },
});
if (!photo) throw new AppError(404, "photo_not_found");
await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER");
const part = await req.file();
if (!part) throw badRequest("file_missing");
const tmpDir = storage.resolve(".uploads");
await mkdir(tmpDir, { recursive: true });
const tmp = path.join(tmpDir, `${randomUUID()}.part`);
let stored = false;
try {
await pipeline(part.file, createWriteStream(tmp));
if (part.file.truncated) throw new AppError(413, "file_too_large");
if (!(await isTiff(tmp))) throw badRequest("not_a_dng");
const outcome = await ingest.attachLinearDng(photo, tmp, { width: query.width, height: query.height, capturedAt });
stored = true;
const full = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude });
return { status: outcome.status, photo: toSummary(full, signer) };
} catch (err) {
if (!stored) await ingest.discardHeld(photo.id).catch(() => {});
await rm(tmp, { force: true });
throw err;
}
});
/**
* The desktop app sends the original of a photo that only has its preview here, when the file on that computer
* no longer has the fingerprint it had on arrival (Photo Mechanic wrote captions into it afterwards). Same photo:
@@ -204,3 +254,18 @@ export async function registerUploadRoutes(
});
});
}
/** LightCraft's linear DNG is a TIFF. A mosaic raw is not accepted through this door. */
async function isTiff(file: string): Promise<boolean> {
const handle = await open(file, "r");
try {
const buf = Buffer.alloc(4);
const { bytesRead } = await handle.read(buf, 0, 4, 0);
if (bytesRead < 4) return false;
const little = buf[0] === 0x49 && buf[1] === 0x49 && buf[2] === 0x2a && buf[3] === 0x00;
const big = buf[0] === 0x4d && buf[1] === 0x4d && buf[2] === 0x00 && buf[3] === 0x2a;
return little || big;
} finally {
await handle.close();
}
}
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { samePlayer, type PlayerIdentity } from "./identity.js";
const row = (over: Partial<PlayerIdentity>): PlayerIdentity => ({
externalId: null,
birthDate: null,
fullName: null,
teamId: "team",
name: "Zalazar",
...over,
});
describe("samePlayer", () => {
it("follows the federation id from one club to another", () => {
const then = row({ externalId: "p1", teamId: "feirense", name: "Zalazar", fullName: "Rodrigo Zalazar" });
const now = row({ externalId: "p1", teamId: "sporting", name: "Zalazar", fullName: "Rodrigo Zalazar Martinez" });
expect(samePlayer(then, now)).toBe(true);
});
it("uses the birth date and full name when the id differs", () => {
const then = row({ birthDate: "1999-08-12", fullName: "Rodrigo Zalazar Martínez", teamId: "feirense" });
const now = row({ externalId: "other", birthDate: "1999-08-12", fullName: "Rodrigo Zalazar Martinez", teamId: "sporting" });
expect(samePlayer(then, now)).toBe(true);
});
it("does not treat two shirt names at different clubs as one person", () => {
const a = row({ name: "Silva", fullName: "Rui Silva", teamId: "a" });
const b = row({ name: "Silva", fullName: "João Silva", teamId: "b" });
expect(samePlayer(a, b)).toBe(false);
});
});
+22
View File
@@ -0,0 +1,22 @@
/** A squad row, enough to tell one human from another across clubs and seasons. */
export interface PlayerIdentity {
externalId: string | null;
birthDate: string | null;
fullName: string | null;
teamId: string;
name: string;
}
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
/**
* The same human: the federation's id (stable when they change club), or the same birth date and full name.
* The same shirt name in the same club is the last resort. A shirt name alone is not, and neither is today's club.
*/
export function samePlayer(a: PlayerIdentity, b: PlayerIdentity): boolean {
if (a.externalId && a.externalId === b.externalId) return true;
const left = fold(a.fullName ?? "");
const right = fold(b.fullName ?? "");
if (a.birthDate && left && a.birthDate === b.birthDate && left === right) return true;
return a.teamId === b.teamId && a.name === b.name;
}
+278 -15
View File
@@ -9,6 +9,7 @@ import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js";
import type { LocalStorage } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
import { samePlayer } from "./identity.js";
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
import {
type Fetch,
@@ -186,6 +187,123 @@ export class SportsService {
}
}
this.deps.log.info({ season, saved }, "sports: liga season imported");
// The calendar used to be all that a past season stored. Squads follow, without holding the folder scan.
void this.importLigaSquads({ season: asked, limit: 80 }).catch((err) => this.deps.log.warn({ err, season: asked }, "sports: liga squads not read"));
return saved;
}
/** Squads already on file are skipped. An empty or failed read is tried again next process, not in a loop. */
private readonly squadClaimed = new Set<string>();
/** Competition-seasons whose team lists were read to the end. The current season is never marked done while empty. */
private readonly registerDone = new Set<string>();
/**
* Liga squads for seasons whose games are already stored but whose player lists were never read.
* Other federations publish the sheet per match (line-ups), not a season squad, so this is Liga's list only.
* The people those rows become are `linkStoredSquads`.
*/
async importLigaSquads(opts: { season?: string; limit?: number } = {}): Promise<number> {
const limit = opts.limit ?? 20;
const season = opts.season?.replace(/\D/g, "") || null;
// A dummy value keeps the array non-empty: Prisma cannot type an empty one, and ALL('{}') is awkward.
const claimed = this.squadClaimed.size ? [...this.squadClaimed] : ["__none__"];
const rows = await this.deps.db.$queryRaw<{ id: string; external_id: string; season: string }[]>`
SELECT DISTINCT t.id, t.external_id, f.season
FROM sports_teams t
JOIN sports_fixtures f ON (f.home_team_id = t.id OR f.away_team_id = t.id)
JOIN sports_competitions c ON c.id = f.competition_id
WHERE t.provider = 'LIGA' AND c.provider = 'LIGA'
AND (${season}::text IS NULL OR f.season = ${season})
AND NOT EXISTS (SELECT 1 FROM sports_players p WHERE p.team_id = t.id AND p.season = f.season)
AND (t.id::text || ':' || f.season) <> ALL(${claimed}::text[])
ORDER BY f.season DESC
LIMIT ${limit}`;
let changed = 0;
for (const t of rows) {
const key = `${t.id}:${t.season}`;
if (this.squadClaimed.has(key)) continue;
this.squadClaimed.add(key);
try {
changed += await this.savePlayers(t.id, t.season, await this.liga.squad(t.external_id, t.season), "api");
} catch (err) {
this.squadClaimed.delete(key);
this.deps.log.warn({ err, team: t.id, season: t.season }, "sports: liga squad not read");
}
}
if (changed) this.deps.log.info({ season, changed }, "sports: liga squads imported");
return changed;
}
/**
* Every Liga club and every player the federation still publishes, season by season, newest first.
* A photo of a club five years ago then has that season's squad, including players who have since moved.
* Stops at the first past season that lists no teams. The current season being empty (pre-season) does not stop it.
* `stopped` is checked between requests so a shutdown leaves within one call.
*/
async backfillLigaRegister(stopped: () => boolean): Promise<number> {
await this.ensureCatalog();
const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "LIGA" } });
let season = seasonOf(new Date());
let saved = 0;
for (let year = 0; year < 25 && !stopped(); year++) {
let sawTeams = false;
let failed = 0;
for (const c of comps) {
if (stopped()) return saved;
const key = `${c.externalId}:${season}`;
if (this.registerDone.has(key)) {
sawTeams = true;
continue;
}
let teams: TeamData[];
try {
teams = await this.liga.teams(c.externalId, season);
} catch (err) {
const missing = err instanceof ProviderHttpError ? err.status === 404 : err instanceof Error && err.message.startsWith("liga: unexpected");
if (missing) {
this.registerDone.add(key);
continue;
}
failed++;
this.deps.log.warn({ err, competition: c.externalId, season }, "sports: liga teams not read");
continue;
}
if (!teams.length) {
this.registerDone.add(key);
continue;
}
sawTeams = true;
let complete = true;
for (const t of teams) {
if (stopped()) return saved;
const teamId = await this.upsertTeam("LIGA", t);
await this.deps.db.sportsCompetitionTeam.upsert({
where: { competitionId_teamId_season: { competitionId: c.id, teamId, season } },
create: { competitionId: c.id, teamId, season },
update: {},
});
const have = await this.deps.db.sportsPlayer.count({ where: { teamId, season } });
if (have > 0) continue;
const claim = `${teamId}:${season}`;
if (this.squadClaimed.has(claim)) continue;
this.squadClaimed.add(claim);
try {
saved += await this.savePlayers(teamId, season, await this.liga.squad(t.externalId, season), "api");
} catch (err) {
complete = false;
this.squadClaimed.delete(claim);
this.deps.log.warn({ err, team: t.name, season }, "sports: liga squad not read");
}
}
if (complete) this.registerDone.add(key);
}
if (failed === comps.length && comps.length) break;
if (year > 0 && !sawTeams) break;
const start = Number(season.slice(0, 4)) - 1;
if (!Number.isFinite(start) || start < 2000) break;
season = `${start}${start + 1}`;
}
if (saved) this.deps.log.info({ saved }, "sports: liga register imported");
return saved;
}
@@ -745,9 +863,12 @@ export class SportsService {
// --- squads -----------------------------------------------------------------------------------------------------
/** A team's current squad: its latest season, without the players who left. */
async squad(teamId: string) {
const latest = await this.deps.db.sportsPlayer.findFirst({ where: { teamId }, orderBy: { updatedAt: "desc" }, select: { season: true } });
/** A team's squad for one season, or its latest when none is asked. Players who left are left out. */
async squad(teamId: string, season?: string) {
// Season, not updatedAt: reading an old season must not make it look like the current squad.
const latest = season
? { season }
: await this.deps.db.sportsPlayer.findFirst({ where: { teamId }, orderBy: { season: "desc" }, select: { season: true } });
if (!latest) return [];
const players = await this.deps.db.sportsPlayer.findMany({ where: { teamId, season: latest.season, goneAt: null } });
// Shirt numbers, then the handball officials by letter (A, B, …), then those without either.
@@ -758,7 +879,10 @@ export class SportsService {
/** Both teams of an event, with the person each player is in the organisation (for tagging by number). */
async eventSquads(eventId: string) {
const { db } = this.deps;
const event = await db.event.findUnique({ where: { id: eventId }, include: { homeTeam: true, awayTeam: true } });
const event = await db.event.findUnique({
where: { id: eventId },
include: { homeTeam: true, awayTeam: true, fixture: { select: { season: true } } },
});
if (!event) throw notFound("event_not_found");
const sides = [] as { side: "home" | "away"; team: { id: string; name: string; abbreviation: string | null; logoUrl: string | null }; players: unknown[] }[];
// Photos of each person in this event: faces confirmed as them, and faces the system takes for them (the
@@ -777,12 +901,9 @@ export class SportsService {
["away", event.awayTeam],
] as const) {
if (!team) continue;
const players = await this.squad(team.id);
const people = await db.person.findMany({
where: { organizationId: event.organizationId, sportsPlayerId: { in: players.map((p) => p.id) } },
select: { id: true, sportsPlayerId: true },
});
const personOf = new Map(people.map((p) => [p.sportsPlayerId, p.id]));
const season = event.fixture?.season ?? seasonOf(event.startsAt);
const players = await this.squad(team.id, season);
const personOf = await this.peopleOf(event.organizationId, players);
sides.push({
side,
team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl },
@@ -830,7 +951,7 @@ export class SportsService {
include: {
homeTeam: true,
awayTeam: true,
fixture: { select: { id: true, externalId: true, round: true, officials: true, competition: { select: { provider: true, externalId: true, season: true } } } },
fixture: { select: { id: true, season: true, externalId: true, round: true, officials: true, competition: { select: { provider: true, externalId: true, season: true } } } },
organization: { select: { biometricsEnabled: true, codeGenerator: true } },
},
});
@@ -840,10 +961,10 @@ export class SportsService {
const result = { created: 0, updated: 0, headshots: 0 };
const headshots: { personId: string; url: string }[] = [];
// Liga squads are read again right now (players and coaching staff), not only on the 6-hourly refresh.
const season = event.fixture?.season ?? seasonOf(event.startsAt);
for (const team of [event.homeTeam, event.awayTeam]) {
if (team?.provider !== "LIGA") continue;
try {
const season = event.fixture?.competition.provider === "LIGA" ? event.fixture.competition.season : seasonOf(new Date());
await this.savePlayers(team.id, season, await this.liga.squad(team.externalId, season), "api");
} catch (err) {
log.warn({ err, team: team.id }, "sports: liga squad re-read failed");
@@ -852,7 +973,7 @@ export class SportsService {
for (const team of [event.homeTeam, event.awayTeam]) {
if (!team) continue;
const club = settings.teamNames[team.id] ?? team.name;
for (const p of await this.squad(team.id)) {
for (const p of await this.squad(team.id, season)) {
await this.linkSquadPerson(orgId, team, club, p, event.organization.biometricsEnabled, headshots, result);
}
}
@@ -944,6 +1065,7 @@ export class SportsService {
const { db, log } = this.deps;
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
let created = false;
if (!person) person = await this.personForIdentity(orgId, p);
if (!person) {
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } });
if (byName && !byName.sportsPlayerId && (!byName.club || byName.club === club || byName.club === team.name)) person = byName;
@@ -966,8 +1088,10 @@ export class SportsService {
}
}
}
const linkedSeason = person.sportsPlayerId === p.id ? p.season : await this.seasonOfLinked(person.sportsPlayerId);
const newer = !linkedSeason || p.season >= linkedSeason;
if (created) result.created++;
else if (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id) {
else if (newer && (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id)) {
person = await db.person.update({ where: { id: person.id }, data: { club, number: p.number, sportsPlayerId: p.id } });
result.updated++;
}
@@ -984,6 +1108,124 @@ export class SportsService {
if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo });
}
/** The person already created for this human at another club or in another season. */
private async personForIdentity(orgId: string, p: SportsPlayer) {
const match: ({ externalId: string } | { birthDate: string; fullName: string })[] = [];
if (p.externalId) match.push({ externalId: p.externalId });
if (p.birthDate && p.fullName) match.push({ birthDate: p.birthDate, fullName: p.fullName });
if (!match.length) return null;
const rows = await this.deps.db.sportsPlayer.findMany({ where: { OR: match }, select: { id: true } });
if (!rows.length) return null;
return this.deps.db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: rows.map((r) => r.id) } } });
}
private async seasonOfLinked(sportsPlayerId: string | null): Promise<string | null> {
if (!sportsPlayerId) return null;
const linked = await this.deps.db.sportsPlayer.findUnique({ where: { id: sportsPlayerId }, select: { season: true } });
return linked?.season ?? null;
}
/** Which person is each squad row: the row itself, or the same human at the club they play for now. */
private async peopleOf(orgId: string, players: SportsPlayer[]): Promise<Map<string, string>> {
const out = new Map<string, string>();
if (!players.length) return out;
const externalIds = [...new Set(players.map((p) => p.externalId).filter((id): id is string => !!id))];
const births = players.filter((p): p is SportsPlayer & { birthDate: string; fullName: string } => !!p.birthDate && !!p.fullName);
const keys = await this.deps.db.sportsPlayer.findMany({
where: {
OR: [
{ id: { in: players.map((p) => p.id) } },
...(externalIds.length ? [{ externalId: { in: externalIds } }] : []),
...births.map((p) => ({ birthDate: p.birthDate, fullName: p.fullName })),
],
},
select: { id: true, externalId: true, birthDate: true, fullName: true, teamId: true, name: true },
});
if (!keys.length) return out;
const people = await this.deps.db.person.findMany({
where: { organizationId: orgId, sportsPlayerId: { in: keys.map((k) => k.id) } },
select: { id: true, sportsPlayerId: true },
});
const personByPlayer = new Map(people.map((p) => [p.sportsPlayerId, p.id]));
for (const player of players) {
const hit = keys.find((k) => k.id && personByPlayer.has(k.id) && samePlayer(k, player));
if (hit?.id) {
const personId = personByPlayer.get(hit.id);
if (personId) out.set(player.id, personId);
}
}
return out;
}
/**
* Squad rows that no person of the organisation represents yet become people (and, a few at a time, reference
* photos). A player already known by the federation's id is not created again under an old club. Only
* organisations that turned biometrics on, and only clubs that already appear on one of their games.
*/
async linkStoredSquads(limit = 8): Promise<number> {
const { db, log } = this.deps;
const rows = await db.$queryRaw<{ organization_id: string; player_id: string }[]>`
SELECT e.organization_id, sp.id AS player_id
FROM sports_players sp
JOIN sports_teams t ON t.id = sp.team_id
JOIN events e ON (e.home_team_id = t.id OR e.away_team_id = t.id)
JOIN organizations o ON o.id = e.organization_id AND o.biometrics_enabled
WHERE NOT EXISTS (
SELECT 1 FROM people p
JOIN sports_players mine ON mine.id = p.sports_player_id
WHERE p.organization_id = e.organization_id
AND (
mine.id = sp.id
OR (sp.external_id IS NOT NULL AND mine.external_id = sp.external_id)
OR (
sp.birth_date IS NOT NULL AND sp.full_name IS NOT NULL
AND mine.birth_date = sp.birth_date
AND lower(mine.full_name) = lower(sp.full_name)
)
OR (mine.team_id = sp.team_id AND mine.name = sp.name)
)
)
GROUP BY e.organization_id, sp.id, sp.season
ORDER BY sp.season DESC
LIMIT ${limit}`;
if (!rows.length) return 0;
const players = await db.sportsPlayer.findMany({ where: { id: { in: rows.map((r) => r.player_id) } }, include: { team: true } });
const byId = new Map(players.map((p) => [p.id, p]));
const settingsOf = new Map<string, CodeGeneratorSettings>();
const fresh: { personId: string; url: string }[] = [];
const headshots: { orgId: string; personId: string; url: string }[] = [];
const result = { created: 0, updated: 0 };
for (const row of rows) {
const p = byId.get(row.player_id);
if (!p) continue;
let settings = settingsOf.get(row.organization_id);
if (!settings) {
settings = await this.settings(row.organization_id);
settingsOf.set(row.organization_id, settings);
}
const club = settings.teamNames[p.team.id] ?? p.team.name;
const before = fresh.length;
try {
await this.linkSquadPerson(row.organization_id, p.team, club, p, true, fresh, result);
} catch (err) {
log.warn({ err, player: p.id, organization: row.organization_id }, "sports: squad person not linked");
}
for (const h of fresh.slice(before)) headshots.push({ orgId: row.organization_id, ...h });
}
for (let i = 0; i < headshots.length; i += 4) {
await Promise.all(
headshots.slice(i, i + 4).map((h) =>
this.saveHeadshot(h.orgId, h.personId, h.url).catch((err) => {
log.warn({ err, person: h.personId }, "sports: headshot failed");
return false;
}),
),
);
}
if (result.created) log.info({ created: result.created, headshots: headshots.length }, "sports: squad people linked");
return result.created;
}
private async saveHeadshot(orgId: string, personId: string, src: string): Promise<boolean> {
const u = new URL(src);
if (u.protocol !== "https:" || !HEADSHOT_HOSTS.includes(u.hostname)) return false;
@@ -1075,6 +1317,7 @@ export class SportsWorker {
private timer: ReturnType<typeof setTimeout> | undefined;
private stopped = false;
private ticking = false;
private filling = false;
private lastRefresh = 0;
constructor(
@@ -1083,12 +1326,16 @@ export class SportsWorker {
) {}
start(): void {
void this.fillRegister();
const tick = async () => {
this.ticking = true;
try {
if (Date.now() - this.lastRefresh >= (this.opts.refreshCheckMs ?? 10 * 60_000)) {
this.lastRefresh = Date.now();
await this.service.refreshDue();
// Past seasons used to store only the calendar. A few missing squads, then the people they name.
await this.service.importLigaSquads({ limit: 20 });
await this.service.linkStoredSquads(24);
}
await this.service.pollLineups();
} catch (err) {
@@ -1101,10 +1348,26 @@ export class SportsWorker {
this.timer = setTimeout(tick, 5_000);
}
/** Past seasons of every Liga club, then the people those rows are. One pass per process; the tick keeps up afterwards. */
private async fillRegister(): Promise<void> {
this.filling = true;
try {
await this.service.backfillLigaRegister(() => this.stopped);
while (!this.stopped) {
const n = await this.service.linkStoredSquads(24);
if (!n) break;
}
} catch (err) {
this.opts.log.warn({ err }, "sports: register not filled");
} finally {
this.filling = false;
}
}
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking, { timeoutMs });
const drained = await waitUntil(() => !this.ticking && !this.filling, { timeoutMs });
if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running");
}
}
+5 -4
View File
@@ -14,7 +14,7 @@ import { SecretBox } from "./delivery/secrets.js";
import { DeliveryService, DeliveryWorker } from "./delivery/service.js";
import { RenderPool, RenderProcess } from "./develop/engine.js";
import { DevelopService, RenderWorker } from "./develop/service.js";
import { FacePool, FaceProcess } from "./faces/process.js";
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
import { SportsService, SportsWorker } from "./sports/service.js";
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
@@ -126,15 +126,16 @@ const invoices = new InvoicingWorker(new InvoicingService({ db, secrets, log, no
const faceEngine =
config.FACES_BIN && config.FACES_MODELS_DIR
? new FacePool(
Array.from({ length: capacity.faces }, () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER })),
? new GrowingFacePool(
() => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER }),
capacity.faces,
)
: undefined;
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
const faces = faceEngine
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), {
concurrency: capacity.faces,
concurrency: () => faceEngine?.size ?? 1,
intervalMs: 1000,
log,
heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT),
+2 -2
View File
@@ -8,8 +8,8 @@ describe("capacity", () => {
const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB });
const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * GB });
expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, autopilot: 2, delivery: 4 });
expect(big).toMatchObject({ cpus: 32, faces: 6, ingest: 8, archive: 9, archiveBurst: 91, render: 16, autopilot: 16, delivery: 8 });
expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 6, archiveBurst: 91, archiveDownloads: 960 });
expect(big).toMatchObject({ cpus: 32, faces: 31, ingest: 8, archive: 9, archiveBurst: 91, render: 16, autopilot: 16, delivery: 8 });
expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 47, archiveBurst: 91, archiveDownloads: 960 });
// A fixed ARCHIVE_CONCURRENCY never holds a backlog back; downloads run many at once even on a small machine.
expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 });
});
+3 -2
View File
@@ -174,7 +174,7 @@ describe("search by photo", () => {
expect(res.json()).toMatchObject({ roster: 1, faces: [{ person: { id: rui.id, name: "Rui Silva" } }] });
});
it("asks the game first, including a referee, and the rest of the organization only when the game has no match", async () => {
it("asks the game first, including a referee, and leaves a face the game does not know unnamed", async () => {
const { orgId, token, events, rui } = await setup();
const home = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "gil2", sport: "andebol", name: "Gil Eanes", slug: "gil-eanes-2" } });
const away = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "cdf2", sport: "andebol", name: "Feirense", slug: "feirense-2" } });
@@ -206,7 +206,8 @@ describe("search by photo", () => {
engine.next = { width: 800, height: 1000, faces: [found(4, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
res = await post();
expect(res.json()).toMatchObject({ faces: [{ person: { id: outsider.id, name: "Só lá fora" } }] });
expect(res.json()).toMatchObject({ faces: [{ person: null }] });
expect(JSON.stringify(res.json())).not.toContain(outsider.id);
});
it("names an embedding read on the photographer's computer, without the photo", async () => {
-2
View File
@@ -16,7 +16,6 @@ import { LoginPage } from "./pages/LoginPage.js";
import { MembersPage } from "./pages/MembersPage.js";
import { MetadataPage } from "./pages/MetadataPage.js";
import { PreferencesPage } from "./pages/PreferencesPage.js";
import { RealEstatePage } from "./pages/RealEstatePage.js";
import { Shell } from "./pages/Shell.js";
function Gate() {
@@ -41,7 +40,6 @@ function Gate() {
<Route path="members" element={<MembersPage />} />
<Route path="preferences" element={<PreferencesPage />} />
<Route path="help" element={<HelpPage />} />
<Route path="real-estate" element={<RealEstatePage />} />
<Route path="*" element={<p className="p-6 text-sm text-muted">{t.notFound}</p>} />
</Route>
<Route path="/login" element={<Navigate to="/" replace />} />
+2
View File
@@ -22,6 +22,8 @@ export interface WasmPhoto {
export interface BracketJob {
push(bytes: Uint8Array): void;
merge(maxEdge: number): BracketMerge;
/** Scene-linear DNG. Absent on an engine built before it. */
mergeDng?(maxEdge: number): Uint8Array;
free(): void;
}
+40 -1
View File
@@ -219,6 +219,8 @@ export const t = {
off: "Desligado",
intro: "Larga os ficheiros de um imóvel. Cada ângulo são várias exposições da mesma posição, normalmente três. Os ficheiros ficam neste computador; para agrupar só seguem os dados de exposição.",
step: "Cada ângulo é fundido aqui, neste computador, pelo motor de imagem. A janela vem da exposição escura e a sala da clara.",
queued: "À espera da vez…",
readingOne: "A ler este ângulo…",
fusing: "A fundir este ângulo…",
fuseFailed: "Não deu para fundir este ângulo.",
previewAlt: (n: number) => `Ângulo ${n} fundido`,
@@ -226,6 +228,25 @@ export const t = {
chooseFolder: "Escolher pasta",
dropHint: "ou larga uma pasta aqui",
reading: (done: number, total: number) => `A ler ${done} de ${total}…`,
readingAll: (n: number, total: number) => `A ler o ângulo ${n} de ${total}`,
fusingOne: (n: number, total: number) => `A fundir o ângulo ${n} de ${total}`,
fusingAll: (done: number, total: number) => `A fundir ${done} de ${total} ângulos`,
savingAll: (done: number, total: number) => `A guardar ${done} de ${total}`,
resultHelp: "Cada imagem é o ângulo já fundido. Escolhe um acabamento e guarda o JPEG neste computador.",
save: "Guardar",
saveAll: "Guardar todos",
edit: "Editar",
exposure: "Exposição",
highlights: "Altas luzes",
shadows: "Sombras",
lookFailed: "Não apliquei o acabamento.",
savedFolder: "Os JPEG ficaram na pasta que escolheste.",
savedDownload: "Os JPEG foram descarregados.",
looks: {
natural: "Natural",
interior: "Interior claro",
brighter: "Mais luz",
},
noPhotos: "Não há fotografias nesta seleção. Um ficheiro XMP só acompanha o raw.",
support: (n: number) => (n === 1 ? "1 ficheiro de apoio (XMP e semelhantes) não é uma fotografia." : `${n} ficheiros de apoio (XMP e semelhantes) não são fotografias.`),
asideMore: (n: number) => `e mais ${n}`,
@@ -250,6 +271,19 @@ export const t = {
empty: "Ainda não há presets.",
remove: "Apagar",
},
merge: {
button: "Fundir exposições",
title: "Funde as exposições do mesmo ângulo num DNG linear, na coleção. As originais ficam. O acabamento faz-se no Revelar.",
reading: "A ler as exposições…",
working: (n: number, total: number) => `A fundir ${n} de ${total}…`,
done: (n: number) => (n === 1 ? "1 DNG ficou na coleção." : `${n} DNG ficaram na coleção.`),
errors: {
none: "Não há um conjunto de exposições. Seleciona as fotos do mesmo ângulo.",
missing: "Falta o ficheiro original de alguma exposição.",
engine: "O motor ainda não grava o DNG. Quando a cópia do cartão acabar, atualiza a página.",
failed: "Não fundi. Tenta outra vez.",
},
},
card: {
title: "Importar cartão",
open: "Cartão…",
@@ -274,7 +308,9 @@ export const t = {
sidecars: "Levar WAV/XMP",
needSource: "Escolhe primeiro o cartão/pasta de origem.",
progress: (done: number, total: number, name: string) => `A processar ${done}/${total}… ${name}`,
remaining: (label: string) => `faltam cerca de ${label}`,
overall: (done: number, total: number, percent: number) => `${done} de ${total} · ${percent}%`,
general: "Geral",
remaining: (label: string) => (label.startsWith("menos") ? `falta ${label}` : `faltam cerca de ${label}`),
stop: "Parar",
stopping: "Pára depois do ficheiro que está a copiar.",
oldShellStop: "Esta versão da app de secretária ainda não consegue parar a meio. Atualiza-a; a cópia que já vai continua.",
@@ -284,6 +320,9 @@ export const t = {
moveAction: "Mover",
scan: (raw: number, jpeg: number, other: number, size: string) =>
other > 0 ? `${raw} RAW · ${jpeg} JPEG · ${other} outras · ${size}` : `${raw} RAW · ${jpeg} JPEG · ${size}`,
free: (size: string) => `Livre no destino: ${size}`,
fits: "Cabe no disco, com margem.",
notAll: "Não cabe tudo. Copio dias completos e paro antes do dia que não cabe.",
result: {
moved: (n: number) => `${n} movidas`,
copied: (n: number) => `${n} copiadas`,
+55 -7
View File
@@ -1,8 +1,8 @@
import { useEffect, useState, useSyncExternalStore } from "react";
import { t } from "../i18n.js";
import { desktopInvoke } from "../platform.js";
import { copyPace } from "./cardPace.js";
import { cardJobList, dismissCard, enqueueCard, startQueued, stopCard, subscribeCardJobs, type CardJob, type CardResult, type CardSettings, type RawJpeg } from "./cardJobs.js";
import { copyPace, overallPace } from "./cardPace.js";
import { cardJobList, dismissCard, enqueueCard, rescanQueued, startQueued, stopCard, subscribeCardJobs, type CardJob, type CardResult, type CardSettings, type RawJpeg } from "./cardJobs.js";
import { SnapshotMenu } from "./SnapshotMenu.js";
/**
@@ -66,6 +66,13 @@ function CardDialog({ onClose }: { onClose: () => void }) {
desktopInvoke<CardSettings>("card_settings").then(setS).catch(() => {});
}, []);
useEffect(() => {
const timer = setTimeout(() => {
void rescanQueued(s);
}, 400);
return () => clearTimeout(timer);
}, [s]);
const pickSource = async () => {
setError(null);
const path = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
@@ -230,15 +237,21 @@ function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => v
{job.status === "stopped" && <span className="shrink-0 text-faint">{t.card.stopped}</span>}
</div>
{scan && <p className="mt-1 text-muted">{scan}</p>}
{job.scan?.freeBytes != null && (
<p className="mt-1 text-muted">
{t.card.free(human(job.scan.freeBytes))}
{job.scan.fits === true ? ` · ${t.card.fits}` : ""}
{job.scan.fits === false ? ` · ${t.card.notAll}` : ""}
</p>
)}
{job.status === "running" && job.progress && (
<>
<div className="mt-2 h-1.5 overflow-hidden bg-black">
<div className="h-full bg-accent" style={{ width: `${Math.round(pace.fraction * 100)}%` }} />
</div>
<p className="mt-1 text-muted">
{t.card.progress(job.progress.done, job.progress.total, job.progress.name)}
<p className="mt-2 text-ink">
{t.card.overall(job.progress.done, job.progress.total, Math.round(pace.fraction * 100))}
{pace.left ? ` · ${t.card.remaining(pace.left)}` : ""}
</p>
<Track fraction={pace.fraction} />
{job.progress.name && <p className="mt-1 truncate text-muted">{job.progress.name}</p>}
</>
)}
{job.error && <p className="mt-1 text-danger">{job.error}</p>}
@@ -247,6 +260,41 @@ function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => v
);
}
/** The copy as a whole, under the library, including when the card window is closed. */
export function CardOverallStatus() {
const jobs = useCardJobs();
const [, setTick] = useState(0);
const running = jobs.some((job) => job.status === "running");
useEffect(() => {
if (!running) return;
const timer = setInterval(() => setTick((n) => n + 1), 1000);
return () => clearInterval(timer);
}, [running]);
const overall = overallPace(jobs, Date.now());
if (!overall) return null;
const name = jobs.find((job) => job.status === "running" && job.progress?.name)?.progress?.name;
return (
<div className="border-t border-line bg-panel px-3 py-2" role="status" aria-label={t.card.general}>
<p className="mb-1 flex flex-wrap items-baseline gap-x-2 text-[12px] text-ink">
<span className="font-semibold">{t.card.general}</span>
<span>{t.card.overall(overall.done, overall.total, Math.round(overall.fraction * 100))}</span>
{overall.left && <span className="text-muted">{t.card.remaining(overall.left)}</span>}
{name && <span className="min-w-0 truncate text-muted">{name}</span>}
</p>
<Track fraction={overall.fraction} />
</div>
);
}
function Track({ fraction }: { fraction: number }) {
const percent = Math.round(Math.max(0, Math.min(1, fraction)) * 100);
return (
<div className="mt-1 h-3 overflow-hidden bg-black" role="progressbar" aria-valuenow={percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full bg-accent" style={{ width: `${percent}%` }} />
</div>
);
}
function JobResult({ result }: { result: CardResult }) {
const parts = [
result.moved ? t.card.result.moved(result.moved) : "",
+74
View File
@@ -0,0 +1,74 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { useRef, useState } from "react";
import { t } from "../i18n.js";
import { MergeError, mergeIntoCollection } from "./mergeExposures.js";
/**
* "Fundir exposições": the selection (or every detected bracket in the folder) becomes a linear DNG
* in this collection. The originals stay. The editor's own controls do the finish.
*/
export function MergeButton({
api,
orgId,
eventId,
photos,
selectedIds,
}: {
api: ApiClient;
orgId: string;
/** Null is the inbox. */
eventId: string | null;
photos: readonly PhotoSummary[];
selectedIds: readonly string[];
}) {
const [status, setStatus] = useState<string | null>(null);
const [failed, setFailed] = useState(false);
const [busy, setBusy] = useState(false);
const pending = useRef(false);
const run = async () => {
if (pending.current) return;
pending.current = true;
setBusy(true);
setFailed(false);
setStatus(t.merge.reading);
try {
const made = await mergeIntoCollection({
api,
orgId,
eventId,
photos,
selectedIds,
onStatus: (stack, total) => setStatus(t.merge.working(stack, total)),
});
setStatus(t.merge.done(made));
} catch (err) {
const code = err instanceof MergeError ? err.code : "failed";
setStatus(t.merge.errors[code] ?? t.merge.errors.failed);
setFailed(true);
} finally {
pending.current = false;
setBusy(false);
}
};
return (
<span className="inline-flex items-center gap-2">
<button
type="button"
title={t.merge.title}
disabled={busy}
onClick={() => void run()}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.merge.button}
</button>
{status && (
<span role="status" className={`max-w-64 truncate text-[12px] ${failed ? "text-danger" : "text-muted"}`}>
{status}
</span>
)}
</span>
);
}
+20
View File
@@ -16,6 +16,10 @@ export interface CardScan {
jpeg: number;
other: number;
bytes: number;
/** Free bytes on the destination. Absent on a shell that does not report it. */
freeBytes?: number;
/** False when the card would not fit, with a gigabyte left over. */
fits?: boolean;
}
export interface CardResult {
@@ -116,6 +120,22 @@ function ensureProgress() {
});
}
/** Asks again, with the destination, so the dialog can show free space. An older shell keeps the first scan. */
export async function rescanQueued(settings: CardSettings): Promise<void> {
const waiting = jobs.filter((job) => job.status === "queued");
await Promise.all(
waiting.map(async (job) => {
try {
const scan = await desktopInvoke<CardScan>("card_scan", { source: job.source, settings });
const current = jobs.find((item) => item.id === job.id);
if (current?.status === "queued") patch(job.id, { scan });
} catch {
// The installed shell scans without a destination. The counts from enqueue stay.
}
}),
);
}
export async function enqueueCard(source: string): Promise<void> {
const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
jobs = [...jobs, { id, source, settings: null, scan: null, status: "queued", progress: null, startedAt: null, result: null, error: null }];
+28 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { copyPace, formatRemaining, remainingMs } from "./cardPace.js";
import { copyPace, formatRemaining, overallPace, remainingMs } from "./cardPace.js";
describe("card copy pace", () => {
it("estimates the rest from the bytes already written", () => {
@@ -12,6 +12,33 @@ describe("card copy pace", () => {
expect(pace.left).toBe("1 min");
});
it("adds every card into one bar", () => {
const started = 1_000;
const now = started + 10_000;
const pace = overallPace(
[
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 10, bytesTotal: 40 } },
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 30, bytesTotal: 60 } },
{ status: "queued", startedAt: null, progress: null },
],
now,
);
expect(pace).toMatchObject({ done: 2, total: 8 });
expect(pace?.fraction).toBeCloseTo(0.4);
});
it("counts files when a card has no byte total", () => {
const started = 1_000;
const pace = overallPace(
[
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 10, bytesTotal: 40 } },
{ status: "running", startedAt: started, progress: { done: 2, total: 4 } },
],
started + 10_000,
);
expect(pace?.fraction).toBeCloseTo(3 / 8);
});
it("waits for a little progress before guessing", () => {
expect(remainingMs(0, 10, 0, 5_000)).toBeNull();
expect(remainingMs(1, 10, 0, 100)).toBeNull();
+28
View File
@@ -16,6 +16,34 @@ export function formatRemaining(ms: number): string {
return `${hours} h ${rest} min`;
}
export interface PaceJob {
status: string;
startedAt: number | null;
progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null;
}
/** One bar for every card still copying: bytes when each job reports them, otherwise file counts. */
export function overallPace(jobs: readonly PaceJob[], now: number): { done: number; total: number; fraction: number; left: string | null } | null {
const running = jobs.filter((job) => job.status === "running" && job.progress && job.progress.total > 0 && job.startedAt !== null);
if (running.length === 0) return null;
const startedAt = Math.min(...running.map((job) => job.startedAt as number));
const done = running.reduce((sum, job) => sum + (job.progress?.done ?? 0), 0);
const total = running.reduce((sum, job) => sum + (job.progress?.total ?? 0), 0);
const byBytes = running.every((job) => (job.progress?.bytesTotal ?? 0) > 0);
const progress = {
done,
total,
...(byBytes
? {
bytesDone: running.reduce((sum, job) => sum + (job.progress?.bytesDone ?? 0), 0),
bytesTotal: running.reduce((sum, job) => sum + (job.progress?.bytesTotal ?? 0), 0),
}
: {}),
};
const pace = copyPace(progress, startedAt, now);
return { done, total, fraction: pace.fraction, left: pace.left };
}
export function copyPace(
progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null,
startedAt: number | null,
+113
View File
@@ -0,0 +1,113 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { loadEngine, type EngineModule } from "../develop/engine.js";
import { localOriginal } from "../platform.js";
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
export class MergeError extends Error {
constructor(readonly code: "none" | "missing" | "engine" | "failed") {
super(code);
}
}
async function loadFrame(photo: PhotoSummary, api: ApiClient): Promise<Uint8Array | null> {
const local = await localOriginal(photo.sha256);
if (local && local.byteLength > 0) return new Uint8Array(local);
if (!photo.originalStored) return null;
const bytes = await api.originalBytes(photo.id);
if (!bytes || bytes.byteLength === 0) return null;
return new Uint8Array(bytes);
}
function rgbaToJpeg(rgba: Uint8Array, width: number, height: number): Promise<Blob> {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
if (!context || width <= 0 || height <= 0) return Promise.reject(new Error("canvas"));
const pixels = new Uint8ClampedArray(rgba.byteLength);
pixels.set(rgba);
context.putImageData(new ImageData(pixels, width, height), 0, 0);
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("jpeg"))), "image/jpeg", 0.92);
});
}
/** A neutral JPEG of the linear file, so the grid has something to show before the editor opens the DNG. */
async function previewOf(engine: EngineModule, dng: Uint8Array): Promise<{ blob: Blob; width: number; height: number }> {
const photo = new engine.Photo(dng, 2048);
try {
photo.render(engine.defaultSettings(), 2048, 2048, false, false);
const blob = await rgbaToJpeg(photo.pixels(), photo.width, photo.height);
return { blob, width: photo.sourceWidth, height: photo.sourceHeight };
} finally {
photo.free();
}
}
function stemOf(photo: PhotoSummary): string {
const name = photo.originalName || photo.name;
const dot = name.lastIndexOf(".");
return dot > 0 ? name.slice(0, dot) : name;
}
/**
* Merges the selection, or every detected bracket in the folder, into a linear DNG of the same collection.
* The originals stay. One stack at a time: several raws in memory at once is what made a property shoot stall.
*/
export async function mergeIntoCollection(opts: {
api: ApiClient;
orgId: string;
eventId: string | null;
photos: readonly PhotoSummary[];
selectedIds: readonly string[];
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
const stacks = stacksToMerge(opts.photos, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
const byId = new Map(opts.photos.map((photo) => [photo.id, photo]));
let engine: EngineModule;
try {
engine = await loadEngine();
} catch {
throw new MergeError("engine");
}
let made = 0;
for (let index = 0; index < stacks.length; index++) {
opts.onStatus?.(index + 1, stacks.length);
const frames = stacks[index]!.map((id) => byId.get(id)).filter((photo): photo is PhotoSummary => !!photo);
if (frames.length < 2) throw new MergeError("none");
const files: Uint8Array[] = [];
for (const frame of frames) {
const bytes = await loadFrame(frame, opts.api);
if (!bytes) throw new MergeError("missing");
files.push(bytes);
}
const job = new engine.BracketJob();
try {
for (const file of files) job.push(file);
if (!job.mergeDng) throw new MergeError("engine");
const dng = job.mergeDng(MERGE_EDGE);
const preview = await previewOf(engine, dng);
const mid = frames[Math.floor((frames.length - 1) / 2)]!;
const uploaded = await opts.api.uploadPhoto(opts.orgId, preview.blob, `${stemOf(mid)}-fundido.jpg`, {
...(opts.eventId ? { eventId: opts.eventId } : { inbox: true }),
silent: true,
});
const copy = new Uint8Array(dng.byteLength);
copy.set(dng);
await opts.api.attachLinearDng(uploaded.photo.id, new Blob([copy]), {
width: preview.width,
height: preview.height,
capturedAt: mid.capturedAt,
});
made += 1;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
} finally {
job.free();
}
}
return made;
}
+63
View File
@@ -0,0 +1,63 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { describe, expect, it } from "vitest";
import { stacksToMerge } from "./mergeStacks.js";
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
function photo(id: string, exposureTime: number, ms: number, name = `${id}.cr3`): PhotoSummary {
return {
id,
eventId: "e1",
originalName: name,
name,
sha256: id.padEnd(64, "a"),
originalStored: true,
status: "READY",
width: 4000,
height: 3000,
capturedAt: at(ms),
cameraModel: "EOS R5",
lens: null,
focalLength: 16,
aperture: 8,
exposureTime,
iso: 100,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: "", preview: "", source: "" },
};
}
describe("stacks to merge", () => {
const dark = photo("a", 1 / 500, 0);
const mid = photo("b", 1 / 125, 200);
const bright = photo("c", 1 / 30, 400);
const later = photo("d", 1 / 125, 30_000);
it("finds one angle in the folder when nothing is selected", () => {
expect(stacksToMerge([dark, mid, bright, later], [])).toEqual([["a", "b", "c"]]);
});
it("merges the selection even when it is not a detected bracket", () => {
expect(stacksToMerge([dark, later], ["a", "d"])).toEqual([["a", "d"]]);
});
it("detects the folder when only the open photo is selected", () => {
expect(stacksToMerge([dark, mid, bright], ["a"])).toEqual([["a", "b", "c"]]);
});
it("does nothing when there is no bracket and fewer than two are selected", () => {
expect(stacksToMerge([dark, later], ["a"])).toEqual([]);
});
it("does not treat a merged file as another exposure", () => {
const merged = photo("m", 1 / 125, 300, "b-fundido.dng");
const renamed = photo("n", 1 / 125, 500, "n.dng");
renamed.name = "n";
expect(stacksToMerge([dark, mid, bright, merged, renamed], [])).toEqual([["a", "b", "c"]]);
});
});
+51
View File
@@ -0,0 +1,51 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
/** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */
export const MERGE_EDGE = 4096;
function isMergedFile(photo: PhotoSummary): boolean {
const names = [photo.originalName, photo.name];
return names.some((name) => {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
});
}
export function frameOf(photo: PhotoSummary): BracketFrame {
return {
id: photo.id,
fileName: photo.originalName || photo.name,
capturedAt: photo.capturedAt,
cameraModel: photo.cameraModel,
focalLength: photo.focalLength,
aperture: photo.aperture,
iso: photo.iso,
width: photo.width,
height: photo.height,
exposureTime: photo.exposureTime,
};
}
function byCapture(a: PhotoSummary, b: PhotoSummary): number {
const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "");
if (time !== 0) return time;
return (a.originalName || a.name).localeCompare(b.originalName || b.name, undefined, { numeric: true, sensitivity: "base" });
}
/**
* Stacks to merge. A selection of two or more is that set (detected into angles when they are brackets,
* otherwise one stack in capture order). With nothing selected, every bracket in the folder is a stack.
* A DNG already produced here is not an exposure.
*/
export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] {
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
const selected = new Set(selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? ready.filter((photo) => selected.has(photo.id)) : ready;
if (pool.length < 2) return [];
const grouped = groupBrackets(pool.map(frameOf));
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byCapture).map((photo) => photo.id)];
}
+15 -2
View File
@@ -15,6 +15,7 @@ import { IptcInfo } from "../library/IptcInfo.js";
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
import { FilterBar } from "../library/FilterBar.js";
import { cache } from "../offline/cache.js";
import { MergeButton } from "../library/MergeButton.js";
import { localPhotos } from "../offline/local.js";
import { isNetworkError, offlineQueue } from "../offline/queue.js";
import { patchPhotos, useOfflineSync } from "../offline/sync.js";
@@ -219,9 +220,16 @@ export function DevelopPage() {
setPhotos((list) => list.map((p) => (ids.has(p.id) ? applyPatch(p, m.patch) : p)));
} else if (m.type === "photo.rendered") {
setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)));
} else if (m.type === "photo.added") {
const inThis = scope === "inbox" || scope === null ? m.photo.eventId === null : m.photo.eventId === scope;
if (!inThis) return;
setAll((list) => {
if (!list || list.some((p) => p.id === m.photo.id)) return list;
return [...list, m.photo].sort((a, b) => (a.capturedAt ?? "").localeCompare(b.capturedAt ?? ""));
});
}
},
[session],
[session, scope],
);
const live = useLibraryLive(api, onMessage);
// Reconnected: anything sent meanwhile is fetched in order.
@@ -566,6 +574,9 @@ export function DevelopPage() {
</span>
)}
<span className="ml-auto flex items-center gap-2">
{canCull && orgId && scope && !scope.startsWith("search:") && !scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={scope === "inbox" ? null : scope} photos={photos} selectedIds={[...selected]} />
)}
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
{t.dev.undo}
</button>
@@ -602,7 +613,9 @@ export function DevelopPage() {
crop={crop}
onSourceSize={(w, h) => setSourceSize({ w, h })}
onError={(m) => setNote(m)}
{...(oneToOne ? { localSource: fullSource } : isDesktop() && { localSource: () => localOriginalToView(current.sha256) })}
{...(oneToOne || current.originalName.toLowerCase().endsWith(".dng") || current.name.toLowerCase().endsWith(".dng")
? { localSource: fullSource }
: isDesktop() && { localSource: () => localOriginalToView(current.sha256) })}
picking={picking && !cropping && !before}
onPick={(u, v) => {
setPicking(false);
+13 -15
View File
@@ -4,17 +4,15 @@ import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { FacesQueuePage } from "./FacesQueuePage.js";
const staged = vi.hoisted(() => ({
request: vi.fn(),
}));
const staged = vi.hoisted(() => {
const request = vi.fn();
return { request, api: { request, absolute: (path: string) => path } };
});
vi.mock("../auth.js", () => ({
useAuth: () => ({
organization: { id: "org-1" },
api: {
request: staged.request,
absolute: (path: string) => path,
},
api: staged.api,
}),
}));
@@ -32,7 +30,7 @@ describe("faces queue", () => {
staged.request.mockReset();
});
it("shows that Confirmar is working, then takes the card away", async () => {
it("takes the card away as soon as Confirmar is clicked", async () => {
let release: () => void = () => undefined;
const pending = new Promise<void>((resolve) => {
release = resolve;
@@ -46,15 +44,15 @@ describe("faces queue", () => {
<FacesQueuePage />
</MemoryRouter>,
);
const button = await screen.findByRole("button", { name: "Confirmar" });
await userEvent.click(button);
expect((await screen.findByRole("button", { name: "A confirmar…" })).hasAttribute("disabled")).toBe(true);
release();
await userEvent.click(await screen.findByRole("button", { name: "Confirmar" }));
await waitFor(() => expect(screen.queryByText("Ricardo Candeias")).toBeNull());
expect(staged.request).toHaveBeenCalledWith("POST", "/v1/face-groups/g1/confirm", { personId: "p1" });
expect(screen.getByText("A confirmar…")).toBeTruthy();
expect(staged.request).toHaveBeenCalledWith("POST", "/v1/orgs/org-1/face-review/confirm", { personId: "p1", groupIds: ["g1"] });
release();
await waitFor(() => expect(screen.queryByText("A confirmar…")).toBeNull());
});
it("says so when Confirmar fails, and leaves the card", async () => {
it("says so when Confirmar fails, and puts the card back", async () => {
staged.request.mockImplementation((method: string) => {
if (method === "GET") return Promise.resolve({ groups: [ricardo] });
return Promise.reject(new Error("conflict"));
@@ -66,7 +64,7 @@ describe("faces queue", () => {
);
await userEvent.click(await screen.findByRole("button", { name: "Confirmar" }));
expect(await screen.findByText("Não confirmei. Tenta outra vez.")).toBeTruthy();
expect(screen.getByText("Ricardo Candeias")).toBeTruthy();
await waitFor(() => expect(screen.getByText("Ricardo Candeias")).toBeTruthy());
expect(screen.getByRole("button", { name: "Confirmar" }).hasAttribute("disabled")).toBe(false);
});
});
+18 -13
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Link } from "react-router";
import { useAuth } from "../auth.js";
import { FaceCrop } from "../library/FacesView.js";
@@ -31,8 +31,9 @@ export function FacesQueuePage() {
const { api, organization } = useAuth();
const orgId = organization?.id ?? "";
const [rows, setRows] = useState<Row[] | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [failed, setFailed] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [failed, setFailed] = useState(false);
const pending = useRef(false);
const [open, setOpen] = useState<Sample[] | null>(null);
const [at, setAt] = useState(0);
@@ -53,17 +54,20 @@ export function FacesQueuePage() {
const confirm = async (pile: Row[]) => {
const personId = pile[0]?.suggestion?.id;
if (!personId) return;
setBusy(personId);
setFailed(null);
if (!personId || pending.current) return;
const ids = pile.map((row) => row.id);
pending.current = true;
setBusy(true);
setFailed(false);
setRows((cur) => cur?.filter((row) => !ids.includes(row.id)) ?? null);
try {
for (const row of pile) await api.request("POST", `/v1/face-groups/${row.id}/confirm`, { personId });
setRows((cur) => cur?.filter((r) => !pile.some((p) => p.id === r.id)) ?? null);
await api.request("POST", `/v1/orgs/${orgId}/face-review/confirm`, { personId, groupIds: ids });
} catch {
setFailed(personId);
setFailed(true);
await load().catch(() => undefined);
} finally {
setBusy(null);
pending.current = false;
setBusy(false);
}
};
@@ -73,6 +77,8 @@ export function FacesQueuePage() {
<p className="px-4 pt-3 text-[13px] text-muted">
As caras por confirmar, juntas por pessoa. As camisolas ensinam-se em <Link to="/numbers" className="underline">{t.numbersNav}</Link>.
</p>
{busy && <p className="px-4 pt-2 text-[13px] text-muted">{t.faces.confirming}</p>}
{failed && !busy && <p className="px-4 pt-2 text-[13px] text-danger">{t.faces.confirmFailed}</p>}
<div className="grid min-h-0 min-w-0 flex-1 content-start gap-3 overflow-x-hidden overflow-y-auto p-4 pb-6 sm:grid-cols-2 xl:grid-cols-3">
{rows === null && <p className="text-sm text-muted">A carregar…</p>}
{rows?.length === 0 && <p className="text-sm text-muted">Nada por confirmar.</p>}
@@ -94,10 +100,9 @@ export function FacesQueuePage() {
.join(" · ")}
</p>
</div>
<button type="button" className="h-8 w-full shrink-0 border border-black bg-accent text-[12px] text-ink disabled:opacity-70" disabled={busy === who?.id || !who?.id} onClick={() => void confirm(pile)}>
{busy === who?.id ? t.faces.confirming : t.faces.confirm}
<button type="button" className="h-8 w-full shrink-0 border border-black bg-accent text-[12px] text-ink disabled:opacity-70" disabled={busy || !who?.id} onClick={() => void confirm(pile)}>
{t.faces.confirm}
</button>
{failed === who?.id && <p className="text-[11px] text-danger">{t.faces.confirmFailed}</p>}
</article>
);
})}
+6 -1
View File
@@ -18,7 +18,8 @@ import { IptcInfo } from "../library/IptcInfo.js";
import { useLibraryLive } from "../library/realtime.js";
import { useIngest } from "../library/ingest.js";
import { LocalFtpButton } from "../library/LocalFtp.js";
import { CardIngestButton } from "../library/CardIngest.js";
import { CardIngestButton, CardOverallStatus } from "../library/CardIngest.js";
import { MergeButton } from "../library/MergeButton.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js";
@@ -523,6 +524,9 @@ export function LibraryPage() {
))}
</select>
)}
{canCull && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} />
)}
{canCull && (
<SendButton
api={api}
@@ -672,6 +676,7 @@ export function LibraryPage() {
)}
</div>
)}
{desktop && <CardOverallStatus />}
<div className="border-t border-line bg-raised px-3 py-1.5 text-[11px] text-faint">{t.shortcuts}</div>
</div>
+2 -36
View File
@@ -1,9 +1,8 @@
import { DEFAULT_MODULES, MODULES, type Module } from "@photoreport/contracts";
import { ApiError } from "@photoreport/sdk";
import { useState } from "react";
import { useAuth } from "../auth.js";
import { LocalCatalog } from "../desktop/LocalCatalog.js";
import { Alert } from "../components/ui.js";
import { LocalCatalog } from "../desktop/LocalCatalog.js";
import { t } from "../i18n.js";
import { isDesktop } from "../platform.js";
import { PageHeader } from "./Shell.js";
@@ -12,12 +11,9 @@ import { PageHeader } from "./Shell.js";
const CHOOSABLE = MODULES.filter((m) => m !== "advanced");
export function PreferencesPage() {
const { api, me, reload, organization, role } = useAuth();
const { api, me, reload } = useAuth();
const [selected, setSelected] = useState<Module[]>(me?.preferences.editorModules ?? [...DEFAULT_MODULES]);
const [status, setStatus] = useState<"idle" | "saved" | "error">("idle");
const [realEstateError, setRealEstateError] = useState<string | null>(null);
const [realEstateBusy, setRealEstateBusy] = useState(false);
const realEstateOn = organization?.realEstateEnabled === true;
const toggle = async (module: Module) => {
const next = selected.includes(module) ? selected.filter((m) => m !== module) : [...selected, module];
@@ -54,37 +50,7 @@ export function PreferencesPage() {
</label>
</li>
))}
{role === "OWNER" && organization && (
<li>
<label className="flex h-11 cursor-pointer items-center gap-3 rounded-md border border-line bg-panel px-3 text-sm hover:border-faint">
<input
type="checkbox"
className="h-4 w-4 accent-[var(--color-accent)]"
checked={realEstateOn}
disabled={realEstateBusy}
onChange={() => {
setRealEstateBusy(true);
setRealEstateError(null);
void (async () => {
try {
await api.setRealEstate(organization.id, !realEstateOn);
await reload();
} catch (err) {
const code = err instanceof ApiError ? err.code : "";
setRealEstateError(t.realEstate.errors[code] ?? t.unexpectedError);
} finally {
setRealEstateBusy(false);
}
})();
}}
/>
{t.realEstate.setting}
</label>
</li>
)}
</ul>
{role === "OWNER" && organization && <p className="mt-3 text-sm text-muted">{t.realEstate.settingHelp}</p>}
{realEstateError && <Alert>{realEstateError}</Alert>}
</section>
{isDesktop() && <LocalCatalog />}
</>
-109
View File
@@ -1,109 +0,0 @@
import type { BracketFrame } from "@photoreport/metadata";
import { groupBrackets } from "@photoreport/metadata";
import type { ApiClient, Me, Organization } from "@photoreport/sdk";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { App } from "../App.js";
vi.mock("../library/realtime.js", () => ({
useLibraryLive: () => "live",
onSocketLive: () => () => undefined,
}));
vi.mock("../realestate/fuse.js", () => ({
fuseBracket: () => Promise.resolve(new Blob([Uint8Array.from([0xff, 0xd8])], { type: "image/jpeg" })),
}));
const staged = vi.hoisted(() => ({ frames: new Map<string, BracketFrame>() }));
vi.mock("../realestate/readFrame.js", async () => {
const actual = await vi.importActual<typeof import("../realestate/readFrame.js")>("../realestate/readFrame.js");
return {
...actual,
readBracketFile: (file: File) => Promise.resolve(staged.frames.get(file.name) ?? { id: file.name, fileName: file.name }),
};
});
const org = (realEstateEnabled: boolean): Organization => ({ id: "o1", slug: "fpa", name: "FPA", mode: "AGENCY", realEstateEnabled });
function me(role: Me["memberships"][number]["role"], realEstateEnabled: boolean): Me {
return {
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
memberships: [{ role, organization: org(realEstateEnabled) }],
preferences: { editorModules: ["crop", "basic"] },
};
}
function fakeApi(who: Me, overrides: Partial<Record<keyof ApiClient, unknown>> = {}): ApiClient {
return {
client: "web",
resume: vi.fn().mockResolvedValue(true),
me: vi.fn().mockResolvedValue(who),
listEvents: vi.fn().mockResolvedValue({ events: [], inboxCount: 0 }),
listPhotos: vi.fn().mockResolvedValue({ photos: [], total: 0 }),
absolute: (path: string) => path,
groupRealEstate: vi.fn(async (_orgId: string, frames: BracketFrame[]) => groupBrackets(frames)),
setRealEstate: vi.fn().mockResolvedValue({ enabled: true }),
...overrides,
} as unknown as ApiClient;
}
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
function shot(name: string, bias: number, ms: number): BracketFrame {
return {
id: name,
fileName: name,
capturedAt: at(ms),
cameraSerial: "body",
focalLength: 16,
aperture: 8,
iso: 100,
exposureBias: bias,
exposureTime: 0.01,
};
}
describe("real estate area", () => {
beforeEach(() => {
URL.createObjectURL = () => "blob:fused";
URL.revokeObjectURL = () => undefined;
});
afterEach(() => {
staged.frames.clear();
window.history.pushState({}, "", "/");
});
it("stays out of the menu until the organization turns it on", async () => {
render(<App api={fakeApi(me("PHOTOGRAPHER", false))} />);
expect(await screen.findByText(/Ainda não chegaram fotografias/)).toBeTruthy();
expect(screen.queryByRole("link", { name: "Imobiliário" })).toBeNull();
});
it("groups a dropped bracket and leaves the loose frame out", async () => {
staged.frames.set("a.cr3", shot("a.cr3", -2, 0));
staged.frames.set("b.cr3", shot("b.cr3", 0, 200));
staged.frames.set("c.cr3", shot("c.cr3", 2, 400));
staged.frames.set("solo.cr3", shot("solo.cr3", 0, 30_000));
const api = fakeApi(me("PHOTOGRAPHER", true));
render(<App api={api} />);
await userEvent.click(await screen.findByRole("link", { name: "Imobiliário" }));
const input = screen.getByLabelText("Escolher ficheiros");
await userEvent.upload(input, [new File(["a"], "a.cr3"), new File(["b"], "b.cr3"), new File(["c"], "c.cr3"), new File(["s"], "solo.cr3")]);
expect(await screen.findByText("1 ângulo")).toBeTruthy();
expect(screen.getByText("Ângulo 1 · 3 exposições")).toBeTruthy();
expect(await screen.findByRole("img", { name: "Ângulo 1 fundido" })).toBeTruthy();
expect(screen.getByText("1 fotografia fica de fora")).toBeTruthy();
expect(screen.getByText("solo.cr3 · 0 EV")).toBeTruthy();
expect(api.groupRealEstate).toHaveBeenCalledOnce();
});
it("lets the owner show the area from preferences", async () => {
window.history.pushState({}, "", "/preferences");
const api = fakeApi(me("OWNER", false));
render(<App api={api} />);
await userEvent.click(await screen.findByRole("checkbox", { name: "Imobiliário" }));
expect(api.setRealEstate).toHaveBeenCalledWith("o1", true);
});
});
-274
View File
@@ -1,274 +0,0 @@
import type { BracketFrame } from "@photoreport/metadata";
import { ApiError, hasRole, type RealEstateGrouping } from "@photoreport/sdk";
import { useEffect, useRef, useState } from "react";
import { useAuth } from "../auth.js";
import { t } from "../i18n.js";
import { fuseBracket } from "../realestate/fuse.js";
import { fillFromSidecar, pairKey, partitionBracketFiles, readBracketFile } from "../realestate/readFrame.js";
import { PageHeader } from "./Shell.js";
const READ_AT_ONCE = 4;
/**
* Interior brackets, separate from the sports library. The files stay on this computer. The server
* only receives exposure metadata and says which frames belong to the same angle; the develop
* engine merges each angle in the browser.
*/
export function RealEstatePage() {
const { api, organization, role } = useAuth();
const enabled = organization?.realEstateEnabled === true && role !== null && hasRole(role, "PHOTOGRAPHER");
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
const [error, setError] = useState<string | null>(null);
const [frames, setFrames] = useState<BracketFrame[]>([]);
const [files, setFiles] = useState<Map<string, File>>(new Map());
const [result, setResult] = useState<RealEstateGrouping | null>(null);
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
const [support, setSupport] = useState(0);
const take = async (list: File[]) => {
const split = partitionBracketFiles(list);
if ((split.images.length === 0 && split.sidecars.length === 0 && split.other === 0) || busyRef.current || !organization) return;
busyRef.current = true;
setBusy(true);
setError(null);
setResult(null);
setFrames([]);
setFiles(new Map());
setSupport(split.sidecars.length + split.other);
setProgress({ done: 0, total: split.images.length + split.sidecars.length });
try {
if (split.images.length === 0) {
setError(t.realEstate.noPhotos);
return;
}
let done = 0;
const total = split.images.length + split.sidecars.length;
const readOne = async (file: File) => {
try {
return await readBracketFile(file);
} finally {
done += 1;
setProgress({ done, total });
}
};
const read = await mapPool(split.images, READ_AT_ONCE, readOne);
const sidecars = await mapPool(split.sidecars, READ_AT_ONCE, readOne);
const byKey = new Map(split.sidecars.map((file, index) => [pairKey(file.webkitRelativePath || file.name), sidecars[index]!]));
const merged = read.map((frame, index) => {
const image = split.images[index];
const extra = image ? byKey.get(pairKey(image.webkitRelativePath || image.name)) : undefined;
return extra ? fillFromSidecar(frame, extra) : frame;
});
setFrames(merged);
const paired = new Map<string, File>();
merged.forEach((frame, index) => {
const file = split.images[index];
if (file) paired.set(frame.id, file);
});
setFiles(paired);
setResult(await api.groupRealEstate(organization.id, merged));
} catch (err) {
const code = err instanceof ApiError ? err.code : "";
setError(t.realEstate.errors[code] ?? t.unexpectedError);
} finally {
busyRef.current = false;
setBusy(false);
setProgress(null);
}
};
return (
<>
<PageHeader title={t.realEstate.title} />
<section className="max-w-3xl p-6">
{!enabled ? (
<p className="text-sm text-muted">{t.realEstate.disabled}</p>
) : (
<>
<p className="text-sm text-muted">{t.realEstate.intro}</p>
<p className="mt-2 text-sm text-muted">{t.realEstate.step}</p>
<div
className="mt-5 border border-dashed border-line bg-panel px-4 py-8 text-center"
onDragOver={(event) => event.preventDefault()}
onDrop={(event) => {
event.preventDefault();
void filesFromDrop(event.dataTransfer).then((files) => take(files));
}}
>
<div className="flex flex-wrap items-center justify-center gap-3">
<label className="inline-flex h-9 cursor-pointer items-center bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong">
{t.realEstate.choose}
<input
aria-label={t.realEstate.choose}
className="sr-only"
type="file"
multiple
disabled={busy}
onChange={(event) => {
const list = event.target.files ? [...event.target.files] : [];
event.target.value = "";
void take(list);
}}
/>
</label>
<label className="inline-flex h-9 cursor-pointer items-center border border-line bg-panel px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-ink hover:border-faint">
{t.realEstate.chooseFolder}
<input
aria-label={t.realEstate.chooseFolder}
className="sr-only"
type="file"
multiple
disabled={busy}
{...{ webkitdirectory: "", directory: "" }}
onChange={(event) => {
const list = event.target.files ? [...event.target.files] : [];
event.target.value = "";
void take(list);
}}
/>
</label>
</div>
<p className="mt-3 text-[13px] text-faint">{t.realEstate.dropHint}</p>
</div>
{busy && progress && <p className="mt-4 text-sm text-muted">{t.realEstate.reading(progress.done, progress.total)}</p>}
{error && <p className="mt-4 text-sm text-danger">{error}</p>}
{support > 0 && <p className="mt-4 text-sm text-muted">{t.realEstate.support(support)}</p>}
{result && <Grouping frames={frames} files={files} result={result} />}
</>
)}
</section>
</>
);
}
function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Map<string, File>; result: RealEstateGrouping }) {
const byId = new Map(frames.map((frame) => [frame.id, frame]));
return (
<div className="mt-6 space-y-4">
<p className="text-sm text-ink">{t.realEstate.stacks(result.stacks.length)}</p>
{result.stacks.length === 0 && <p className="text-sm text-muted">{t.realEstate.none}</p>}
<ul className="space-y-3">
{result.stacks.map((stack, index) => (
<li key={`${index}-${stack.frameIds[0] ?? ""}`} className="border border-line bg-panel">
<p className="border-b border-line px-3 py-2 text-[13px] font-semibold">{t.realEstate.angle(index + 1, stack.frameIds.length)}</p>
<AnglePreview index={index} ids={stack.frameIds} files={files} />
<ul className="px-3 py-2 text-[13px] text-muted">
{stack.frameIds.map((id) => (
<li key={id}>{line(byId.get(id), id)}</li>
))}
</ul>
</li>
))}
</ul>
{result.aside.length > 0 && (
<div>
<p className="text-sm text-ink">{t.realEstate.aside(result.aside.length)}</p>
<p className="mt-1 text-[13px] text-faint">{t.realEstate.asideHelp}</p>
<ul className="mt-2 text-[13px] text-muted">
{result.aside.slice(0, 12).map((id) => (
<li key={id}>{line(byId.get(id), id)}</li>
))}
{result.aside.length > 12 && <li>{t.realEstate.asideMore(result.aside.length - 12)}</li>}
</ul>
</div>
)}
</div>
);
}
function AnglePreview({ index, ids, files }: { index: number; ids: string[]; files: Map<string, File> }) {
const [url, setUrl] = useState<string | null>(null);
const [failed, setFailed] = useState(false);
const key = ids.join("\n");
useEffect(() => {
const stack = ids.map((id) => files.get(id)).filter((file): file is File => file instanceof File);
if (stack.length < 2) {
setFailed(true);
return;
}
let cancelled = false;
let objectUrl = "";
setUrl(null);
setFailed(false);
fuseBracket(stack)
.then((blob) => {
if (cancelled) return;
objectUrl = URL.createObjectURL(blob);
setUrl(objectUrl);
})
.catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
// `key` is the stack. `files` is replaced as a whole when a new folder is read.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, files]);
if (failed) return <p className="px-3 py-2 text-[13px] text-danger">{t.realEstate.fuseFailed}</p>;
if (!url) return <p className="px-3 py-2 text-[13px] text-muted">{t.realEstate.fusing}</p>;
return <img alt={t.realEstate.previewAlt(index + 1)} className="block w-full" src={url} />;
}
function line(frame: BracketFrame | undefined, id: string): string {
const name = frame?.fileName || id;
return `${name} · ${exposureLabel(frame)}`;
}
function exposureLabel(frame: BracketFrame | undefined): string {
if (!frame || (frame.exposureBias == null && (frame.exposureTime == null || frame.exposureTime <= 0))) return t.realEstate.noExposure;
if (frame.exposureBias == null) return t.realEstate.noBias;
return formatBias(frame.exposureBias);
}
function formatBias(value: number): string {
const rounded = Math.round(value * 10) / 10;
const text = Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
if (rounded > 0) return t.realEstate.bias(`+${text}`);
return t.realEstate.bias(text);
}
async function mapPool<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length);
let next = 0;
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (next < items.length) {
const index = next;
next += 1;
out[index] = await fn(items[index]!);
}
});
await Promise.all(workers);
return out;
}
async function filesFromDrop(data: DataTransfer): Promise<File[]> {
const entries: FileSystemEntry[] = [];
for (const item of data.items) {
const entry = item.webkitGetAsEntry?.();
if (entry) entries.push(entry);
}
if (entries.length === 0) return [...data.files];
const nested = await Promise.all(entries.map((entry) => filesInEntry(entry)));
return nested.flat();
}
async function filesInEntry(entry: FileSystemEntry): Promise<File[]> {
if (entry.name.startsWith(".")) return [];
if (entry.isFile) {
const file = await new Promise<File>((resolve, reject) => (entry as FileSystemFileEntry).file(resolve, reject));
return file.name.startsWith(".") ? [] : [file];
}
if (!entry.isDirectory) return [];
const reader = (entry as FileSystemDirectoryEntry).createReader();
const children: FileSystemEntry[] = [];
for (;;) {
const batch = await new Promise<FileSystemEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));
if (batch.length === 0) break;
children.push(...batch);
}
const nested = await Promise.all(children.map((child) => filesInEntry(child)));
return nested.flat();
}
-10
View File
@@ -111,16 +111,6 @@ export function Shell() {
</NavLink>
</>
)}
{organization?.realEstateEnabled === true && role !== null && hasRole(role, "PHOTOGRAPHER") && (
<>
<span aria-hidden="true" className="text-[#3a3a3a]">
|
</span>
<NavLink to="/real-estate" className={moduleClass}>
{t.realEstate.nav}
</NavLink>
</>
)}
</nav>
<Bell />
+31
View File
@@ -0,0 +1,31 @@
import { loadEngine } from "../develop/engine.js";
import { finishValues, needsFinish, type LookId } from "./looks.js";
/** The fused JPEG, then one develop pass when a finish or a slider asks for it. */
export async function applyFinish(jpeg: Blob, look: LookId, tweaks: Record<string, number>): Promise<Blob> {
const values = finishValues(look, tweaks);
if (!needsFinish(values)) return jpeg;
const engine = await loadEngine();
const photo = new engine.Photo(new Uint8Array(await jpeg.arrayBuffer()), 2048);
try {
const settings = engine.apply(engine.defaultSettings(), JSON.stringify({ command: "develop.set", params: { values } }));
photo.render(settings, photo.sourceWidth, photo.sourceHeight, false, false);
return rgbaToJpeg(photo.pixels(), photo.width, photo.height);
} finally {
photo.free();
}
}
function rgbaToJpeg(rgba: Uint8Array, width: number, height: number): Promise<Blob> {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
if (!context || width <= 0 || height <= 0) return Promise.reject(new Error("canvas"));
const pixels = new Uint8ClampedArray(rgba.byteLength);
pixels.set(rgba);
context.putImageData(new ImageData(pixels, width, height), 0, 0);
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("jpeg"))), "image/jpeg", 0.92);
});
}
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { inOrder } from "./fuse.js";
describe("bracket queue", () => {
it("reads the next angle only after the current one finishes", async () => {
const run = inOrder();
const order: string[] = [];
let release: () => void = () => undefined;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const first = run(async () => {
order.push("start-1");
await gate;
order.push("end-1");
});
const second = run(async () => {
order.push("start-2");
});
await Promise.resolve();
expect(order).toEqual(["start-1"]);
release();
await first;
await second;
expect(order).toEqual(["start-1", "end-1", "start-2"]);
});
});
+47 -14
View File
@@ -3,25 +3,58 @@ import { loadEngine } from "../develop/engine.js";
/** Long side of each frame. The engine bins a raw mosaic down to this instead of demosaicing it whole. */
const PREVIEW_EDGE = 1024;
export type FusePhase = "queued" | "reading" | "merging";
/** Runs jobs one after another. A rejected job does not stop the next. */
export function inOrder(): <T>(job: () => Promise<T>) => Promise<T> {
let chain: Promise<unknown> = Promise.resolve();
return (job) => {
const run = chain.then(job, job);
chain = run.then(
() => undefined,
() => undefined,
);
return run;
};
}
const enqueue = inOrder();
function paint(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
/**
* Merge one angle with the develop engine (LightCraft's HDR merge) and return a JPEG preview.
* Angles run one at a time: reading every raw of a property at once filled memory and the first one never finished.
* The files stay in this browser; nothing is uploaded.
*/
export async function fuseBracket(files: File[]): Promise<Blob> {
const engine = await loadEngine();
const job = new engine.BracketJob();
try {
for (const file of files) {
job.push(new Uint8Array(await file.arrayBuffer()));
}
const merged = job.merge(PREVIEW_EDGE);
export function fuseBracket(files: File[], onPhase?: (phase: FusePhase) => void, isCancelled?: () => boolean): Promise<Blob> {
onPhase?.("queued");
return enqueue(async () => {
if (isCancelled?.()) throw new Error("cancelled");
onPhase?.("reading");
await paint();
if (isCancelled?.()) throw new Error("cancelled");
const engine = await loadEngine();
const job = new engine.BracketJob();
try {
const jpeg = new Uint8Array(merged.jpeg());
return new Blob([jpeg], { type: "image/jpeg" });
for (const file of files) {
if (isCancelled?.()) throw new Error("cancelled");
job.push(new Uint8Array(await file.arrayBuffer()));
}
onPhase?.("merging");
await paint();
if (isCancelled?.()) throw new Error("cancelled");
const merged = job.merge(PREVIEW_EDGE);
try {
const jpeg = new Uint8Array(merged.jpeg());
return new Blob([jpeg], { type: "image/jpeg" });
} finally {
merged.free();
}
} finally {
merged.free();
job.free();
}
} finally {
job.free();
}
});
}
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { finishValues, needsFinish } from "./looks.js";
describe("real estate finishes", () => {
it("keeps the merge when nothing was chosen", () => {
expect(needsFinish(finishValues("natural", {}))).toBe(false);
});
it("lets a slider replace one control of a preset", () => {
const values = finishValues("interior", { "light.shadows": 10 });
expect(values["light.shadows"]).toBe(10);
expect(values["light.highlights"]).toBe(-40);
expect(needsFinish(values)).toBe(true);
});
});
+20
View File
@@ -0,0 +1,20 @@
/** Finishes on top of the fused JPEG. Empty values keep the merge as the engine made it. */
export const LOOKS = [
{ id: "natural", values: {} },
{ id: "interior", values: { "light.exposure": 0.35, "light.highlights": -40, "light.shadows": 45, "light.whites": -15 } },
{ id: "brighter", values: { "light.exposure": 0.65, "light.highlights": -25, "light.shadows": 30 } },
] as const;
export type LookId = (typeof LOOKS)[number]["id"];
/** Preset first. A slider that moved replaces that one control. */
export function finishValues(look: LookId, tweaks: Record<string, number>): Record<string, number> {
const preset = LOOKS.find((item) => item.id === look)?.values ?? {};
const values: Record<string, number> = { ...preset };
for (const [id, value] of Object.entries(tweaks)) values[id] = value;
return values;
}
export function needsFinish(values: Record<string, number>): boolean {
return Object.values(values).some((value) => value !== 0);
}
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from "vitest";
import { jpegName } from "./save.js";
describe("fused file names", () => {
it("names the jpeg from the raw", () => {
expect(jpegName("PSR10099.CR3")).toBe("PSR10099-fundido.jpg");
expect(jpegName("sala 1.cr3")).toBe("sala-1-fundido.jpg");
expect(jpegName("")).toBe("angulo-fundido.jpg");
});
});
+54
View File
@@ -0,0 +1,54 @@
/** A download name for one fused angle. */
export function jpegName(fileName: string): string {
const stem = fileName.replace(/\.[^.]+$/, "").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "");
return `${stem || "angulo"}-fundido.jpg`;
}
export function downloadBlob(name: string, blob: Blob): void {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
URL.revokeObjectURL(url);
}
interface Writable {
write(data: Blob): Promise<void>;
close(): Promise<void>;
}
interface DirectoryPicker {
showDirectoryPicker?: () => Promise<{
getFileHandle(name: string, opts: { create: boolean }): Promise<{ createWritable(): Promise<Writable> }>;
}>;
}
/** All the angles into one folder when the browser allows it, otherwise one download each. */
export async function saveBlobs(
files: readonly { name: string; blob: Blob }[],
onStep?: (done: number, total: number) => void,
): Promise<"folder" | "download" | "cancel"> {
const picker = (window as DirectoryPicker).showDirectoryPicker;
if (!picker) {
for (const file of files) downloadBlob(file.name, file.blob);
onStep?.(files.length, files.length);
return "download";
}
try {
const dir = await picker();
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
if (!file) continue;
const handle = await dir.getFileHandle(file.name, { create: true });
const writable = await handle.createWritable();
await writable.write(file.blob);
await writable.close();
onStep?.(index + 1, files.length);
}
return "folder";
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") return "cancel";
throw err;
}
}
+273 -64
View File
@@ -274,6 +274,9 @@ fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
}
}
/// Leave this much free on the destination. A copy that would end closer than this does not start the next day.
const DISK_HEADROOM: u64 = 1024 * 1024 * 1024;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardScan {
@@ -281,11 +284,17 @@ pub struct CardScan {
pub jpeg: usize,
pub other: usize,
pub bytes: u64,
/// Free space on the destination volume. Absent when it could not be read, or no destination was given.
#[serde(skip_serializing_if = "Option::is_none")]
pub free_bytes: Option<u64>,
/// Whether the photos (and sidecars) fit in that free space, with a gigabyte left over.
#[serde(skip_serializing_if = "Option::is_none")]
pub fits: Option<bool>,
}
/// Looks at a card/folder: how many RAW, JPEG and other photos, and the total size. No files are touched.
#[tauri::command]
pub async fn card_scan(source: String) -> Result<CardScan, String> {
pub async fn card_scan(source: String, settings: Option<CardSettings>) -> Result<CardScan, String> {
tauri::async_runtime::spawn_blocking(move || {
let root = expand(&source);
if !root.is_dir() {
@@ -293,13 +302,18 @@ pub async fn card_scan(source: String) -> Result<CardScan, String> {
}
let mut files = Vec::new();
collect(&root, &mut files);
let (mut raw, mut jpeg, mut other, mut bytes) = (0usize, 0usize, 0usize, 0u64);
let mode = settings.as_ref().map(|s| s.raw_jpeg).unwrap_or(RawJpeg::Both);
let with_sidecars = settings.as_ref().map(|s| s.sidecars).unwrap_or(false);
let (mut raw, mut jpeg, mut other, mut bytes, mut sidecar_bytes) = (0usize, 0usize, 0usize, 0u64, 0u64);
for f in &files {
let ext = ext_of(f);
if !is_image(&ext) {
if !wanted(&ext, mode) {
continue;
}
bytes += std::fs::metadata(f).map(|m| m.len()).unwrap_or(0);
if with_sidecars {
sidecar_bytes += sidecar_bytes_of(f);
}
if is_raw(&ext) {
raw += 1;
} else if is_jpeg(&ext) {
@@ -308,7 +322,16 @@ pub async fn card_scan(source: String) -> Result<CardScan, String> {
other += 1;
}
}
Ok(CardScan { raw, jpeg, other, bytes })
let (free_bytes, fits) = match settings.as_ref() {
Some(settings) => {
let free = volume_free(&expand(&settings.destination));
let needed = bytes.saturating_add(sidecar_bytes);
let fits = free.map(|free| needed.saturating_add(DISK_HEADROOM) <= free);
(free, fits)
}
None => (None, None),
};
Ok(CardScan { raw, jpeg, other, bytes, free_bytes, fits })
})
.await
.map_err(|e| e.to_string())?
@@ -326,6 +349,9 @@ pub struct CardResult {
pub destination: String,
/// The photographer asked to stop. Files already verified stay; the rest were not touched.
pub stopped: bool,
/// Capture days that were not started, because the next one would not fit.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub held: Vec<String>,
}
#[derive(Serialize, Clone)]
@@ -399,9 +425,144 @@ fn report(app: Option<&AppHandle>, progress: &Progress) {
}
}
/// Bytes still free for a normal user on the volume that holds `path` (the nearest existing parent).
#[cfg(unix)]
fn volume_free(path: &Path) -> Option<u64> {
let mut cursor = if path.as_os_str().is_empty() { PathBuf::from(".") } else { path.to_path_buf() };
loop {
if cursor.exists() {
break;
}
if !cursor.pop() {
return None;
}
}
let Ok(c) = std::ffi::CString::new(cursor.to_string_lossy().as_bytes()) else {
return None;
};
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c.as_ptr(), &mut stat) } != 0 {
return None;
}
Some((stat.f_bavail as u64).saturating_mul(stat.f_frsize as u64))
}
#[cfg(not(unix))]
fn volume_free(_path: &Path) -> Option<u64> {
None
}
fn day_key(when: &chrono::DateTime<Local>) -> String {
format!("{:04}-{:02}-{:02}", when.year(), when.month(), when.day())
}
fn sidecar_bytes_of(src: &Path) -> u64 {
let Some(stem) = src.file_stem().and_then(|s| s.to_str()) else {
return 0;
};
let Some(parent) = src.parent() else {
return 0;
};
let mut n = 0u64;
for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{ext}"));
if side.is_file() {
n += std::fs::metadata(&side).map(|m| m.len()).unwrap_or(0);
}
}
n
}
struct Planned {
src: PathBuf,
dir: PathBuf,
name: String,
/// Size on the card. The progress bar counts this, including a file that is skipped.
photo_len: u64,
/// Bytes this photo and its sidecars will write. Zero when the destination already has them.
write_len: u64,
}
struct DayPlan {
key: String,
items: Vec<Planned>,
write_len: u64,
}
fn plan_days(photos: &[PathBuf], settings: &CardSettings) -> Vec<DayPlan> {
let base = expand(&settings.destination);
let mut rows: Vec<(String, Planned)> = Vec::with_capacity(photos.len());
for src in photos {
let ext = ext_of(src);
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let when = capture_day(src, &ext);
let key = day_key(&when);
let folder = render_folder(&settings.folder_template, &when, &ext);
let dir = base.join(folder.trim_start_matches('/'));
let photo_len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
let target = dir.join(&name);
let photo_write = if target.exists() && !settings.overwrite { 0 } else { photo_len };
let mut write_len = photo_write;
if settings.sidecars {
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{ext}"));
if !side.is_file() {
continue;
}
let side_target = dir.join(format!("{stem}.{ext}"));
if side_target.exists() && !settings.overwrite {
continue;
}
write_len += std::fs::metadata(&side).map(|m| m.len()).unwrap_or(0);
}
}
}
rows.push((key, Planned { src: src.clone(), dir, name, photo_len, write_len }));
}
rows.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.src.cmp(&b.1.src)));
let mut days: Vec<DayPlan> = Vec::new();
for (key, item) in rows {
if days.last().map(|day| day.key.as_str()) != Some(key.as_str()) {
days.push(DayPlan { key, items: Vec::new(), write_len: 0 });
}
let day = days.last_mut().unwrap();
day.write_len += item.write_len;
day.items.push(item);
}
days
}
/// `room` is space left for this copy, already after the headroom. None: the volume could not be read, so
/// every day is copied. The first day that does not fit, and every day after it, stays on the card.
fn days_that_fit(days: Vec<DayPlan>, room: Option<u64>) -> (Vec<DayPlan>, Vec<String>) {
let Some(mut room) = room else {
return (days, Vec::new());
};
let mut take = Vec::new();
let mut held = Vec::new();
let mut stop = false;
for day in days {
if stop || day.write_len > room {
stop = true;
held.push(day.key);
continue;
}
room -= day.write_len;
take.push(day);
}
(take, held)
}
fn room_for(settings: &CardSettings) -> Option<u64> {
volume_free(&expand(&settings.destination)).map(|free| free.saturating_sub(DISK_HEADROOM))
}
/// One card, one stream. A memory card has a single reader: several threads on it seek back and forth and
/// usually finish later, not sooner. A second card is a second call, so the two readers work at once.
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool) -> Result<CardResult, String> {
/// `room` limits how much may be written. Days are copied whole, oldest first; a day that does not fit is
/// not started, and neither is any day after it. A move deletes a day's sources only once that day is complete.
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool, room: Option<u64>) -> Result<CardResult, String> {
if !root.is_dir() {
return Err("not_a_folder".to_string());
}
@@ -409,8 +570,9 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
let mut files = Vec::new();
collect(root, &mut files);
let photos: Vec<PathBuf> = files.into_iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).collect();
let total = photos.len();
let bytes_total: u64 = photos.iter().map(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)).sum();
let (days, held) = days_that_fit(plan_days(&photos, settings), room);
let total: usize = days.iter().map(|day| day.items.len()).sum();
let bytes_total: u64 = days.iter().map(|day| day.items.iter().map(|item| item.photo_len).sum::<u64>()).sum();
let mut bytes_done = 0u64;
let mut r = CardResult {
copied: 0,
@@ -420,72 +582,86 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
notes: Vec::new(),
destination: base.to_string_lossy().to_string(),
stopped: false,
held: held.clone(),
};
for (i, src) in photos.iter().enumerate() {
if let Some(day) = held.first() {
note(&mut r.notes, &format!("O dia {day} não cabe. Fica no cartão, tal como os dias a seguir."));
}
let mut index = 0usize;
for day in &days {
if cancel.load(Ordering::Relaxed) {
r.stopped = true;
break;
}
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
report(app, &Progress { done: i + 1, total, name: name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total });
let ext = ext_of(src);
let folder = render_folder(&settings.folder_template, &capture_day(src, &ext), &ext);
let dir = base.join(folder.trim_start_matches('/'));
if let Err(e) = std::fs::create_dir_all(&dir) {
r.failed += 1;
bytes_done += len;
note(&mut r.notes, &format!("{name}: pasta — {e}"));
continue;
}
// The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then.
let target = dir.join(&name);
if target.exists() && !settings.overwrite {
r.skipped += 1;
bytes_done += len;
continue;
}
if let Err(e) = copy_verified(src, &target) {
r.failed += 1;
bytes_done += len;
note(&mut r.notes, &format!("{name}: {e}"));
continue;
}
// Its sidecars (same stem): best effort — a sidecar that fails is noted but does not fail the photo.
let mut sidecars_done: Vec<PathBuf> = Vec::new();
if settings.sidecars {
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
for s in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{s}"));
if !side.exists() {
continue;
}
let side_target = dir.join(format!("{stem}.{s}"));
if side_target.exists() && !settings.overwrite {
continue;
}
match copy_verified(&side, &side_target) {
Ok(()) => sidecars_done.push(side),
Err(e) => note(&mut r.notes, &format!("{stem}.{s}: {e}")),
let mut remove_after: Vec<PathBuf> = Vec::new();
let mut day_complete = true;
let mut wrote = 0usize;
for item in &day.items {
if cancel.load(Ordering::Relaxed) {
r.stopped = true;
day_complete = false;
break;
}
index += 1;
report(app, &Progress { done: index, total, name: item.name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total });
if let Err(e) = std::fs::create_dir_all(&item.dir) {
r.failed += 1;
bytes_done += item.photo_len;
day_complete = false;
note(&mut r.notes, &format!("{}: pasta — {e}", item.name));
continue;
}
// The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then.
let target = item.dir.join(&item.name);
if target.exists() && !settings.overwrite {
r.skipped += 1;
bytes_done += item.photo_len;
continue;
}
if let Err(e) = copy_verified(&item.src, &target) {
r.failed += 1;
bytes_done += item.photo_len;
day_complete = false;
note(&mut r.notes, &format!("{}: {e}", item.name));
continue;
}
// Sidecars (same stem): best effort. A sidecar that fails is noted but does not fail the photo.
let mut sidecars_done: Vec<PathBuf> = Vec::new();
if settings.sidecars {
if let (Some(stem), Some(parent)) = (item.src.file_stem().and_then(|s| s.to_str()), item.src.parent()) {
for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{ext}"));
if !side.exists() {
continue;
}
let side_target = item.dir.join(format!("{stem}.{ext}"));
if side_target.exists() && !settings.overwrite {
continue;
}
match copy_verified(&side, &side_target) {
Ok(()) => sidecars_done.push(side),
Err(e) => note(&mut r.notes, &format!("{stem}.{ext}: {e}")),
}
}
}
}
remove_after.push(item.src.clone());
remove_after.extend(sidecars_done);
wrote += 1;
bytes_done += item.photo_len;
}
// Move: the copy is verified, so the originals can go. Only what arrived whole is deleted.
if settings.mv {
let _ = std::fs::remove_file(src);
for side in &sidecars_done {
let _ = std::fs::remove_file(side);
// Move deletes the day's sources only when the whole day arrived. A partial day stays on the card.
if settings.mv && day_complete && !r.stopped {
for path in &remove_after {
let _ = std::fs::remove_file(path);
}
r.moved += 1;
r.moved += wrote;
} else {
r.copied += 1;
r.copied += wrote;
}
if r.stopped {
break;
}
bytes_done += len;
}
let finished = r.copied + r.moved + r.skipped + r.failed;
report(
@@ -505,7 +681,8 @@ pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings,
let end_id = job_id.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
let root = expand(&source);
ingest_dir(Some(&app), &root, &settings, &job_id, &cancel)
let room = room_for(&settings);
ingest_dir(Some(&app), &root, &settings, &job_id, &cancel, room)
})
.await
.map_err(|e| e.to_string());
@@ -550,15 +727,47 @@ mod tests {
..CardSettings::default()
};
let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true)).unwrap();
let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true), None).unwrap();
assert!(stopped.stopped);
assert_eq!(stopped.copied, 0);
assert!(!dst.join("a.jpg").exists());
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false)).unwrap();
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false), None).unwrap();
assert!(!done.stopped);
assert_eq!(done.copied, 2);
assert_eq!(std::fs::read(dst.join("a.jpg")).unwrap(), b"hello card");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_day_that_does_not_fit_stays_on_the_card_and_the_one_before_is_moved() {
let dir = std::env::temp_dir().join(format!("pr-card-days-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
let dst = dir.join("dst");
std::fs::create_dir_all(&src).unwrap();
let old = src.join("old.jpg");
let new = src.join("new.jpg");
std::fs::write(&old, b"day-one").unwrap();
std::fs::write(&new, b"day-two-is-bigger").unwrap();
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(5 * 24 * 3600);
std::fs::OpenOptions::new().write(true).open(&old).unwrap().set_modified(past).unwrap();
let settings = CardSettings {
destination: dst.to_string_lossy().to_string(),
folder_template: String::new(),
mv: true,
sidecars: false,
..CardSettings::default()
};
let room = std::fs::metadata(&old).unwrap().len();
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false), Some(room)).unwrap();
assert_eq!(done.moved, 1);
assert_eq!(done.held.len(), 1);
assert!(dst.join("old.jpg").exists());
assert!(!dst.join("new.jpg").exists());
assert!(!old.exists());
assert!(new.exists());
assert!(!done.notes.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
}
+42 -43
View File
@@ -1,7 +1,8 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api";
import { eventLayout } from "./events";
import { Icon, Loading, PersonFace } from "./parts";
export type Tab = "galleries" | "people" | "teams" | "review";
@@ -60,6 +61,11 @@ export function Browse({
const [filtersOpen, setFiltersOpen] = useState(false);
/** A tournament's day or group opened from its tile. */
const [openGroup, setOpenGroup] = useState<string | null>(null);
const openPanel = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!openGroup) return;
openPanel.current?.scrollIntoView({ block: "nearest" });
}, [openGroup]);
/** "Juntar nomes": the clubs ticked to count as one (null: not joining). */
const [joining, setJoining] = useState<string[] | null>(null);
const [joinInto, setJoinInto] = useState("");
@@ -281,59 +287,52 @@ export function Browse({
</button>
);
/** A tournament's galleries by day or group (the folder above them): one tile each, opened in place. */
/** A tournament's galleries by day or group (the folder above them): one tile each, opened under that tile. */
const events = (items: GalleryCard[]) => {
const groups = new Map<string, GalleryCard[]>();
const loose: GalleryCard[] = [];
for (const g of items) {
if (!g.group) loose.push(g);
else groups.set(g.group, [...(groups.get(g.group) ?? []), g]);
}
for (const [name, gs] of groups)
if (gs.length < 2) {
loose.push(...gs);
groups.delete(name);
}
const open = openGroup ? groups.get(openGroup) : undefined;
const { groups, loose } = eventLayout(items);
return (
<>
{(groups.size > 0 || loose.length > 0) && (
{(groups.length > 0 || loose.length > 0) && (
<div className="arq-cards">
{[...groups].map(([name, gs]) => {
const cover = gs.find((g) => g.cover)?.cover;
const dates = gs.map((g) => g.startsAt).filter((d): d is string => !!d).sort();
{groups.map((group) => {
const cover = group.galleries.find((g) => g.cover)?.cover;
const dates = group.galleries.map((g) => g.startsAt).filter((d): d is string => !!d).sort();
const expanded = openGroup === group.name;
const photos = group.galleries.reduce((n, g) => n + g.photoCount, 0);
return (
<button key={name} type="button" className="arq-card arq-groupcard" aria-expanded={openGroup === name} onClick={() => setOpenGroup(openGroup === name ? null : name)}>
<span className="arq-date">{dates[0] ? shortDay.format(new Date(dates[0])) : "Sem data"}</span>
<span className="arq-thumb">
{cover && <img src={cover} alt="" loading="lazy" decoding="async" />}
<span className="arq-badge dark">{gs.length} galerias</span>
</span>
<span className="arq-event">
<strong>{name}</strong>
<span>
{gs.length} galerias · {gs.reduce((n, g) => n + g.photoCount, 0)} fotos
<Fragment key={group.name}>
<button type="button" className="arq-card arq-groupcard" aria-expanded={expanded} onClick={() => setOpenGroup(expanded ? null : group.name)}>
<span className="arq-date">{dates[0] ? shortDay.format(new Date(dates[0])) : "Sem data"}</span>
<span className="arq-thumb">
{cover && <img src={cover} alt="" loading="lazy" decoding="async" />}
<span className="arq-badge dark">{group.galleries.length} galerias</span>
</span>
</span>
</button>
<span className="arq-event">
<strong>{group.name}</strong>
<span>
{group.galleries.length} galerias · {photos} fotos
</span>
</span>
</button>
{expanded && (
<div className="arq-group-open" ref={openPanel}>
<div className="arq-kind-head">
<h3>{group.name}</h3>
<span className="arq-muted">{group.galleries.length} galerias</span>
<span className="arq-grow" />
<button type="button" className="arq-link" onClick={() => setOpenGroup(null)}>
Fechar
</button>
</div>
<div className="arq-cards">{group.galleries.map(card)}</div>
</div>
)}
</Fragment>
);
})}
{loose.map(card)}
</div>
)}
{open && (
<div className="arq-group-open">
<div className="arq-kind-head">
<h3>{openGroup}</h3>
<span className="arq-muted">{open.length} galerias</span>
<span className="arq-grow" />
<button type="button" className="arq-link" onClick={() => setOpenGroup(null)}>
Fechar
</button>
</div>
<div className="arq-cards">{open.map(card)}</div>
</div>
)}
</>
);
};
@@ -2292,6 +2292,7 @@
box-shadow: 0 0 0 2px var(--ink), 5px 5px 0 0 var(--card), 5px 5px 0 2px var(--ink);
}
.arq-group-open {
grid-column: 1 / -1;
display: flex;
flex-direction: column;
gap: 12px;
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import type { GalleryCard } from "./api";
import { eventLayout } from "./events";
function card(id: string, group: string | null): GalleryCard {
return { id, title: id, group, home: null, away: null, competition: null, startsAt: null, photoCount: 10, cover: null };
}
describe("tournament tiles", () => {
it("keeps a tournament's galleries on that tile", () => {
const { groups, loose } = eventLayout([
card("a", "JORNADA 8"),
card("b", "JORNADA 8"),
card("c", "PG COMUNICAÇÃO"),
card("d", "PG COMUNICAÇÃO"),
card("e", "PG COMUNICAÇÃO"),
card("solo", null),
card("one", "Só um dia"),
]);
expect(groups.map((group) => [group.name, group.galleries.map((gallery) => gallery.id)])).toEqual([
["JORNADA 8", ["a", "b"]],
["PG COMUNICAÇÃO", ["c", "d", "e"]],
]);
expect(loose.map((gallery) => gallery.id)).toEqual(["solo", "one"]);
});
});
+29
View File
@@ -0,0 +1,29 @@
import type { GalleryCard } from "./api";
export interface EventGroup {
name: string;
galleries: GalleryCard[];
}
/**
* Tournaments are one tile per folder. A folder with a single gallery is just that gallery: clicking it opens
* the gallery. A folder with several galleries opens under its own tile, not after the whole list.
*/
export function eventLayout(items: readonly GalleryCard[]): { groups: EventGroup[]; loose: GalleryCard[] } {
const byName = new Map<string, GalleryCard[]>();
const loose: GalleryCard[] = [];
for (const item of items) {
const name = item.group?.trim() ?? "";
if (!name) {
loose.push(item);
continue;
}
byName.set(name, [...(byName.get(name) ?? []), item]);
}
const groups: EventGroup[] = [];
for (const [name, galleries] of byName) {
if (galleries.length < 2) loose.push(...galleries);
else groups.push({ name, galleries });
}
return { groups, loose };
}
+16 -9
View File
@@ -187,7 +187,8 @@ Only for organizations whose owner switched it on with a recorded legal basis (b
Each photo that arrives is queued (`photos.faces_status`); the worker reads the last 30 days first (when the photo
was taken, or the game's date when the camera wrote none), newest game first, and only then the older archive.
A folder of an old season that has just been indexed waits until that month is clear, then comes ahead of the
archive that has been waiting. Asking to analyse one event still puts it first. A photo whose analysis failed is
archive that has been waiting. The worker starts a few face processes and adds more while the CPU stays under
about 99%, stopping sooner when memory (the model) runs short. Asking to analyse one event still puts it first. A photo whose analysis failed is
queued again a few at a time, after it has been quiet for six hours, recent games first. Confirming a face
improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the
detector that finds a face in the photo is not retrained. The worker runs `workers/faces` on the original:
@@ -234,11 +235,15 @@ number for that event's context:
- **Season:** the official match's, or the event's day (July to June). The squad read is that season's, so an
old game gets the number worn then, even for players who have since left.
- **Official match (linked to its teams):** the match sheet first — that season's players and coaches, and the
referees of the fixture, when they already have a face. A face none of them explains is then compared with
everyone of that sport. A session (no away side) has no sheet: the face alone, against everyone of the sport.
The shirt, when it is read, stays with those two clubs. Then what the shirts clearly read (three
or more clear readings) in the person's confirmed photos of the same season and competition.
- **A game whose two clubs are known** (teams already stored, or the home and away names matching one team of
that sport each): only that season's squad — players and coaches — and the referees of the fixture, when they
already have a face. A player who has since moved is included when that season's list has them (the same
federation id, or the same birth date and full name), with the shirt number of that season. A face none of
them explains stays unnamed. It is never someone who was not at either club that season.
A session (no away side), an exhibition, or a name that matches no team has no sheet: the face alone, against
everyone of that sport, and only a clearly stronger match. The shirt, when it is read, stays with those two clubs.
Then what the shirts clearly read (three or more clear readings) in the person's confirmed photos of the same
season and competition.
- An editor of the folder can give a face another name. The list shows the official face, the club and the shirt
number.
- **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's
@@ -257,7 +262,8 @@ hand-drawn boxes.
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation:
- **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup. Gives teams, squads (numbers,
positions, official headshots) and the season's fixtures.
positions, official headshots) and the season's fixtures. On start the worker walks every season the federation
still publishes, club by club, so a past season keeps the squad and the shirt numbers of that year.
- **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and
fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the
match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence
@@ -295,8 +301,9 @@ What organisations do with it:
from public https hosts (private, loopback and link-local addresses refused, redirects checked again, 5 MB, 10 s)
and cached 5 minutes. For a generic event the form lists the day's entries; picking one fills name, venue, city
and time and suggests a caption ("Title, Venue, City.") to edit. Repeating entries show their first date only.
- **People from squads:** squads become people (club, number, `sportsPlayerId`). With biometrics on, the Liga
headshot becomes the reference photo, and number suggestions for faces use the event's squads.
- **People from squads:** one person per human. A later season at another club updates the club and the shirt
number; an older season does not. The number shown on a photo is still that season's. With biometrics on, the
Liga headshot becomes the reference photo, and number suggestions for faces use the event's squads.
## Working without a network (desktop app)
+60 -4
View File
@@ -2,15 +2,18 @@
//!
//! This is not the `hdr.*` develop panel. That panel is display headroom for one photo. Here several
//! exposures of the same angle become one scene-linear image: the engine aligns them, measures the
//! exposure steps, and weights each pixel so a clipped channel contributes nothing. The result is
//! developed with the engine's Auto settings (the same finish LightCraft applies to a merge).
//! exposure steps, and weights each pixel so a clipped channel contributes nothing. The JPEG preview
//! is developed with the engine's Auto settings. The linear DNG is not: the editor does that finish.
use std::sync::Arc;
use lightcraft_color::Xy;
use lightcraft_develop::DevelopSettings;
use lightcraft_merge::frame::Frame;
use lightcraft_merge::{Deghost, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress};
use lightcraft_merge::{
Deghost, DngSamples, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress,
write_linear_dng,
};
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto};
use lightcraft_raster::Rgb32f;
use lightcraft_raster::resample::{Filter, fit};
@@ -188,7 +191,7 @@ fn to_working(merged: &HdrResult) -> (Rgb32f, SourceInfo) {
}
}
fn camera_working(image: Rgb32f, color: &ColorData, gain: f32) -> (Rgb32f, SourceInfo) {
pub(crate) fn camera_working(image: Rgb32f, color: &ColorData, gain: f32) -> (Rgb32f, SourceInfo) {
let white = as_shot_xy(color);
let transform = lightcraft_raw::color::camera_transform_of(color, white);
let m = transform.matrix.to_f32();
@@ -221,6 +224,41 @@ fn as_shot_xy(color: &ColorData) -> Xy {
lightcraft_color::D65
}
/// Scene-linear DNG of one bracket (16-bit float). `max_edge` is the long side of each frame before
/// the merge, clamped to 64..=4096. The develop finish is not baked in: the file stays linear so the
/// editor's controls do it.
pub fn merge_linear_dng(files: &[&[u8]], max_edge: u32) -> Result<Vec<u8>, EngineError> {
if files.len() < 2 {
return Err(EngineError::Decode(
"a bracket needs at least two exposures".into(),
));
}
let edge = clamped_edge(max_edge);
let mut frames = Vec::with_capacity(files.len());
for file in files {
frames.push(load_bracket_frame(file, edge)?);
}
let merged = merge_hdr(
frames,
&HdrOptions {
align: true,
deghost: Deghost::None,
},
&no_progress,
)
.map_err(|e| EngineError::Decode(e.to_string()))?;
write_linear_dng(
&merged.radiance,
&merged.color,
merged.orientation,
&merged.metadata,
merged.baseline_exposure,
DngSamples::Half,
&merged.lens,
)
.map_err(|e| EngineError::Decode(e.to_string()))
}
fn apply_mat(m: &[[f32; 3]; 3], p: [f32; 3]) -> [f32; 3] {
[
m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2],
@@ -314,6 +352,24 @@ mod tests {
);
}
#[test]
fn a_merge_writes_a_dng_the_editor_can_open() {
let dark = exposure_dng(-2.0);
let mid = exposure_dng(0.0);
let bright = exposure_dng(2.0);
let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()];
let dng = merge_linear_dng(&files, 256).expect("dng");
assert!(dng.len() > 64);
let source = crate::render::Source::decode(&dng, 256).expect("decode");
let (w, h) = source.size();
assert!(w >= 64 && h >= 64, "{w}x{h}");
let pixels = source.render(&DevelopSettings::default(), 128, 128, false, false);
assert_eq!(
pixels.rgba.len(),
pixels.width as usize * pixels.height as usize * 4
);
}
#[test]
fn one_photo_is_not_a_bracket() {
let mid = exposure_dng(0.0);
+37
View File
@@ -23,6 +23,39 @@ pub struct Source {
pub source_height: u32,
}
/// A linear DNG (three samples, no mosaic) into the working space. Mosaic raws are refused: those stay
/// on the merge path, which bins them on purpose.
fn decode_linear_dng(bytes: &[u8], max_edge: u32) -> Result<Source, EngineError> {
let raw = lightcraft_raw::decode(bytes).map_err(|e| EngineError::Decode(e.to_string()))?;
if raw.cfa.is_some() || raw.cpp != 3 {
return Err(EngineError::Decode("not a linear photo".into()));
}
let developed = raw
.develop(lightcraft_raw::Method::Bilinear)
.map_err(|e| EngineError::Decode(e.to_string()))?;
let gain = 2f32.powf(raw.color.baseline_exposure as f32);
let (image, info) = crate::merge::camera_working(developed, &raw.color, gain);
let image = image.into_oriented(raw.orientation);
let (source_width, source_height) = (image.width as u32, image.height as u32);
let edge = if max_edge == 0 {
usize::MAX
} else {
max_edge as usize
};
let image = if image.width.max(image.height) > edge {
fit(&image, edge, edge, Filter::Mitchell)
} else {
image
};
Ok(Source {
image: Arc::new(image),
info,
cache: StageCache::default(),
source_width,
source_height,
})
}
/// An 8-bit sRGB render with alpha (RGBA, row-major).
pub struct Pixels {
pub width: u32,
@@ -32,7 +65,11 @@ pub struct Pixels {
impl Source {
/// Decodes `bytes`, keeping at most `max_edge` pixels on the long side (0 = full resolution).
/// A linear DNG (a merged bracket) is developed from its camera RGB. Mosaic raws are not.
pub fn decode(bytes: &[u8], max_edge: u32) -> Result<Source, EngineError> {
if lightcraft_raw::probe(bytes) == Some(lightcraft_raw::RawFormat::Dng) {
return decode_linear_dng(bytes, max_edge);
}
let edge = if max_edge == 0 { u32::MAX } else { max_edge };
let d = lightcraft_codecs::decode(bytes, DecodeOptions::fit(edge, edge))
.map_err(|e| EngineError::Decode(e.to_string()))?;
+7
View File
@@ -189,6 +189,13 @@ impl BracketJob {
self.files.push(bytes.to_vec());
}
/// Scene-linear DNG (16-bit float). `max_edge` is the long side of each frame before the merge.
#[wasm_bindgen(js_name = mergeDng)]
pub fn merge_dng(&self, max_edge: u32) -> Result<Vec<u8>, JsError> {
let refs: Vec<&[u8]> = self.files.iter().map(Vec::as_slice).collect();
photoreport_engine::merge::merge_linear_dng(&refs, max_edge).map_err(js_err)
}
/// Developed JPEG preview of the merged bracket. `max_edge` is the long side of each frame.
pub fn merge(&self, max_edge: u32) -> Result<BracketMerge, JsError> {
let refs: Vec<&[u8]> = self.files.iter().map(Vec::as_slice).collect();
+26
View File
@@ -114,6 +114,32 @@ export class ApiClient {
return this.request<{ stored: boolean }>("POST", `/v1/photos/${photoId}/original`, form);
}
/**
* A JPEG preview of a merge. `silent` holds it until {@link attachLinearDng} replaces the file,
* so the library hears about the photo once. `inbox` keeps it out of every event.
*/
uploadPhoto(orgId: string, file: Blob, name: string, opts: { eventId?: string | null; silent?: boolean; inbox?: boolean } = {}) {
const form = new FormData();
form.append("file", file, name);
const params = new URLSearchParams();
if (opts.eventId) params.set("eventId", opts.eventId);
if (opts.inbox) params.set("inbox", "1");
if (opts.silent) params.set("silent", "1");
const query = params.size ? `?${params}` : "";
return this.request<{ status: string; photo: PhotoSummary }>("POST", `/v1/orgs/${orgId}/uploads${query}`, form);
}
/** The linear DNG that replaces a held preview. The photo then shows up in the collection. */
attachLinearDng(photoId: string, file: Blob, meta: { width: number; height: number; capturedAt: string | null }) {
const form = new FormData();
form.append("file", file, "merged.dng");
const params = new URLSearchParams();
params.set("width", String(meta.width));
params.set("height", String(meta.height));
if (meta.capturedAt) params.set("capturedAt", meta.capturedAt);
return this.request<{ status: string; photo: PhotoSummary }>("POST", `/v1/photos/${photoId}/linear-dng?${params}`, form);
}
/** Desktop app: takes the deliveries waiting for this computer's folders (rendered on the server). */
claimLocalDeliveries(orgId: string, machine: string) {
return this.request<{ items: { id: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine });