From b86f4f4c2e30b909963df30c2cb88d4b4d697ac1 Mon Sep 17 00:00:00 2001 From: spark Date: Fri, 6 Nov 2026 20:38:57 +0000 Subject: [PATCH] fix(faces,app): prefer clear jersey #; PhotoReport photo context menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A detected face with a clear shorts number and no similar person was left unnamed when the face path won by default. Clear readings now drive the suggestion. Right-click no longer opens the webview image menu — pick, reject, IPTC, remove, etc. --- apps/api/src/faces/service.ts | 38 +++++++++---- apps/api/test/faces.test.ts | 52 +++++++++++++++++ apps/app/src/i18n.ts | 9 +++ apps/app/src/library/Grid.tsx | 67 ++++++++++++++++++++-- apps/app/src/library/PhotoContextMenu.tsx | 69 +++++++++++++++++++++++ apps/app/src/pages/LibraryPage.tsx | 59 ++++++++++++++++++- docs/ARCHITECTURE.md | 3 +- 7 files changed, 276 insertions(+), 21 deletions(-) create mode 100644 apps/app/src/library/PhotoContextMenu.tsx diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 17005ae..81817be 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -600,20 +600,24 @@ export class FaceService { .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 >= floor && (!second || first.s - second.s >= gap); - let suggestedPersonId = ok ? first.p.id : null; - let suggestionScore = ok ? first.s : null; + const ok = !!(first && first.s >= floor && (!second || first.s - second.s >= gap)); + let suggestedPersonId: string | null = null; + let suggestionScore: number | null = null; const read = await this.groupNumber(g.id); - const firstNumber = ok && read ? (await numberOf([first.p.id])).get(first.p.id) : null; - if (ok && read && firstNumber && firstNumber !== read.number && read.votes >= 2) { - // The face says one person, the shirt clearly says another number: still suggested, but as less sure. - suggestionScore = Math.round(first.s * 0.8 * 1000) / 1000; - } else if (ok && read && firstNumber === read.number) { + const firstNumber = first && read ? (await numberOf([first.p.id])).get(first.p.id) ?? null : null; + const faceAgrees = ok && !!read && firstNumber === read.number; + // Clear shirt, face not the wearer (or no face match, or the face's person has no number here): the number wins. + // A single clear reading is enough — waiting for two left a lone #9 on the shorts unnamed. + const preferNumber = + !!read && + allowNumber && + (!ok || faceAgrees === false || (ok && firstNumber == null)); + if (faceAgrees && first && read) { // Face and shirt agree on the same player: surer than either alone. + suggestedPersonId = first.p.id; suggestionScore = Math.round(Math.min(0.99, first.s + 0.15 * read.score) * 1000) / 1000; - } 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. + } else if (preferNumber && read) { + // The number decides among faces that look near, then the squad who wears it (kit colour if both teams). 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); @@ -626,10 +630,20 @@ export class FaceService { suggestedPersonId = near[0]!.p.id; suggestionScore = Math.round(Math.max(near[0]!.s, read.score * 0.9) * 1000) / 1000; } else { - // No face to go by: the number (and, when both teams have it, the colour of the kit). const byNumber = ctx ? await this.suggestByNumber(g.id, ctx, read) : null; if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber); } + // Number found nobody: keep a sure face, but quieter when the shirt disagreed. + if (!suggestedPersonId && ok && first) { + suggestedPersonId = first.p.id; + suggestionScore = + firstNumber && firstNumber !== read.number + ? Math.round(first.s * 0.8 * 1000) / 1000 + : first.s; + } + } else if (ok && first) { + suggestedPersonId = first.p.id; + suggestionScore = first.s; } if (suggestedPersonId && (rejected?.has(suggestedPersonId) || off.has(suggestedPersonId))) { suggestedPersonId = null; diff --git a/apps/api/test/faces.test.ts b/apps/api/test/faces.test.ts index b9ed907..8eb13b3 100644 --- a/apps/api/test/faces.test.ts +++ b/apps/api/test/faces.test.ts @@ -401,6 +401,58 @@ describe("faces", () => { expect(groups[0]!.person).toBeNull(); expect((await ctx.db.photo.findMany({ select: { players: true } })).every((p) => p.players.length === 0)).toBe(true); }); + + it("names from a clear shirt number when the face has nobody close (the #9 on the shorts)", async () => { + const { token, day1, orgId } = await setup(); + await ctx.db.person.createMany({ + data: [ + { organizationId: orgId, name: "Avançado Nove", club: "VSC", number: "9" }, + { organizationId: orgId, name: "Rui Costa", club: "VSC", number: "10" }, + ], + }); + // Face of someone never confirmed (no similar person); the shorts clearly read 9. + const reader = { + read: async (_file: string, box: { y0: number }) => + box.y0 > 0.4 ? { number: "9", score: 0.92 } : { number: null, score: 0.9 }, + }; + const withNumbers = new FaceService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), broadcaster, log: quiet, engine, jersey: reader }); + await photo("2026:09:23 21:05:00", [42]); + for (let ids = await withNumbers.claim(10); ids.length; ids = await withNumbers.claim(10)) for (const id of ids) await withNumbers.process(id); + const { groups } = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { + groups: { suggestion: { name: string } | null; number: { value: string } | null; person: unknown }[]; + }; + expect(groups[0]!.number).toMatchObject({ value: "9" }); + expect(groups[0]!.suggestion).toMatchObject({ name: "Avançado Nove" }); + expect(groups[0]!.person).toBeNull(); + }); + + it("prefers the clear shirt number over a face that matches someone else", async () => { + const { token, day1, day2, orgId } = await setup(); + await photo("2026:09:23 21:00:00", [1]); + await drain(); + const listed = (eventId: string) => + ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/face-groups`, headers: bearer(token) }).then( + (r) => r.json() as { groups: { id: string; suggestion: { name: string } | null }[] }, + ); + const [g] = (await listed(day1.id)).groups; + await ctx.app.inject({ + method: "POST", + url: `/v1/face-groups/${g!.id}/confirm`, + headers: bearer(token), + payload: { name: "Miguel Silva", club: "ABC", number: "7" }, + }); + // Same club as day2's home so suggestByNumber can find them on that game. + await ctx.db.person.create({ data: { organizationId: orgId, name: "Avançado Nove", club: "ABC", number: "9" } }); + // A week later: the face alone looks like Miguel, but the shirt reads 9 — the number wins. + await photo("2026:09:30 21:00:00", [1]); + await drain(); + const later = (await listed(day2.id)).groups[0]!; + expect(later.suggestion!.name).toBe("Miguel Silva"); + await ctx.db.face.updateMany({ where: { groupId: later.id }, data: { jerseyNumber: "9", jerseyScore: 0.93 } }); + await faces.refreshSuggestions(day2.id); + expect((await listed(day2.id)).groups[0]!.suggestion).toMatchObject({ name: "Avançado Nove" }); + }); + it("tells apart two players with the same number, one per team, by the colour of the kit", async () => { const { token, day1, orgId } = await setup(); const team = (name: string, ext: string) => ctx.db.sportsTeam.create({ data: { provider: "FPA", externalId: ext, sport: "handball", name, slug: name.toLowerCase() } }); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 85c32c3..bb4d831 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -52,6 +52,15 @@ export const t = { }, removeFromEventHelp: "Ficam em Sem evento. Não são apagadas da biblioteca. O que já foi enviado sai desse destino.", removedFromEvent: (n: number) => (n === 1 ? "1 foto retirada do evento" : `${n} fotos retiradas do evento`), + photoMenu: "Fotografia", + photoMenuPick: "Escolher", + photoMenuReject: "Rejeitar", + photoMenuClear: "Limpar marca", + photoMenuInfo: "Informação", + photoMenuRemove: "Tirar do evento", + photoMenuDevelop: "Revelar", + photoMenuLoupe: "Lupa", + photoMenuGrid: "Grelha", folderSheet: { opening: "A abrir a pasta…", close: "Fechar", diff --git a/apps/app/src/library/Grid.tsx b/apps/app/src/library/Grid.tsx index 47dfcca..bbef976 100644 --- a/apps/app/src/library/Grid.tsx +++ b/apps/app/src/library/Grid.tsx @@ -26,9 +26,10 @@ interface CellProps { focused: boolean; onPick: (id: string, e: React.MouseEvent) => void; onOpen: (id: string) => void; + onMenu?: (id: string, e: React.MouseEvent) => void; } -const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, onPick, onOpen }: CellProps) { +const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, onPick, onOpen, onMenu }: CellProps) { const ref = useRef(null); useEffect(() => { if (focused) ref.current?.scrollIntoView({ block: "nearest" }); @@ -60,6 +61,12 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o data-photo-id={photo.id} onClick={(e) => onPick(photo.id, e)} onDoubleClick={() => onOpen(photo.id)} + onContextMenu={(e) => { + if (!onMenu) return; + e.preventDefault(); + e.stopPropagation(); + onMenu(photo.id, e); + }} aria-pressed={selected} aria-label={`${photo.name}${photo.flag === "PICK" ? ", escolhida" : photo.flag === "REJECT" ? ", rejeitada" : ""}${photo.rating ? `, ${photo.rating} estrelas` : ""}`} className={`relative flex aspect-square flex-col items-center justify-between gap-1 border px-2 pb-1 pt-4 ${ @@ -75,7 +82,15 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o erro ) : shown ? ( - setImgFailed(true)} alt="" loading="lazy" decoding="async" draggable={false} className="block max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" /> + setImgFailed(true)} + alt="" + loading="lazy" + decoding="async" + draggable={false} + className="pointer-events-none block max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" + /> {softCrop && } ) : ( @@ -118,9 +133,15 @@ export function Grid(props: { srcFor: (photo: PhotoSummary) => string; onPick: (id: string, e: React.MouseEvent) => void; onOpen: (id: string) => void; + onMenu?: (id: string, e: React.MouseEvent) => void; }) { return ( -
+
e.preventDefault()} + > {props.photos.map((photo, index) => ( ))}
@@ -148,7 +170,23 @@ export interface LoupeFace { suggested: boolean; } -export function Loupe({ photo, src, fallback, index, total, faces = [] }: { photo: PhotoSummary; src: string; fallback?: string; index: number; total: number; faces?: LoupeFace[] }) { +export function Loupe({ + photo, + src, + fallback, + index, + total, + faces = [], + onMenu, +}: { + photo: PhotoSummary; + src: string; + fallback?: string; + index: number; + total: number; + faces?: LoupeFace[]; + onMenu?: (id: string, e: React.MouseEvent) => void; +}) { // Desktop app: previews seen once show again without a network; never seen, the thumbnail stands in. const preview = useCachedImage(src, isDesktop()); const thumb = useCachedImage(fallback ?? null, isDesktop() && !!fallback); @@ -170,9 +208,26 @@ export function Loupe({ photo, src, fallback, index, total, faces = [] }: { phot }, [photo.sha256]); const shown = (failed ? thumb : preview) ?? thumb ?? ""; return ( -
+
{ + if (!onMenu) { + e.preventDefault(); + return; + } + e.preventDefault(); + onMenu(photo.id, e); + }} + > - setFailed(true)} alt={photo.name} className="block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" /> + setFailed(true)} + alt={photo.name} + draggable={false} + className="pointer-events-none block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" + /> {softCrop && } {faces.map((f) => ( void; +} + +/** PhotoReport's own right-click menu — replaces the webview's "Open Image / Download / Copy". */ +export function PhotoContextMenu(props: { + x: number; + y: number; + actions: PhotoMenuAction[]; + onClose: () => void; +}) { + const ref = useRef(null); + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + props.onClose(); + } + }; + const onDown = (e: MouseEvent) => { + if (ref.current && !ref.current.contains(e.target as Node)) props.onClose(); + }; + window.addEventListener("keydown", onKey, true); + window.addEventListener("mousedown", onDown, true); + return () => { + window.removeEventListener("keydown", onKey, true); + window.removeEventListener("mousedown", onDown, true); + }; + }, [props.onClose]); + // Keep the menu on screen. + const left = Math.min(props.x, typeof window !== "undefined" ? window.innerWidth - 220 : props.x); + const top = Math.min(props.y, typeof window !== "undefined" ? window.innerHeight - props.actions.length * 32 - 16 : props.y); + return ( +
+ {props.actions.map((a) => ( + + ))} +
+ ); +} diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index 9ecf847..8679d7b 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -30,6 +30,7 @@ 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"; +import { PhotoContextMenu, type PhotoMenuAction } from "../library/PhotoContextMenu.js"; import { RemoveFromEventDialog } from "../library/RemoveFromEvent.js"; import { isEventScope, isRemoveKey, removeFromEvent } from "../library/remove.js"; import { initialLibrary, isMac, type LibraryFilter, libraryReducer, matchesFilter, patchForKey, pmPatchForKey } from "../library/store.js"; @@ -60,6 +61,7 @@ export function LibraryPage() { const [inboxCount, setInboxCount] = useState(0); const [targets, setTargets] = useState([]); const [iptcOpen, setIptcOpen] = useState(false); + const [photoMenu, setPhotoMenu] = useState<{ x: number; y: number; id: string } | null>(null); const { open: openFolderScan, syncGames } = useFolderScan(); const [state, dispatch] = useReducer(libraryReducer, initialLibrary); const [filter, setFilterState] = useState(() => savedFilter(orgId)); @@ -444,6 +446,13 @@ export function LibraryPage() { dispatch({ type: "select", id, mode: "single", visible: [] }); setLoupe(true); }, []); + const onPhotoMenu = useCallback( + (id: string, e: React.MouseEvent) => { + if (!state.selected.has(id)) dispatch({ type: "select", id, mode: "single", visible: visibleIds }); + setPhotoMenu({ x: e.clientX, y: e.clientY, id }); + }, + [state.selected, visibleIds], + ); // Face boxes and names over the loupe. useEffect(() => { setLoupeFaces([]); @@ -463,6 +472,32 @@ export function LibraryPage() { const srcFor = useCallback((p: PhotoSummary) => api.absolute(p.urls.thumb), [api]); + const photoMenuActions = useMemo((): PhotoMenuAction[] => { + if (!photoMenu || !canCull) return []; + const ids = selection.map((p) => p.id); + const inEvent = isEventScope(state.scope); + const actions: PhotoMenuAction[] = [ + { id: "pick", label: t.photoMenuPick, onSelect: () => void patch(ids, { flag: "PICK" }) }, + { id: "reject", label: t.photoMenuReject, onSelect: () => void patch(ids, { flag: "REJECT" }) }, + { id: "clear", label: t.photoMenuClear, onSelect: () => void patch(ids, { flag: "NONE" }) }, + { id: "info", label: t.photoMenuInfo, onSelect: () => setIptcOpen(true) }, + ]; + if (loupe) { + actions.push({ id: "grid", label: t.photoMenuGrid, onSelect: () => setLoupe(false) }); + } else if (focus) { + actions.push({ id: "loupe", label: t.photoMenuLoupe, onSelect: () => setLoupe(true) }); + actions.push({ + id: "develop", + label: t.photoMenuDevelop, + onSelect: () => navigate(`/develop/${focus.id}`), + }); + } + if (inEvent) { + actions.push({ id: "remove", label: t.photoMenuRemove, danger: true, onSelect: () => setRemoveOpen(true) }); + } + return actions; + }, [photoMenu, canCull, selection, state.scope, loupe, focus, patch, navigate]); + if (!organization) return

{t.noAccess}

; const picks = state.photos.filter((p) => p.flag === "PICK").length; @@ -753,10 +788,27 @@ export function LibraryPage() { ) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? ( ) : loupe && focus ? ( - + ) : visible.length || suggested.length ? ( <> - + {suggested.length > 0 && (

{state.scope === "face:" ? t.lookup.possible(suggested.length) : t.searchSuggested(suggested.length)}

@@ -783,6 +835,9 @@ export function LibraryPage() { onPlayers={(ids, players) => patch(ids, { players })} /> + {photoMenu && photoMenuActions.length > 0 && ( + setPhotoMenu(null)} /> + )} {removeOpen && isEventScope(state.scope) && (