Compare commits

...
Author SHA1 Message Date
spark 45c97bbcb2 Show what the folder search is doing before the first photo.
ci / rust (pull_request) Failing after 43s
ci / typescript (pull_request) Failing after 2m22s
The wait names the step (download, count, graphics, load) and how long it has already taken, so a first-time prepare is not a frozen sentence.
2026-10-17 21:48:25 +01:00
spark 596105493a Folder search keeps going when the window is closed
ci / rust (push) Failing after 48s
ci / typescript (push) Failing after 8m11s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Failing after 10m57s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Failing after 15m59s
Closing it only hides the window. The Mac build also links compiler-rt so the GPU installer can finish.
2026-10-17 21:01:15 +01:00
spark 7b88827847 Folder search keeps going when the window is closed.
ci / rust (pull_request) Failing after 42s
ci / typescript (pull_request) Failing after 7m57s
Closing it only hides the window; a bar at the bottom opens it again. The Mac build also links compiler-rt, which the GPU recogniser needs and the installer was missing.
2026-10-17 21:00:51 +01:00
spark 7aac72e0ea Desktop: use the GPU, Neural Engine and CPU together for face recognition
ci / rust (push) Failing after 47s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Failing after 6m50s
ci / typescript (push) Failing after 7m49s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Failing after 15m38s
The boxes stay on the CPU interpreter. The recogniser uses every accelerator when a startup check still matches that interpreter.
2026-10-17 20:38:15 +01:00
11 changed files with 354 additions and 45 deletions

No files matched your search

+17 -1
View File
@@ -625,7 +625,20 @@ export const t = {
accelGpu: "A usar a gráfica e o processador.", accelGpu: "A usar a gráfica e o processador.",
accelAne: "A usar o Neural Engine e o processador.", accelAne: "A usar o Neural Engine e o processador.",
accelCpu: "O reconhecimento nesta máquina está a correr no processador.", accelCpu: "O reconhecimento nesta máquina está a correr no processador.",
preparing: "A preparar o reconhecimento neste computador. Da primeira vez demora um pouco.", preparing: "A preparar o reconhecimento neste computador.",
preparingList: (n: number) => (n > 0 ? `Encontrei ${n} fotos JPEG.` : "A contar as fotos da pasta."),
preparingGpu: "A preparar a gráfica. Da primeira vez costuma levar cerca de um minuto. As seguintes são mais rápidas.",
preparingLoad: "A carregar o modelo na memória.",
downloading: (done: number, total: number) => {
const mb = (n: number) => `${Math.round(n / 1_000_000)} MB`;
return total > 0 ? `A descarregar o modelo (${mb(done)} de ${mb(total)}).` : "A descarregar o modelo.";
},
elapsed: (seconds: number) => {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
const clock = `${minutes}:${rest.toString().padStart(2, "0")}`;
return `Já vão ${clock}.`;
},
game: "Jogo", game: "Jogo",
roster: (n: number) => roster: (n: number) =>
n === 1 n === 1
@@ -639,6 +652,9 @@ export const t = {
scanning: (done: number, total: number) => `A ver ${done} de ${total}`, scanning: (done: number, total: number) => `A ver ${done} de ${total}`,
cancel: "Parar", cancel: "Parar",
close: "Fechar", close: "Fechar",
reopen: "Abrir",
backgroundDone: "A pasta está lida.",
stopped: "A pesquisa foi parada.",
none: "Nenhuma foto corresponde a essa pesquisa.", none: "Nenhuma foto corresponde a essa pesquisa.",
empty: "Nenhuma cara nem número nestas fotos.", empty: "Nenhuma cara nem número nestas fotos.",
unread: (n: number) => (n === 1 ? "1 foto sem cara nem número ficou de fora." : `${n} fotos sem cara nem número ficaram de fora.`), unread: (n: number) => (n === 1 ? "1 foto sem cara nem número ficou de fora." : `${n} fotos sem cara nem número ficaram de fora.`),
+59 -1
View File
@@ -1,7 +1,8 @@
import { fireEvent, render, screen } from "@testing-library/react"; import { fireEvent, render, screen } from "@testing-library/react";
import type { ApiClient, EventSummary } from "@photoreport/sdk"; import type { ApiClient, EventSummary } from "@photoreport/sdk";
import { useState } from "react";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { CardScan, cardMatches } from "./CardScan.js"; import { CardScan, cardMatches, waitLine } from "./CardScan.js";
const face = (over: { number?: string | null; name?: string; club?: string | null; personNumber?: string | null } = {}) => ({ const face = (over: { number?: string | null; name?: string; club?: string | null; personNumber?: string | null } = {}) => ({
box: { x0: 0, y0: 0, x1: 0.1, y1: 0.1 }, box: { x0: 0, y0: 0, x1: 0.1, y1: 0.1 },
@@ -32,6 +33,16 @@ describe("searching a card", () => {
}); });
}); });
describe("the wait before the first photo", () => {
it("names the step and the time already spent", () => {
expect(waitLine(null, 65)).toBe("A preparar o reconhecimento neste computador. Já vão 1:05.");
expect(waitLine({ step: "gpu", done: 0, total: 0 }, 12)).toContain("A preparar a gráfica.");
expect(waitLine({ step: "gpu", done: 0, total: 0 }, 12)).toContain("Já vão 0:12.");
expect(waitLine({ step: "download", done: 50_000_000, total: 250_000_000 }, 3)).toContain("50 MB de 250 MB");
expect(waitLine({ step: "list", done: 4005, total: 4005 }, 1)).toContain("4005 fotos JPEG");
});
});
describe("card folder dialog", () => { describe("card folder dialog", () => {
it("reads the JPEGs, filters by name and number, and imports only the selected originals", async () => { it("reads the JPEGs, filters by name and number, and imports only the selected originals", async () => {
vi.stubGlobal( vi.stubGlobal(
@@ -107,4 +118,51 @@ describe("card folder dialog", () => {
expect(await screen.findByRole("button", { name: /Rui/ })).toBeTruthy(); expect(await screen.findByRole("button", { name: /Rui/ })).toBeTruthy();
expect(scanCard).toHaveBeenCalledTimes(1); expect(scanCard).toHaveBeenCalledTimes(1);
}); });
it("keeps reading after the dialog is closed", async () => {
vi.stubGlobal("createImageBitmap", async () => ({ width: 800, height: 600, close() {} }));
vi.spyOn(URL, "createObjectURL").mockImplementation(() => "blob:later");
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
HTMLCanvasElement.prototype.getContext = (() => ({ drawImage() {} })) as unknown as typeof HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.toBlob = function (cb) {
cb(new Blob([new Uint8Array([1])], { type: "image/jpeg" }));
};
let release: (value: { slots: number; roster: number; faces: ReturnType<typeof face>[] }) => void = () => {};
const scanCard = vi.fn(
() =>
new Promise<{ slots: number; roster: number; faces: ReturnType<typeof face>[] }>((resolve) => {
release = resolve;
}),
);
const dismissed = vi.fn();
function Host() {
const [visible, setVisible] = useState(true);
return (
<CardScan
api={{ scanCard } as unknown as ApiClient}
orgId="org"
eventId="game"
games={[{ id: "game", home: "A", away: "B", startsAt: "2026-10-17T15:00:00.000Z" } as EventSummary]}
visible={visible}
onImport={() => {}}
onClose={() => setVisible(false)}
onShow={() => setVisible(true)}
onDismiss={dismissed}
/>
);
}
render(<Host />);
const picker = document.querySelector("input[type=file]") as HTMLInputElement;
fireEvent.change(picker, { target: { files: [new File(["a"], "a.jpg", { type: "image/jpeg" })] } });
expect(await screen.findByText("A ver 0 de 1")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Fechar" }));
expect(dismissed).not.toHaveBeenCalled();
expect(screen.queryByRole("dialog")).toBeNull();
expect(screen.getByRole("status").textContent).toContain("A ver 0 de 1");
release({ slots: 4, roster: 1, faces: [face({ name: "Rui" })] });
expect(await screen.findByText("A pasta está lida.")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Abrir" }));
expect(await screen.findByRole("button", { name: /Rui/ })).toBeTruthy();
expect(scanCard).toHaveBeenCalledTimes(1);
});
}); });
+104 -15
View File
@@ -1,6 +1,6 @@
import type { ApiClient, CardScan as CardReading, EventSummary } from "@photoreport/sdk"; import type { ApiClient, CardScan as CardReading, EventSummary } from "@photoreport/sdk";
import { ApiError } from "@photoreport/sdk"; import { ApiError } from "@photoreport/sdk";
import { useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n.js"; import { t } from "../i18n.js";
import { kv } from "../offline/kv.js"; import { kv } from "../offline/kv.js";
import { asArrayBuffer, desktopInvoke, isDesktop } from "../platform.js"; import { asArrayBuffer, desktopInvoke, isDesktop } from "../platform.js";
@@ -59,6 +59,22 @@ export function cardMatches(faces: Face[], query: string): boolean {
}); });
} }
interface PrepareStep {
step: string;
done: number;
total: number;
}
/** What the desktop is doing before the first photo, plus how long this wait has already lasted. */
export function waitLine(prepare: PrepareStep | null, elapsed: number): string {
let what = t.cardScan.preparing;
if (prepare?.step === "download") what = t.cardScan.downloading(prepare.done, prepare.total);
else if (prepare?.step === "list") what = t.cardScan.preparingList(prepare.total);
else if (prepare?.step === "gpu") what = t.cardScan.preparingGpu;
else if (prepare?.step === "load") what = t.cardScan.preparingLoad;
return `${what} ${t.cardScan.elapsed(elapsed)}`;
}
function labelOf(faces: Face[]): string { function labelOf(faces: Face[]): string {
const bits: string[] = []; const bits: string[] = [];
for (const f of faces) { for (const f of faces) {
@@ -107,13 +123,21 @@ export function CardScan({
games, games,
onImport, onImport,
onClose, onClose,
onDismiss = onClose,
onShow,
visible = true,
}: { }: {
api: ApiClient; api: ApiClient;
orgId: string; orgId: string;
eventId: string; eventId: string;
games: EventSummary[]; games: EventSummary[];
onImport: (files: File[], eventId: string) => void; onImport: (files: File[], eventId: string) => void;
/** Hide the dialog. The read keeps going. */
onClose: () => void; onClose: () => void;
/** Throw the panel away. Used when nothing was started, or when the finished bar is closed. */
onDismiss?: () => void;
onShow?: () => void;
visible?: boolean;
}) { }) {
const input = useRef<HTMLInputElement>(null); const input = useRef<HTMLInputElement>(null);
const stop = useRef(false); const stop = useRef(false);
@@ -129,24 +153,56 @@ export function CardScan({
const [roster, setRoster] = useState<number | null | undefined>(undefined); const [roster, setRoster] = useState<number | null | undefined>(undefined);
const [localMode, setLocalMode] = useState(false); const [localMode, setLocalMode] = useState(false);
const [accelerators, setAccelerators] = useState<string | null>(null); const [accelerators, setAccelerators] = useState<string | null>(null);
const [prepare, setPrepare] = useState<PrepareStep | null>(null);
const [elapsed, setElapsed] = useState(0);
const [stopped, setStopped] = useState(false);
const startedAt = useRef(0);
const folderRef = useRef(""); const folderRef = useRef("");
const gameRef = useRef(gameId); const gameRef = useRef(gameId);
gameRef.current = gameId; gameRef.current = gameId;
const choices = useMemo(() => [...games].sort((a, b) => b.startsAt.localeCompare(a.startsAt)), [games]); const choices = useMemo(() => [...games].sort((a, b) => b.startsAt.localeCompare(a.startsAt)), [games]);
const runningRef = useRef(false);
const itemsRef = useRef<Item[]>([]);
const localRef = useRef(false);
const onCloseRef = useRef(onClose);
const onDismissRef = useRef(onDismiss);
runningRef.current = running;
itemsRef.current = items;
localRef.current = localMode;
onCloseRef.current = onClose;
onDismissRef.current = onDismiss;
const hide = useCallback(() => {
if (!runningRef.current && itemsRef.current.length === 0) onDismissRef.current();
else onCloseRef.current();
}, []);
const cancelScan = () => {
stop.current = true;
setStopped(true);
if (localRef.current) void desktopInvoke("faces_cancel").catch(() => {});
};
useEffect(() => { useEffect(() => {
if (!running || total > 0) return;
const id = setInterval(() => setElapsed(Math.floor((Date.now() - startedAt.current) / 1000)), 1000);
return () => clearInterval(id);
}, [running, total]);
useEffect(() => {
if (!visible) return;
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose(); if (e.key === "Escape") hide();
}; };
window.addEventListener("keydown", onKey); window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey);
}, [onClose]); }, [visible, hide]);
const live = useRef<Item[]>([]); const live = useRef<Item[]>([]);
live.current = items; live.current = items;
useEffect(() => { useEffect(() => {
return () => { return () => {
stop.current = true; stop.current = true;
if (localRef.current) void desktopInvoke("faces_cancel").catch(() => {});
for (const item of live.current) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb); for (const item of live.current) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb);
}; };
}, []); }, []);
@@ -156,6 +212,7 @@ export function CardScan({
const run = async (list: FileList) => { const run = async (list: FileList) => {
stop.current = false; stop.current = false;
setStopped(false);
setNote(null); setNote(null);
setSent(null); setSent(null);
setSelected(new Set()); setSelected(new Set());
@@ -230,10 +287,14 @@ export function CardScan({
const runLocal = async (folder: string) => { const runLocal = async (folder: string) => {
stop.current = false; stop.current = false;
setStopped(false);
folderRef.current = folder; folderRef.current = folder;
setLocalMode(true); setLocalMode(true);
setAccelerators(null); setAccelerators(null);
setNote(t.cardScan.preparing); setPrepare(null);
startedAt.current = Date.now();
setElapsed(0);
setNote(null);
setSent(null); setSent(null);
setSelected(new Set()); setSelected(new Set());
setDone(0); setDone(0);
@@ -278,6 +339,9 @@ export function CardScan({
const stopAccel = await listen<{ accelerators: string }>("faces-accel", (e) => { const stopAccel = await listen<{ accelerators: string }>("faces-accel", (e) => {
if (e.payload.accelerators) setAccelerators(e.payload.accelerators); if (e.payload.accelerators) setAccelerators(e.payload.accelerators);
}); });
const stopPrepare = await listen<PrepareStep>("faces-prepare", (e) => {
if (e.payload?.step) setPrepare(e.payload);
});
const stopPhoto = await listen<LocalPhoto>("faces-photo", (e) => { const stopPhoto = await listen<LocalPhoto>("faces-photo", (e) => {
const ev = e.payload; const ev = e.payload;
if (stop.current) return; if (stop.current) return;
@@ -303,6 +367,7 @@ export function CardScan({
}); });
unlisten = () => { unlisten = () => {
stopAccel(); stopAccel();
stopPrepare();
stopPhoto(); stopPhoto();
}; };
const token = await api.realtimeToken(); const token = await api.realtimeToken();
@@ -313,7 +378,7 @@ export function CardScan({
} }
await naming; await naming;
} catch (err) { } catch (err) {
setNote(err instanceof ApiError ? (t.lookup.errors[err.code] ?? t.unexpectedError) : t.cardScan.failed); if (!stop.current) setNote(err instanceof ApiError ? (t.lookup.errors[err.code] ?? t.unexpectedError) : t.cardScan.failed);
} finally { } finally {
unlisten(); unlisten();
setRunning(false); setRunning(false);
@@ -341,6 +406,36 @@ export function CardScan({
}); });
}; };
if (!visible) {
if (!running && items.length === 0) return null;
return (
<div role="status" className="fixed inset-x-0 bottom-0 z-40 flex flex-wrap items-center gap-3 border-t border-black bg-[#1d2a3a] px-4 py-2 text-[12px] text-ink">
<span>{t.cardScan.title}</span>
{running ? (
<span className="font-mono">{total > 0 ? t.cardScan.scanning(done, total) : waitLine(prepare, elapsed)}</span>
) : (
<span>{stopped ? t.cardScan.stopped : t.cardScan.backgroundDone}</span>
)}
{localMode && accelerators === "all" && <span className="text-muted">{t.cardScan.accelAll}</span>}
{localMode && accelerators === "gpu" && <span className="text-muted">{t.cardScan.accelGpu}</span>}
{localMode && accelerators === "ane" && <span className="text-muted">{t.cardScan.accelAne}</span>}
{localMode && accelerators === "cpu" && <span className="text-muted">{t.cardScan.accelCpu}</span>}
<button type="button" onClick={() => onShow?.()} className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong">
{t.cardScan.reopen}
</button>
{running ? (
<button type="button" onClick={cancelScan} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.cancel}
</button>
) : (
<button type="button" onClick={onDismiss} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.close}
</button>
)}
</div>
);
}
return ( return (
<div role="dialog" aria-modal="true" aria-label={t.cardScan.title} className="fixed inset-0 z-30 flex flex-col bg-black/80 p-4"> <div role="dialog" aria-modal="true" aria-label={t.cardScan.title} className="fixed inset-0 z-30 flex flex-col bg-black/80 p-4">
<div className="mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col border border-black bg-panel"> <div className="mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col border border-black bg-panel">
@@ -387,18 +482,11 @@ export function CardScan({
}} }}
/> />
{running && ( {running && (
<button <button type="button" onClick={cancelScan} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
type="button"
onClick={() => {
stop.current = true;
if (localMode) void desktopInvoke("faces_cancel").catch(() => {});
}}
className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
{t.cardScan.cancel} {t.cardScan.cancel}
</button> </button>
)} )}
<button type="button" onClick={onClose} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"> <button type="button" onClick={hide} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.close} {t.cardScan.close}
</button> </button>
</div> </div>
@@ -411,7 +499,8 @@ export function CardScan({
{roster === null && <span className="ml-2 text-ink">{t.cardScan.rosterOpen}</span>} {roster === null && <span className="ml-2 text-ink">{t.cardScan.rosterOpen}</span>}
{roster === 0 && <span className="ml-2 text-ink">{t.cardScan.rosterNone}</span>} {roster === 0 && <span className="ml-2 text-ink">{t.cardScan.rosterNone}</span>}
{typeof roster === "number" && roster > 0 && <span className="ml-2 text-ink">{t.cardScan.roster(roster)}</span>} {typeof roster === "number" && roster > 0 && <span className="ml-2 text-ink">{t.cardScan.roster(roster)}</span>}
{running && <span className="ml-2 font-mono text-ink">{t.cardScan.scanning(done, total)}</span>} {running && total === 0 && <span className="ml-2 text-ink">{waitLine(prepare, elapsed)}</span>}
{running && total > 0 && <span className="ml-2 font-mono text-ink">{t.cardScan.scanning(done, total)}</span>}
</p> </p>
{note && <p className="px-3 pb-2 text-[12px] text-danger">{note}</p>} {note && <p className="px-3 pb-2 text-[12px] text-danger">{note}</p>}
{sent && <p className="px-3 pb-2 text-[12px] text-ink">{sent}</p>} {sent && <p className="px-3 pb-2 text-[12px] text-ink">{sent}</p>}
+68
View File
@@ -0,0 +1,68 @@
import type { EventSummary } from "@photoreport/sdk";
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
import { useAuth } from "../auth.js";
import { CardScan } from "./CardScan.js";
import { useIngest } from "./ingest.js";
interface Session {
eventId: string;
games: EventSummary[];
visible: boolean;
}
interface FolderScanApi {
open: (eventId: string, games: EventSummary[]) => void;
syncGames: (games: EventSummary[]) => void;
}
const FolderScanContext = createContext<FolderScanApi | null>(null);
/**
* Folder search lives above the modules, same as the upload queue. Closing the dialog only hides it: the read keeps
* going, and a bar at the bottom opens it again. A new organization remounts this with the ingest, which stops the read.
*/
export function FolderScanProvider({ children }: { children: ReactNode }) {
const { api, organization } = useAuth();
const { uploads } = useIngest();
const orgId = organization?.id ?? "";
const [session, setSession] = useState<Session | null>(null);
const open = useCallback((eventId: string, games: EventSummary[]) => {
setSession((current) => {
if (current) return { ...current, visible: true, games: games.length > 0 ? games : current.games };
return { eventId, games, visible: true };
});
}, []);
const syncGames = useCallback((games: EventSummary[]) => {
if (games.length === 0) return;
setSession((current) => (current ? { ...current, games } : current));
}, []);
const value = useMemo(() => ({ open, syncGames }), [open, syncGames]);
return (
<FolderScanContext.Provider value={value}>
{children}
{session && orgId && (
<CardScan
api={api}
orgId={orgId}
eventId={session.eventId}
games={session.games}
visible={session.visible}
onImport={(files, id) => uploads.add(files, id)}
onClose={() => setSession((current) => (current ? { ...current, visible: false } : current))}
onShow={() => setSession((current) => (current ? { ...current, visible: true } : current))}
onDismiss={() => setSession(null)}
/>
)}
</FolderScanContext.Provider>
);
}
export function useFolderScan(): FolderScanApi {
const ctx = useContext(FolderScanContext);
if (!ctx) throw new Error("useFolderScan outside FolderScanProvider");
return ctx;
}
+13 -13
View File
@@ -8,7 +8,7 @@ import { t } from "../i18n.js";
import { EventForm } from "../library/EventForm.js"; import { EventForm } from "../library/EventForm.js";
import { EventsPanel } from "../library/EventsPanel.js"; import { EventsPanel } from "../library/EventsPanel.js";
import { EventSettingsButton } from "../library/EventSettings.js"; import { EventSettingsButton } from "../library/EventSettings.js";
import { CardScan } from "../library/CardScan.js"; import { useFolderScan } from "../library/folderScan.js";
import { FacesView } from "../library/FacesView.js"; import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js"; import { LookupBanner } from "../library/PhotoLookup.js";
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js"; import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
@@ -47,7 +47,7 @@ export function LibraryPage() {
const [inboxCount, setInboxCount] = useState(0); const [inboxCount, setInboxCount] = useState(0);
const [targets, setTargets] = useState<DeliveryTarget[]>([]); const [targets, setTargets] = useState<DeliveryTarget[]>([]);
const [iptcOpen, setIptcOpen] = useState(false); const [iptcOpen, setIptcOpen] = useState(false);
const [cardOpen, setCardOpen] = useState(false); const { open: openFolderScan, syncGames } = useFolderScan();
const [state, dispatch] = useReducer(libraryReducer, initialLibrary); const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId)); const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
useEffect(() => setFilterState(savedFilter(orgId)), [orgId]); useEffect(() => setFilterState(savedFilter(orgId)), [orgId]);
@@ -211,6 +211,10 @@ export function LibraryPage() {
const [dragging, setDragging] = useState(false); const [dragging, setDragging] = useState(false);
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined; const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined;
const openEvent = events.find((e) => e.id === uploadInto) ?? archivedEvents?.find((e) => e.id === uploadInto); const openEvent = events.find((e) => e.id === uploadInto) ?? archivedEvents?.find((e) => e.id === uploadInto);
useEffect(() => {
const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events;
syncGames(games);
}, [events, openEvent, syncGames]);
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading"); const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
const failed = uploads.items.filter((i) => i.status === "failed"); const failed = uploads.items.filter((i) => i.status === "failed");
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length; const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
@@ -358,7 +362,13 @@ export function LibraryPage() {
{t.importPhotos} {t.importPhotos}
</button> </button>
{uploadInto && ( {uploadInto && (
<button onClick={() => setCardOpen(true)} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"> <button
onClick={() => {
const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events;
openFolderScan(uploadInto, games);
}}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
{t.cardScan.button} {t.cardScan.button}
</button> </button>
)} )}
@@ -581,16 +591,6 @@ export function LibraryPage() {
onPlayers={(ids, players) => patch(ids, { players })} onPlayers={(ids, players) => patch(ids, { players })}
/> />
{cardOpen && uploadInto && openEvent && (
<CardScan
api={api}
orgId={orgId}
eventId={uploadInto}
games={events.some((e) => e.id === openEvent.id) ? events : [openEvent, ...events]}
onImport={(files, id) => uploads.add(files, id)}
onClose={() => setCardOpen(false)}
/>
)}
{iptcOpen && <IptcInfo api={api} orgId={orgId} photos={selection} targets={targets} canDeliver={canCull} onClose={() => setIptcOpen(false)} />} {iptcOpen && <IptcInfo api={api} orgId={orgId} photos={selection} targets={targets} canDeliver={canCull} onClose={() => setIptcOpen(false)} />}
{creating && ( {creating && (
<EventForm <EventForm
+4 -1
View File
@@ -6,6 +6,7 @@ import { Logo } from "../components/ui.js";
import { t } from "../i18n.js"; import { t } from "../i18n.js";
import { LocalDeliveries } from "../desktop/localDeliveries.js"; import { LocalDeliveries } from "../desktop/localDeliveries.js";
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js"; import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
import { FolderScanProvider } from "../library/folderScan.js";
import { IngestProvider } from "../library/ingest.js"; import { IngestProvider } from "../library/ingest.js";
const moduleClass = ({ isActive }: { isActive: boolean }) => const moduleClass = ({ isActive }: { isActive: boolean }) =>
@@ -127,7 +128,9 @@ export function Shell() {
<LocalDeliveries /> <LocalDeliveries />
<main className="min-h-0 flex-1 overflow-auto"> <main className="min-h-0 flex-1 overflow-auto">
<IngestProvider> <IngestProvider>
<Outlet /> <FolderScanProvider>
<Outlet />
</FolderScanProvider>
</IngestProvider> </IngestProvider>
</main> </main>
</div> </div>
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@photoreport/desktop", "name": "@photoreport/desktop",
"version": "0.3.14", "version": "0.3.16",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "photoreport-desktop" name = "photoreport-desktop"
version = "0.3.14" version = "0.3.16"
edition = "2024" edition = "2024"
publish = false publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine." description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
+26
View File
@@ -47,4 +47,30 @@ fn main() {
]), ]),
)) ))
.expect("failed to run tauri-build"); .expect("failed to run tauri-build");
link_coreml_compiler_rt();
}
/// ONNX Runtime's Core ML objects call `___isPlatformVersionAtLeast`. That helper lives in compiler-rt, which Rust's
/// linker does not pull in, so the desktop build (deployment target 11) fails on the arm64 slice.
fn link_coreml_compiler_rt() {
let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
if os != "macos" || arch != "aarch64" {
return;
}
let Ok(output) = std::process::Command::new("xcrun")
.args(["--sdk", "macosx", "clang", "-print-file-name=libclang_rt.osx.a"])
.output()
else {
return;
};
if !output.status.success() {
return;
}
let path = String::from_utf8(output.stdout).unwrap_or_default();
let path = path.trim();
if path.is_empty() || !std::path::Path::new(path).is_file() {
return;
}
println!("cargo:rustc-link-arg={path}");
} }
+60 -11
View File
@@ -10,7 +10,8 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::{Duration, UNIX_EPOCH}; use std::io::Write;
use std::time::{Duration, Instant, UNIX_EPOCH};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@@ -284,6 +285,18 @@ fn cpu_used(prev: &mut Option<(u64, u64)>) -> Option<f64> {
used used
} }
#[derive(Clone, Serialize)]
struct Prepare {
step: &'static str,
done: u64,
total: u64,
}
/// What the window is waiting on before the first photo. The clock itself runs in the page.
fn emit_prepare(app: &AppHandle, step: &'static str, done: u64, total: u64) {
let _ = app.emit("faces-prepare", Prepare { step, done, total });
}
fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cached: bool, needs_name: bool, error: bool, roster: Option<i32>, thumb: &[u8], faces: Vec<ScanFace>) { fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cached: bool, needs_name: bool, error: bool, roster: Option<i32>, thumb: &[u8], faces: Vec<ScanFace>) {
let n = done.fetch_add(1, Ordering::Relaxed) + 1; let n = done.fetch_add(1, Ordering::Relaxed) + 1;
let name = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); let name = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
@@ -304,7 +317,7 @@ fn emit_one(app: &AppHandle, done: &AtomicUsize, total: usize, path: &Path, cach
); );
} }
async fn ensure_models(api: &str, token: &str, org_id: &str) -> Result<PathBuf, String> { async fn ensure_models(app: &AppHandle, cancel: &AtomicBool, api: &str, token: &str, org_id: &str) -> Result<PathBuf, String> {
let dir = models_dir(); let dir = models_dir();
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
if MODEL_FILES.iter().all(|name| dir.join(name).is_file()) { if MODEL_FILES.iter().all(|name| dir.join(name).is_file()) {
@@ -312,24 +325,53 @@ async fn ensure_models(api: &str, token: &str, org_id: &str) -> Result<PathBuf,
} }
let http = crate::ui::http_client(600)?; let http = crate::ui::http_client(600)?;
for name in MODEL_FILES { for name in MODEL_FILES {
if cancel.load(Ordering::Relaxed) {
return Err("cancelled".into());
}
let dest = dir.join(name); let dest = dir.join(name);
if dest.is_file() { if dest.is_file() {
continue; continue;
} }
let url = format!("{}/v1/orgs/{org_id}/faces/models/{name}", api.trim_end_matches('/')); let url = format!("{}/v1/orgs/{org_id}/faces/models/{name}", api.trim_end_matches('/'));
let res = http.get(url).bearer_auth(token).send().await.map_err(|e| e.to_string())?; download_model(app, cancel, &http, &url, &dest, token).await?;
if !res.status().is_success() {
return Err(format!("models_{}", res.status().as_u16()));
}
let bytes = res.bytes().await.map_err(|e| e.to_string())?;
let tmp = dest.with_extension("part");
std::fs::write(&tmp, &bytes).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, &dest).map_err(|e| e.to_string())?;
} }
Ok(dir) Ok(dir)
} }
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
/// The recogniser is about 250 MB. Report bytes so the wait is not a frozen sentence.
async fn download_model(app: &AppHandle, cancel: &AtomicBool, http: &reqwest::Client, url: &str, dest: &Path, token: &str) -> Result<(), String> {
let mut res = http.get(url).bearer_auth(token).send().await.map_err(|e| e.to_string())?;
if !res.status().is_success() {
return Err(format!("models_{}", res.status().as_u16()));
}
let total = res.content_length().unwrap_or(0);
let tmp = dest.with_extension("part");
let mut file = std::fs::File::create(&tmp).map_err(|e| e.to_string())?;
let mut got = 0u64;
let mut last = Instant::now();
emit_prepare(app, "download", 0, total);
while let Some(chunk) = res.chunk().await.map_err(|e| e.to_string())? {
if cancel.load(Ordering::Relaxed) {
let _ = std::fs::remove_file(&tmp);
return Err("cancelled".into());
}
file.write_all(&chunk).map_err(|e| e.to_string())?;
got += chunk.len() as u64;
if last.elapsed() >= Duration::from_millis(400) {
emit_prepare(app, "download", got, total);
last = Instant::now();
}
}
file.flush().map_err(|e| e.to_string())?;
drop(file);
emit_prepare(app, "download", got, if total == 0 { got } else { total });
std::fs::rename(&tmp, dest).map_err(|e| e.to_string())?;
Ok(())
}
fn run_jobs(dir: PathBuf, jobs: Arc<Mutex<Vec<Job>>>, cancel: Arc<AtomicBool>, app: AppHandle, done: Arc<AtomicUsize>, total: usize, accel: Option<Arc<Accel>>) { fn run_jobs(dir: PathBuf, jobs: Arc<Mutex<Vec<Job>>>, cancel: Arc<AtomicBool>, app: AppHandle, done: Arc<AtomicUsize>, total: usize, accel: Option<Arc<Accel>>) {
emit_prepare(&app, "load", 0, 0);
let engine = match Engine::load(&dir, "auraface", 0.6) { let engine = match Engine::load(&dir, "auraface", 0.6) {
Ok(engine) => engine, Ok(engine) => engine,
Err(err) => { Err(err) => {
@@ -369,6 +411,7 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
if !root.is_dir() { if !root.is_dir() {
return Err("not_a_folder".into()); return Err("not_a_folder".into());
} }
emit_prepare(&app, "list", 0, 0);
let mut files = Vec::new(); let mut files = Vec::new();
jpeg_paths(&root, &mut files); jpeg_paths(&root, &mut files);
let total = files.len(); let total = files.len();
@@ -383,10 +426,13 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String,
} }
pending.push(Job { path, key }); pending.push(Job { path, key });
} }
emit_prepare(&app, "list", total as u64, total as u64);
if pending.is_empty() || cancel.load(Ordering::Relaxed) { if pending.is_empty() || cancel.load(Ordering::Relaxed) {
return Ok(()); return Ok(());
} }
let jobs = Arc::new(Mutex::new(pending)); let jobs = Arc::new(Mutex::new(pending));
// Core ML compiles the recogniser the first time. That is the long silent stretch.
emit_prepare(&app, "gpu", 0, 0);
let accel = crate::accel::open(&models); let accel = crate::accel::open(&models);
let accelerators = accel.as_ref().map(|item| item.label()).unwrap_or("cpu"); let accelerators = accel.as_ref().map(|item| item.label()).unwrap_or("cpu");
let _ = app.emit("faces-accel", AccelStatus { accelerators }); let _ = app.emit("faces-accel", AccelStatus { accelerators });
@@ -450,7 +496,10 @@ pub fn faces_cancel(state: tauri::State<'_, FaceScan>) {
pub async fn faces_scan(app: AppHandle, state: tauri::State<'_, FaceScan>, folder: String, org_id: String, event_id: String, api: String, token: String) -> Result<(), String> { pub async fn faces_scan(app: AppHandle, state: tauri::State<'_, FaceScan>, folder: String, org_id: String, event_id: String, api: String, token: String) -> Result<(), String> {
state.cancel.store(false, Ordering::Relaxed); state.cancel.store(false, Ordering::Relaxed);
let cancel = state.cancel.clone(); let cancel = state.cancel.clone();
let models = ensure_models(&api, &token, &org_id).await?; let models = match ensure_models(&app, &cancel, &api, &token, &org_id).await {
Err(err) if err == "cancelled" => return Ok(()),
other => other?,
};
let cancel2 = cancel.clone(); let cancel2 = cancel.clone();
tauri::async_runtime::spawn_blocking(move || scan_folder(app, folder, org_id, event_id, models, cancel2)) tauri::async_runtime::spawn_blocking(move || scan_folder(app, folder, org_id, event_id, models, cancel2))
.await .await
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport", "productName": "PhotoReport",
"version": "0.3.14", "version": "0.3.16",
"identifier": "pt.photoreport.desktop", "identifier": "pt.photoreport.desktop",
"build": { "build": {
"devUrl": "http://localhost:5173", "devUrl": "http://localhost:5173",