Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
efa9256c87 | ||
|
|
7fdbc9237b |
No files matched your search
@@ -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);
|
||||
|
||||
@@ -62,6 +62,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;
|
||||
@@ -730,17 +734,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 +800,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. */
|
||||
|
||||
@@ -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,8 @@ 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.",
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { applyFinish } from "../realestate/finish.js";
|
||||
import { fuseBracket } from "../realestate/fuse.js";
|
||||
import { fuseBracket, type FusePhase } from "../realestate/fuse.js";
|
||||
import { LOOKS, finishValues, needsFinish, type LookId } from "../realestate/looks.js";
|
||||
import { fillFromSidecar, pairKey, partitionBracketFiles, readBracketFile } from "../realestate/readFrame.js";
|
||||
import { downloadBlob, jpegName, saveBlobs } from "../realestate/save.js";
|
||||
@@ -154,12 +154,14 @@ function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Ma
|
||||
const byId = new Map(frames.map((frame) => [frame.id, frame]));
|
||||
const ready = useRef(new Set<number>());
|
||||
const [fused, setFused] = useState(0);
|
||||
const [active, setActive] = useState<{ index: number; phase: "reading" | "merging" } | null>(null);
|
||||
const [blobs, setBlobs] = useState<Map<number, Blob>>(new Map());
|
||||
const [saving, setSaving] = useState<{ done: number; total: number } | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
ready.current = new Set();
|
||||
setFused(0);
|
||||
setActive(null);
|
||||
setBlobs(new Map());
|
||||
setNote(null);
|
||||
}, [result]);
|
||||
@@ -185,14 +187,18 @@ function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Ma
|
||||
}
|
||||
};
|
||||
|
||||
let progressLabel = t.realEstate.fusingAll(fused, result.stacks.length);
|
||||
if (active?.phase === "reading") progressLabel = t.realEstate.readingAll(active.index + 1, result.stacks.length);
|
||||
else if (active?.phase === "merging") progressLabel = t.realEstate.fusingOne(active.index + 1, result.stacks.length);
|
||||
|
||||
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.resultHelp}</p>}
|
||||
{result.stacks.length > 0 && fused < result.stacks.length && (
|
||||
<div>
|
||||
<Track done={fused} total={result.stacks.length} />
|
||||
<p className="mt-1 text-sm text-muted">{t.realEstate.fusingAll(fused, result.stacks.length)}</p>
|
||||
<Track done={fused} total={result.stacks.length} working={active !== null} />
|
||||
<p className="mt-1 text-sm text-muted">{progressLabel}</p>
|
||||
</div>
|
||||
)}
|
||||
{result.stacks.length > 0 && (
|
||||
@@ -226,6 +232,11 @@ function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Ma
|
||||
if (ready.current.has(index)) return;
|
||||
ready.current.add(index);
|
||||
setFused(ready.current.size);
|
||||
setActive((cur) => (cur?.index === index ? null : cur));
|
||||
}}
|
||||
onPhase={(phase) => {
|
||||
if (phase === "queued") return;
|
||||
setActive({ index, phase });
|
||||
}}
|
||||
onBlob={(blob) =>
|
||||
setBlobs((current) => {
|
||||
@@ -266,6 +277,7 @@ function AnglePreview({
|
||||
fileName,
|
||||
onReady,
|
||||
onBlob,
|
||||
onPhase,
|
||||
}: {
|
||||
index: number;
|
||||
ids: string[];
|
||||
@@ -273,6 +285,7 @@ function AnglePreview({
|
||||
fileName: string;
|
||||
onReady: () => void;
|
||||
onBlob: (blob: Blob) => void;
|
||||
onPhase: (phase: FusePhase) => void;
|
||||
}) {
|
||||
const [base, setBase] = useState<Blob | null>(null);
|
||||
const [shown, setShown] = useState<Blob | null>(null);
|
||||
@@ -283,10 +296,13 @@ function AnglePreview({
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [applying, setApplying] = useState(false);
|
||||
const [lookError, setLookError] = useState(false);
|
||||
const [phase, setPhase] = useState<FusePhase>("queued");
|
||||
const ready = useRef(onReady);
|
||||
const report = useRef(onBlob);
|
||||
const tell = useRef(onPhase);
|
||||
ready.current = onReady;
|
||||
report.current = onBlob;
|
||||
tell.current = onPhase;
|
||||
const key = ids.join("\n");
|
||||
useEffect(() => {
|
||||
const stack = ids.map((id) => files.get(id)).filter((file): file is File => file instanceof File);
|
||||
@@ -298,16 +314,26 @@ function AnglePreview({
|
||||
setBase(null);
|
||||
setShown(null);
|
||||
setFailed(false);
|
||||
setPhase("queued");
|
||||
setLook("natural");
|
||||
setTweaks(null);
|
||||
fuseBracket(stack)
|
||||
fuseBracket(
|
||||
stack,
|
||||
(next) => {
|
||||
if (cancelled) return;
|
||||
setPhase(next);
|
||||
tell.current(next);
|
||||
},
|
||||
() => cancelled,
|
||||
)
|
||||
.then((blob) => {
|
||||
if (cancelled) return;
|
||||
setBase(blob);
|
||||
setShown(blob);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setFailed(true);
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled || (err instanceof Error && err.message === "cancelled")) return;
|
||||
setFailed(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
@@ -354,7 +380,12 @@ function AnglePreview({
|
||||
return () => URL.revokeObjectURL(objectUrl);
|
||||
}, [shown]);
|
||||
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>;
|
||||
if (!url) {
|
||||
let label: string = t.realEstate.queued;
|
||||
if (phase === "reading") label = t.realEstate.readingOne;
|
||||
else if (phase === "merging") label = t.realEstate.fusing;
|
||||
return <p className="px-3 py-2 text-[13px] text-muted">{label}</p>;
|
||||
}
|
||||
const controls = finishValues(look, tweaks ?? {});
|
||||
const setControl = (id: string, value: number) => setTweaks({ ...finishValues(look, tweaks ?? {}), [id]: value });
|
||||
return (
|
||||
@@ -406,11 +437,12 @@ function Slider({ label, min, max, step, value, onChange }: { label: string; min
|
||||
);
|
||||
}
|
||||
|
||||
function Track({ done, total }: { done: number; total: number }) {
|
||||
function Track({ done, total, working = false }: { done: number; total: number; working?: boolean }) {
|
||||
const percent = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||
const width = working ? Math.max(percent, 8) : percent;
|
||||
return (
|
||||
<div className="h-3 overflow-hidden bg-black" role="progressbar" aria-valuenow={done} aria-valuemin={0} aria-valuemax={total}>
|
||||
<div className="h-full bg-accent" style={{ width: `${percent}%` }} />
|
||||
<div className="h-full bg-accent" style={{ width: `${width}%` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user