Files
photoreport/docs/ARCHITECTURE.md
T
sparkandClaude Opus 5.5 57ed2154be
ci / rust (push) Successful in 6m54s
ci / typescript (push) Successful in 7m47s
feat(faces): shirt numbers from our own model
Torso crops reviewed in the app; a ResNet18 trained on Mac (MPS) and exported to ONNX.
The worker reads numbers when JERSEY_MODEL_DIR is set.
A group with no face match is suggested a player by shirt number when exactly one player of the two teams wears it.
The faces worker now applies EXIF orientation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-11 23:31:00 +01:00

16 KiB
Raw Blame History

Architecture

Living plan (Portuguese, editable): https://claude.ai/code/artifact/f64515d2-9d1f-47d5-ade1-743511fb3da2 This file is the in-repo summary agents work from. Decisions dated 2026-10-11.

Decisions

  • One monorepo, one API, one PostgreSQL database, one account system, one UI for web and desktop.
  • Built greenfield on new containers and the next environment; old projects keep running until cutover. Final domain: app.photoreport.pt. Data (accounts, galleries, sales, squads) is imported, not restarted.
  • Desktop = Tauri around the same React SPA (replaces the Flutter Studio).
  • Develop engine = LightCraft crates (lightcraft-develop, lightcraft-pipeline, lightcraft-raw, lightcraft-codecs, lightcraft-faces), pinned, behind engine/core. Not lightcraft-engine/catalog: our catalog is the API.
  • Faces: lightcraft-faces (YuNet detection + AuraFace v1 recognition, SFace optional; pure Rust) in workers/faces, a long-running process the background worker talks to over stdin/stdout. See "Faces" below. Enabled for FPA (own photos, internal federation use for news and galleries); off by default elsewhere.
  • Jersey numbers: PaddleOCR in workers/ml, matched against the squad. OpenAI fallback off by default.
  • CPU: no practical limit; workers scale to whatever cores are needed. Speed first.
  • Priority cameras: Canon EOS R1 and R3, then pro Canon, Sony and Nikon bodies used by photojournalists.

Stack

Node 22 + TypeScript + Fastify · PostgreSQL 17 + pgvector · Prisma · queues as PostgreSQL tables (FOR UPDATE SKIP LOCKED) · Socket.io fanned out with LISTEN/NOTIFY · sharp + ExifTool · local storage now, Garage (S3-compatible) later · SFTPGo (tusd later) · React + Vite + Tailwind (apps/app) · Next.js (apps/site) · Tauri 2 (apps/desktop) · Rust (engine, workers/render) · Python (workers/ml).

Realtime edits (Revelar)

One engine everywhere: engine/core wraps the LightCraft develop crates (settings, commands, decode, render). It runs natively in workers/render and in the browser as WASM (engine/wasm, about 2.5 MB, built into apps/app/public/engine/ and loaded by a Web Worker), so the desktop app (the web app in a Tauri shell) and the browser show the same pixels.

  • A window sends edit commands (never pixels) with POST /v1/photos/:id/edits ({clientId, ops: [{opId, command}]}). The API checks them against the pinned control list (controls.generated.json), assigns the per-photo seq under a row lock, stores them in photo_edits (a retried opId is stored once) and fans them out as photo.edited on the library channel. Last writer wins per control.
  • Each window replays the log with its own engine: confirmed settings plus its own unacknowledged edits on top, so edits show at once and remote ones slot in underneath. A gap in seq (lost message, reconnect) fetches GET /v1/photos/:id/develop?since=<seq>. Unsent edits stay in a per-photo outbox in local storage and are retried with back-off, so editing offline works and survives a reload.
  • Slider drags: the queued op is replaced until it is sent (about one op per 120 ms on the wire), one undo step per drag. Undo/redo are new ops that put the previous values back.
  • The worker keeps a settings snapshot per photo (develop_snapshot, snapshot_seq) and, two seconds after edits stop, renders edited thumb and preview from the original (photo.rendered with new URLs; source stays the unedited preview the editor renders on). Deliveries of edited photos are rendered by the engine from the original at the delivery size, camera EXIF copied back, orientation reset, IPTC written as before.
  • Measured: decode of a 24 MP JPEG to 2048 px about 0.5 s and a 1600 px render about 0.25 s in WASM (one thread); a 4000 px delivery render about 2 s natively.

Uploads and ingest

Camera -> SFTPGo (FTP/SFTP) into <INGEST_ROOT>/<ftp login>/. Each login is tied to one member of one organization (ftp_accounts, managed by admins). The worker (apps/api/src/worker.ts) picks a file up once its size and time stop changing, hashes it (duplicates are dropped), reads EXIF (capture time in Lisbon time unless the camera wrote an offset; a per-login clock offset fixes drifting bodies), routes it to the event the photographer is assigned to whose ingest window (default: 2 h before to 4 h after the start) holds the capture time, or to the inbox, moves it into storage and makes a 480 px thumb and a 2048 px preview. Unreadable files are kept and marked failed; non-JPEG and unknown logins are set aside in _unsupported/ and _unclaimed/. Measured locally: a dropped JPEG shows up in an open browser in about 2 s.

Uploads from the browser or desktop (POST /v1/orgs/:orgId/uploads, one photo per request) go through the same pipeline; an upload can target an open event directly. Still to come: resumable uploads (tus, preview first from the desktop), OCR and faces at ingest, and the final export replaying the edit op log (phase 2). Files live on local disk behind LocalStorage (originals and derivatives per organization); the API and the worker share that folder (Proxmox bind mount). Garage replaces it when files must be served from more than one host.

Galleries and shop

  • Sites: each domain (photoreport.pt, shootyourmove.com, ...) is a sites row: organization, skin (photoreport editorial light, shootyourmove dark with red) and texts. apps/site (Next.js) is one build for every domain; it asks the API with x-site-domain and proxies /v1 so browsers stay on the site's origin.
  • Galleries are made in the app (Vendas, or "Adicionar à galeria" on a library selection), usually from an event with its picks. Public (listed), unlisted (link only) or private (link + password; the unlock returns a token valid for a week, kept in a cookie). Photos on the sites are watermarked with the site's name (600 and 1600 px), made on first view from the edited preview and cached until the edit changes; URLs are signed.
  • Products per organization: JPEG downloads (long edge, 0 = original) and prints (size, lead days); prices are gross. Orders keep a copy of names and prices. VAT: seller's rate inside the price; EU businesses with a VIES-valid number from another member state get reverse charge (net price). OSS for EU consumers is not applied.
  • Payments: the organization's own Stripe account (keys sealed with AES-GCM), hosted Checkout with the methods switched on in its dashboard (cards; Multibanco and MB WAY where Stripe offers them). Webhooks (/v1/public/stripe/:orgId/webhook, signature checked over the raw body) mark orders paid, including late Multibanco payments. Free-download galleries skip payment for digital files.
  • Fulfilment: the worker renders each bought JPEG from the original with the photo's edit and full IPTC at the product's size (never enlarged), then emails the buyer the order link (SMTP). Downloads are counted (20 max). Prints are marked shipped in the app; the order closes when everything is done.

On-site printing

  • Print events (Impressão in the app) have a QR code to events.photoreport.pt/e/<slug> (apps/site). Guests send a photo from the phone or pick one of the photographer's (a gallery linked to the event); each becomes a print-ready JPEG at 300 dpi in the photo's orientation (cropped around what matters), with an optional border and a band with the event's text. Optional approval per photo and a limit per guest (a random key per phone).
  • Stations run apps/print-agent (CUPS) and pair with a one-time code (15 minutes) for a bearer token stored hashed. Every 15 s they report their printers; they claim the oldest queued job for a printer that has the job's paper loaded (operators tick sizes per printer), print with lp, and report the result (three tries, then failed; reprint from the app). The app's queue and the guest's page update live.

Faces

Only for organizations whose owner switched it on with a recorded legal basis (biometric data, GDPR art. 9). Each photo that arrives is queued (photos.faces_status); the worker runs workers/faces on the original: YuNet finds faces, each is aligned to the ArcFace template and embedded by AuraFace (512 numbers, Apache-2.0; model files pinned and checked by SHA-256, infra/faces/download-models.sh). Faces of the same person within an event are grouped (cosine to the group's mean, threshold per model). An editor names a group once (the "Caras" view of the library, or a suggestion from people confirmed in earlier events), and every photo with a face in it gets the name in Players, which goes to IPTC Title and Persons Shown; photos that arrive later and join the group are named on arrival. Suggestions never name photos on their own. Groups can be merged or ignored (public, staff). Measured locally on 2 cores: about 1 s per photo with AuraFace.

Shirt numbers come from our own model, because general OCR doesn't read shirts. The torso under each confirmed face becomes a training sample, labelled with the squad's number. People check these samples in "Números das camisolas". workers/ml/jersey trains a ResNet18 on the checked samples (on a Mac with MPS) and exports it to ONNX.

With JERSEY_MODEL_DIR set, the worker reads the number of every clear face through onnxruntime-node, on the CPU. A group's number is the one more than half of its clear readings agree on; it is shown as #10 on the group.

When a group has no face match, it is suggested as the squad player who wears that number in either team of the event. This happens only when exactly one player matches, and the score is 0.9 × the mean reading. Suggestions still never name anyone on their own.

Next: back-of-shirt numbers. These are players with no face visible, and they need a box detector trained on hand-drawn boxes.

Library realtime

Socket.io on the API (/v1/realtime, WebSocket only, access token in the handshake, one room per organization). Every message goes through PostgreSQL LISTEN/NOTIFY (photoreport_realtime): the worker and every API process publish, every API process delivers to its own sockets. No Redis/Valkey and no sticky sessions needed. Messages: photo.added, photo.updated (culling, players), delivery.updated.

Client delivery (Nextcloud)

PhotoReport storage is the source of truth; Nextcloud receives organised copies. Any client organization can have one or more destinations on any Nextcloud instance, each with its own folder and file-name templates (variables from packages/metadata). Default delivery: final edited JPEG, 4000 px long edge, maximum quality. Implemented (apps/api/src/delivery): editors send picks to a target; each photo becomes a queue item with its {n} fixed at that moment (capture order, never reused). The worker renders it (oriented, 4000 px, JPEG 100 4:4:4, camera EXIF and ICC kept, IPTC written to IIM and XMP with ExifTool), creates the folders (WebDAV MKCOL) and uploads (PUT), up to 4 at a time, retrying network and server errors with back-off (5 attempts); authentication and template errors fail at once. App passwords are stored encrypted (AES-256-GCM, DELIVERY_SECRET_KEY). Editors can create a read-only public link to an event folder (OCS). Large files may later need WebDAV chunked upload.

Instance Client Folders today Files
cloud.photoreport.pt FPA /FPA/Fotos/2026_2027/Competições Nacionais/PO01 - Campeonato Betclic/20260923 - VSC x AAAS/ PS_<Home> x <Away>_<n>.jpg
liga.photoreport.pt Liga Portugal /LPBetclic 25-26/Jornada 1/1. Casa Pia x Sporting/; institutional events at root camera name (JMA27728.jpg)

Archive import: folder names changed across seasons (LPbwin - 22-23, LPBetclic 2023-24, LPBetclic - 24-25, LPBetclic 25-26), so the importer proposes a folder -> competition/match mapping that an editor confirms before import.

Editor scope

JPEG first: most event and match photographers shoot JPEG for speed, so JPEG must be perfect before RAW. Default editor modules: Crop (with straighten and aspect presets) and Basic (white balance, exposure, contrast, highlights, shadows, whites, blacks, texture, clarity, dehaze, vibrance, saturation). Every other LightCraft module (curves, colour mixer, grading, masks, detail, optics...) is available but off by default; each user chooses which panels to show, and the choice syncs across their devices.

RAW support (secondary; LightCraft rev pinned in Cargo.toml, checked 2026-10-11)

  • Canon EOS R1, R3 (CR3): unverified; lossless and single-tile C-RAW decode, other CRX variants fall back to the embedded preview. No measured Canon colour calibration yet.
  • Nikon Z 9, Z 8: NEF decodes except High Efficiency (HE / HE*), which is preview-only.
  • Sony A9 / A9 II / A9 III: verified. Action (low priority): collect real files from each body, add them to our reference set, contribute samples upstream.

Status

Phase 0 code is in place and verified: accounts, organizations and roles, web login (httpOnly refresh cookie, rotation with reuse detection), desktop login through the browser (device authorization) with the keychain, synced editor-panel preferences, deploy receiver and script. Remaining for phase 0: create the next containers and webhooks (docs/DEPLOY.md), and macOS/Windows runners for desktop installers.

Phase 1 so far (verified end to end locally: FTP drop -> live grid -> keyboard culling -> players by code -> IPTC preview -> delivery into the FPA folder layout): events with agenda and IPTC template, FTP ingest and routing, previews, the library (Lightroom-style grid and loupe, P/X/U, stars, colour labels, filters, live updates), code replacements, IPTC with the fields of the current Photo Mechanic pad (packages/metadata), Nextcloud delivery queue and share links, the per-event IPTC pad (same fields and order as Photo Mechanic), and admin screens for delivery targets (FPA and Liga presets) and FTP logins, uploads from the browser (drag and drop or Importar, 4 in parallel with progress, same pipeline as FTP), and the IPTC already in incoming files (XMP first; IIM written by Lightroom/Photo Mechanic on the Mac without a charset flag is read as Mac Roman), shown next to ours. SFTPGo authenticates cameras against the API (external auth hook; passwords made in the app). Browser and desktop uploads go in 4 MB chunks and resume after a dropped connection or a reload. Still open in phase 1: a real match run on the next containers (the phase gate).

Phases (gate to pass)

  1. Foundation: monorepo, CI, next containers, accounts, organizations, tokens (login on web and desktop).
  2. Ingest + library: SFTPGo/tus, routing, previews, IPTC, code replacements, culling, Nextcloud delivery (a real match arrives captioned and delivered with no manual step).
  3. Synced editor (done: WASM and native engine, op log, live sync, offline outbox, render worker, edited deliveries, crop with aspect presets and straighten, Basic and optional modules, copy/paste settings).
  4. Galleries and sales (done: both storefront skins, public/unlisted/private galleries, watermarks, cart, Stripe Checkout and webhooks, VIES reverse charge, rendered downloads with IPTC, order emails, print fulfilment, admin in the app. Open: invoicing software integration, photographer payouts, affiliates, press accounts, data import from the old storefront).
  5. Events and printing (done: QR guest page, print layout with band and border, approval and limits, queue in the app, print agent with CUPS and pairing, paper per printer, paid prints through Stripe. Open: kiosk mode on a tablet, photobooth capture, Windows agent, a real event printed).
  6. Player identification: faces (done: detect, group, confirm, propagate, suggest across events), jersey numbers with squads, global search (parity with old projects validated).
  7. Cutover: final import, redirects, old projects read-only, then switched off.

Deploy

Push to main -> Gitea webhook per container -> pull, build, migrate, reload, health check, auto-rollback. Details: docs/DEPLOY.md.

Infrastructure (next)

Container Services Domain
pr-api apps/api + Socket.io (2 instances) api.next.photoreport.pt
pr-ingest SFTPGo + photoreport-worker (ingest + delivery) ftp.next.photoreport.pt (DNS-only)
pr-app apps/app static app.next.photoreport.pt
pr-site apps/site next.photoreport.pt + brand domains
pr-db PostgreSQL 17 + pgvector, pgBackRest internal
pr-storage /srv/photoreport-data bind mount shared by pr-api and pr-ingest (Garage later) internal
pr-workers workers/media + workers/render internal
pr-ml workers/ml internal