Skip to content

Latest commit

 

History

History
319 lines (278 loc) · 18.2 KB

IMPLEMENTATION_PLAN.md

File metadata and controls

319 lines (278 loc) · 18.2 KB

MediaMind — Version 1 Implementation Plan

Status: Draft for review — no production code until approved Date: 2026-07-02 Related docs: PRD.md (what we're building), ../CLAUDE.md (project rules), ../prototype/HANDOFF.md (Version 0 context)

UI architecture update (2026-07-13): the renderer's UI layer is no longer the "libraries · scans · duplicate review · people" screen set shown in the diagram below — it was rebuilt as a full Windows Explorer clone (app/src/renderer/src/explorer/; see CLAUDE.md's Current State and docs/USER_GUIDE.md). The backend architecture (process split, HTTP/WS transport, localhost hardening, core/providers/store layout) described in this document is still accurate and still how the Explorer shell's own file operations, thumbnails, and metadata are served — only the renderer's top-level screen list is stale. The original screens still exist and still work; they're just not reachable from the Explorer shell yet (deliberately deferred, see docs/USER_GUIDE.md's "Where the older features went").


1. Architecture overview

Two cooperating processes, one desktop app:

┌───────────────────────────────────────────────────────────┐
│ Electron shell                                            │
│  ┌─────────────────────────────────────────────────────┐  │
│  │ React + TypeScript UI (renderer)                    │  │
│  │  Explorer shell (nav/tabs/views/search/file ops) ·  │  │
│  │  legacy libraries/scans/duplicate review/people      │  │
│  │  screens (built, not yet wired into the shell)       │  │
│  └───────────────▲─────────────────────────────────────┘  │
│                  │ HTTP (REST) + WebSocket (progress)     │
│  main process: window mgmt, native folder picker,         │
│  backend lifecycle (spawn/health-check/shutdown)          │
└──────────────────┼────────────────────────────────────────┘
                   │ 127.0.0.1 only, random port + token
┌──────────────────▼────────────────────────────────────────┐
│ Python backend — package `mediamind` (FastAPI)            │
│  api/        REST routes + WebSocket progress             │
│  core/       scanner · dedupe · faces · organizer · safety│
│             · explorer fs ops/search/gallery/oplog        │
│  providers/  face-model plugin system (ONNX)               │
│  store/      per-library SQLite index + embedding cache   │
└──────────────────┬────────────────────────────────────────┘
                   │
        User's real folders (source of truth)
        └── <library>/.mediamind/   index.db, manifests, undo data
        (Explorer file ops instead use an app-wide data dir —
         see docs/USER_GUIDE.md's "Where MediaMind stores its own data")

Why this shape (decisions and rationale):

  • Python owns all media/ML work. The proven V0 stack (InsightFace, ONNX Runtime, OpenCV, pillow-heif, scikit-learn) is Python. The Electron side never touches user media directly — every file operation goes through the backend's safety machinery, so there is exactly one code path that can modify files.
  • Electron + React for the UI (user decision). Thumbnail-heavy review screens are a web-UI strength; the contributor pool is the largest of any desktop stack. The footprint cost is accepted (the face model is ~300 MB anyway).
  • HTTP/WS rather than stdio IPC: independently testable backend (run it headless, hit it with pytest/httpx), natural fit for progress streaming, and it keeps a future CLI or alternative frontend possible without changes.
  • Localhost hardening: backend binds 127.0.0.1 on a random free port and requires a per-session token generated by the Electron main process — no other local process can drive it.
  • V0 is the seed, not a rewrite target. sort_media.py's loaders, frame samplers, routing logic, and safety machinery are ported module-by-module into core/, preserving behavior verified by the V0 author.

2. Repository / folder structure

Monorepo. Prototype scripts move to prototype/ (preserved, still runnable).

MediaMind/
├── CLAUDE.md
├── README.md                  # project-level readme (new)
├── LICENSE                    # Apache-2.0
├── docs/
│   ├── PRD.md
│   ├── IMPLEMENTATION_PLAN.md
│   ├── ARCHITECTURE.md        # living doc, grows with the code (M0+)
│   └── handoffs/              # session handoffs (see CLAUDE.md)
├── prototype/                 # V0, moved as-is in M0
│   ├── sort_media.py
│   ├── sort_faces.py
│   ├── README_sort_media.md
│   └── README_sort_faces.md
├── backend/
│   ├── pyproject.toml         # PEP 621; deps pinned, "numpy<2" until upstream fix
│   └── src/mediamind/
│       ├── api/               # FastAPI app, routes, WS progress, schemas (pydantic)
│       ├── core/
│       │   ├── scanner.py     # walk/classify (from V0 kind_of + walker)
│       │   ├── loaders.py     # image/HEIC/gif/video decode (from V0 loaders)
│       │   ├── dedupe.py      # content hash + perceptual hash grouping
│       │   ├── faces/
│       │   │   ├── engine.py      # detect→embed orchestration (provider-agnostic)
│       │   │   ├── clustering.py  # DBSCAN (from V0), known-people matcher
│       │   │   └── identities.py  # naming, merging, centroids
│       │   ├── organizer.py   # plan → preview → execute organize actions
│       │   └── safety.py      # copy-then-delete, _uniq, manifest, count check,
│       │                      #   trash integration, undo (from V0 deliver())
│       ├── providers/
│       │   ├── base.py        # FaceProvider interface
│       │   ├── registry.py    # catalog, download, checksum, license gate
│       │   └── insightface_onnx.py  # buffalo_l et al. via onnxruntime
│       └── store/
│           ├── db.py          # SQLite (schema + migrations)
│           └── embeddings.py  # cache keyed by (file content hash, provider id)
├── app/
│   ├── package.json
│   ├── electron/              # main process: window, folder picker, backend lifecycle
│   └── src/                   # React renderer
│       ├── api/               # typed client + React Query hooks
│       ├── stores/            # Zustand UI state
│       ├── features/          # library/ scan/ dedupe-review/ people/
│       │                      #   pending-review/ organize/ settings/
│       └── components/        # shared: thumbnail grid, progress, confirm dialogs
└── .github/workflows/         # CI (see §8)

This mirrors the modularity rule in CLAUDE.md: each core/ module is small, single-purpose, and testable without the UI or the model.

3. Technology stack

Layer Choice Rationale
Desktop shell Electron User decision; biggest ecosystem, mature packaging/updater.
UI React 18 + TypeScript (strict) + Vite Fast iteration, huge contributor pool.
UI components/styling Tailwind CSS + a lightweight headless kit (e.g., Radix) Modern look without a heavy framework; keep deps minimal.
Server state TanStack React Query Caching/refetching of backend resources; pairs naturally with REST.
UI state Zustand Minimal, no boilerplate, for selection sets and wizard state.
Backend Python 3.10+ / FastAPI / uvicorn Async, pydantic schemas double as API docs, trivially testable.
ML runtime onnxruntime (CPU default; GPU optional extra) V0-proven; provider models are ONNX.
Face stack (first provider) InsightFace buffalo_l (SCRFD detect + ArcFace embed) V0-validated, strong on Asian faces.
Clustering scikit-learn DBSCAN (cosine) V0-validated; discovers person count, marks noise.
Media decode OpenCV (video/images), Pillow + pillow-heif (HEIC/HEIF/AVIF, GIF) V0-proven loader chain incl. unicode-path fallbacks.
Dedupe hashing BLAKE2b (content), perceptual hash (pHash via imagehash or equivalent) Fast exact + robust near-dup for images.
Index SQLite (stdlib sqlite3, thin migration layer) Zero-dependency, per-library, rebuildable.
Trash send2trash Cross-platform recycle-bin removals (PRD F1.5).
Packaging PyInstaller (backend) + electron-builder (app + installer) Standard for this architecture; Windows first.

Dependency discipline (per CLAUDE.md): everything above is either already in V0 or earns its place; additions beyond this list need justification.

4. Data model & state

Filesystem is the source of truth. The index lives in <library>/.mediamind/ so it travels with the folder, and is always rebuildable by rescanning. It is a cache/index, never primary data.

SQLite schema (initial):

  • files — path, size, mtime, content_hash, kind, decode status
  • embeddings — file_id, frame_no, provider_id, vector (blob); keyed by content hash so renames/moves don't invalidate the cache (the V0 handoff's "biggest UX win")
  • faces — embedding row ↔ bbox ↔ person assignment (+ confidence)
  • persons — id, auto label (Person_001), user name, centroid, exemplar refs
  • duplicate_groups / duplicate_members — scan results + user choices
  • pending_matches — face→known-person suggestions awaiting confirmation (PRD F5)
  • organize_actions / manifest_entries — executed actions, per-file audit trail, undo data (PRD F6.3–F6.4)

Long-running work (scans, organize execution) runs in backend worker tasks; progress streams over WebSocket; scans are cancelable (PRD F1.6) and per-file-fault-isolated (V0 pattern).

5. Face-model provider plugin architecture

Goal (PRD F2): recognition models are configurable, downloadable, and license-gated. Design:

FaceProvider interface (providers/base.py):

class FaceProvider(Protocol):
    id: str                    # e.g. "insightface-buffalo-l"
    embedding_dim: int
    def load(self, model_dir: Path, ctx: ExecutionContext) -> None: ...
    def detect(self, frame_bgr: np.ndarray) -> list[DetectedFace]: ...   # bboxes
    def embed(self, frame_bgr: np.ndarray, face: DetectedFace) -> np.ndarray: ...

Provider manifest (JSON, one per catalog entry):

{
  "id": "insightface-buffalo-l",
  "name": "Asian faces (InsightFace buffalo_l)",
  "description": "Strong on Asian faces; trained on Glint360K.",
  "version": "1.0",
  "license": { "name": "Non-commercial research", "url": "...", "requires_ack": true },
  "files": [ { "url": "...", "sha256": "...", "size": 0 } ],
  "runtime": "onnx",
  "embedding_dim": 512
}

Rules:

  • The app ships no model. The catalog (a static JSON list bundled with the app, extendable by user-supplied manifest files) is the source of providers.
  • Download flow: show name/description/license → require acknowledgment if requires_ack → download with resume → verify sha256 → install to the app model dir → mark available offline.
  • Embeddings are stored per provider_id; clustering and known-people matching never mix providers (PRD F2.5).
  • The registry loads providers by manifest runtime — V1 implements the onnx runtime; new model families that fit ONNX need only a manifest, no code. Genuinely new runtimes implement FaceProvider.
  • Tests use a fake provider (deterministic synthetic embeddings) so the entire pipeline is testable with no model download (per prototype/HANDOFF.md §6).

6. Backend API surface (sketch)

Stable, versioned under /v1 (public-API rule in CLAUDE.md):

  • POST /v1/libraries · GET /v1/libraries — register/choose folders
  • POST /v1/libraries/{id}/scans (type: dedupe|faces) · GET .../scans/{id} · DELETE (cancel) — WS /v1/progress
  • GET /v1/libraries/{id}/duplicates · POST .../duplicates/resolutions (choices) · POST .../duplicates/execute (confirmed removal → trash)
  • GET /v1/libraries/{id}/persons · PATCH .../persons/{pid} (rename) · POST .../persons/merge
  • GET /v1/libraries/{id}/pending · POST .../pending/decisions (confirm/reject)
  • GET /v1/libraries/{id}/multi-person · POST .../multi-person/assignments (PRD F3)
  • POST /v1/libraries/{id}/organize/preview (dry-run plan) · POST .../organize/execute · POST .../organize/undo
  • GET /v1/providers · POST /v1/providers/{id}/download (license ack in body)
  • GET /v1/files/{id}/thumbnail — thumbnail service for the UI

7. Milestones & implementation order

Each milestone ends green (tests pass, app runs) and gets a session handoff.

  • M0 — Scaffolding. Monorepo layout per §2; move prototypes to prototype/; pyproject.toml + Electron/Vite scaffold; LICENSE, README; CI skeleton; backend "hello" endpoint reachable from a bare Electron window.
  • M1 — Backend core (port V0). loaders, scanner, safety ported from sort_media.py with behavior preserved; SQLite store + embedding cache; FaceProvider interface + fake provider; pytest suite for routing, _uniq, copy-then-delete, manifest, count check, dry-run. V0 parity is the exit criterion.
  • M2 — Duplicate engine. Content + perceptual hashing, grouping, "best copy" heuristic; trash-based removal via safety; API endpoints.
  • M3 — App shell. Electron main process (backend spawn/health/shutdown, folder picker), React shell, library management, scan launch + live progress.
  • M4 — Dedupe review UI. Group browser, few-click keep/remove flow, bulk rules, confirm dialog, execution + results. First end-to-end user value.
  • M5 — Face pipeline + people UI. Provider registry/catalog/download with license gate (buffalo_l first); face scan (images+GIF+video); clustering; people grid with face thumbnails; rename + merge (PRD F2, F4).
  • M6 — Review flows. Multi-person review screen (PRD F3); known-people matching with "(Pending)" confirm/reject (PRD F5); organize preview → confirm → execute (PRD F6).
  • M7 — Safety polish. Undo of last organize action; audit-trail viewer; cancel/resume hardening; corrupt-file UX; cross-platform pass (Linux, then macOS).
  • M8 — Release. Second ("General") provider with clear license; PyInstaller + electron-builder packaging; Windows installer; docs (user README, CONTRIBUTING, CHANGELOG); v1.0.0 tag.

Ordering rationale: dedupe (M2/M4) ships user value before the heavier face pipeline and exercises the whole scan→review→execute loop that face features then reuse; safety machinery (M1) exists before any feature can touch files.

8. Testing strategy

  • Unit (pytest), highest priority = safety invariants: routing ("everything routes somewhere"), _uniq collisions, copy-then-delete semantics (simulate failure between copy and delete), manifest completeness, count check, dry-run touches nothing, undo restores exactly.
  • Model-free pipeline tests: fake FaceProvider + synthetic fixtures (PIL-generated images, tiny generated video/GIF/HEIC, one non-media file) — full scan→cluster→review→organize without downloading anything (per prototype/HANDOFF.md §6).
  • API tests: httpx against the FastAPI app in-process; contract tests for every /v1 route; WebSocket progress ordering.
  • Frontend: Vitest for hooks/stores; Playwright for the two critical journeys (dedupe review end-to-end, face scan → rename → pending confirm) against a mocked backend.
  • Integration (opt-in, not in default CI): a marked pytest suite that runs the real buffalo_l provider on a tiny real-media fixture set — run manually and in a scheduled CI job with the model cached.
  • CI: GitHub Actions matrix — backend on Windows/Linux/macOS × Python 3.10–3.12; frontend lint/typecheck/test; packaging smoke build on Windows.

9. Release strategy

  • Versioning: SemVer. v1.0.0 = PRD complete. Pre-releases (v0.x) after M4 (dedupe-only alpha) and M6 (face beta) for early feedback.
  • Channels: GitHub Releases with electron-builder artifacts — Windows (NSIS installer) first; Linux (AppImage) second; macOS (dmg, initially unsigned/documented) third. Auto-update via electron-updater post-1.0.
  • License compliance gate (blocking for any public release): app code Apache-2.0; every provider in the catalog has verified license terms; the buffalo_l non-commercial status is shown in-app before download; the "General" provider must have a permissive license so the app is usable commercially without buffalo_l (PRD §9).
  • Docs at release: README with demo GIF + quickstart, CONTRIBUTING.md, CHANGELOG.md (kept per release), issue templates.
  • Safety bar for every release: the M1 safety suite and the no-data-loss integration checks pass on all target platforms.

10. Risks & mitigations

Risk Mitigation
PyInstaller + onnxruntime/OpenCV bundling issues on Windows Prove packaging in M0 with a spike build, not at M8.
numpy<2 pin conflicts as deps evolve Isolate backend venv; track upstream; pin everything in pyproject.toml.
buffalo_l license limits distribution Never bundle models; license gate in-app; permissive "General" provider before 1.0.
Electron+model footprint perception Documented trade-off (user decision); models download on demand only.
Clustering quality varies per library Strictness slider + fast re-cluster from embedding cache (no re-detection).
Backend orphaned if Electron crashes Heartbeat: backend exits when the app's WS/health pings stop.