Skip to content
TerrydaktalPublic

About

Local-first Rust media browser for large photo and video archives with mpv playback, duplicate detection, and LanceDB CLIP/OCR search

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Iris

Iris is a local media browser for large photo and video archives. It can browse folders directly, inspect metadata, open videos in mpv, show duplicate/similar media relationships, and search an indexed LanceDB database by filename, CLIP similarity, or OCR text.

The app is intentionally local-first. Media files, embeddings, OCR output, duplicate links, and collection roots live in a local LanceDB directory. No personal collection paths should be hardcoded in the source tree.

Project Structure

.
├── Cargo.toml
├── Cargo.lock
├── build.rs                    # Build identity generation
├── debuggability.toml          # Stateful diagnostic contract
├── README.md
├── docs
│   └── DEBUGGABILITY.md        # Live capture and diagnostic build guide
├── iris.desktop
├── icon.png
├── make_transparent.py
├── src
│   ├── main.rs                 # Binary entry point
│   ├── app
│   │   ├── mod.rs              # Application module wiring and internal facade
│   │   ├── model.rs            # Shared application state and database/search value types
│   │   ├── bootstrap.rs        # CLI parsing, daemon socket, and window startup
│   │   ├── desktop.rs          # Native file dragging and focus handoff to video playback
│   │   ├── viewer_assets.rs    # Viewer previews, visible-region detail loading, and texture limits
│   │   ├── metadata.rs         # exiftool and ffprobe integration
│   │   ├── binary.rs           # Image binary/chunk inspection parsers
│   │   ├── media_scan.rs       # Folder media discovery
│   │   ├── search.rs           # LanceDB row loading and in-memory search
│   │   ├── paths.rs            # Database paths, collection roots, and path matching
│   │   ├── platform.rs         # Desktop/platform path helpers
│   │   ├── clipboard.rs        # Wayland and desktop clipboard integration
│   │   ├── formatting.rs       # File metadata labels and wrapped path rendering
│   │   ├── hashing.rs          # SIFT, on-demand embeddings, and worker orchestration
│   │   ├── runtime.rs          # eframe event loop and background-result polling
│   │   └── ui
│   │       ├── mod.rs          # UI feature module wiring
│   │       ├── core.rs         # Window, sidebar, and shared layout behavior
│   │       ├── face.rs         # Face resemblance and photo-to-video frame matching
│   │       ├── lifecycle.rs    # ImageViewer construction and background database lifecycle
│   │       ├── media_assets.rs # Database path resolution, metadata, and thumbnail loading
│   │       ├── search.rs       # Search controls and related-media actions
│   │       ├── sift.rs         # SIFT compare, align, and repair actions
│   │       ├── navigation.rs   # Folder scans, comparison paths, and navigation
│   │       ├── toolbar.rs      # Compact single-row toolbar and responsive action menus
│   │       ├── viewer.rs       # Viewer, metadata panel, editor, and texture cache
│   │       ├── gallery.rs      # Gallery grid and duplicate actions
│   │       └── home.rs         # File-browser home page
│   └── bin
│       └── make_transparent.rs
└── tools
    ├── on_demand_embeddings.py
    ├── diagnose_iris.sh        # Bounded live-process evidence capture
    ├── replay_iris_capture.sh  # Print or explicitly replay a captured command
    ├── measure_debug_overhead.sh # Minimal/observable release comparison
    ├── check_debuggability.sh  # Build, test, and contract checks
    └── media_indexer
        ├── README.md
        ├── main.py
        ├── relocate_collection.py # Manifest-aware shadow LanceDB relocation
        ├── easyocr_worker.py
        ├── face_worker.py
        ├── paddle_worker.py
        ├── pyproject.toml
        ├── uv.lock
        ├── tests/test_relocate_collection.py # Relocation/integrity tests
        ├── models/clip-text   # generated locally, ignored by Git
        └── tools

Generated local data is ignored by Git, including target/, lancedb/, Python virtualenv/cache folders, downloaded/exported indexer models, reports, and extracted *-video/ still folders.

Main Components

Iris Viewer: src/app/

src/main.rs is only the Cargo binary entry point. The Rust desktop application is organized under src/app/ by responsibility, while keeping the existing ImageViewer state shared across the UI feature modules. It provides:

  • Folder and file gallery browsing for images and videos.
  • Filename, CLIP, and OCR search modes from one search UI.
  • Optional folder-scoped CLIP/OCR search across indexed collections.
  • Image viewing, video handoff to mpv, and folder opening.
  • Comparison mode for two to six selected files, with independent zoom and pan state for each file, plus on-demand SIFT alignment to the first image.
  • EXIF/raw metadata via exiftool and video stream/format metadata via ffprobe.
  • Duplicate sidebar for SIFT groups, pHash/VideoHash similar files, and image-video cross-media matches.
  • Right-click actions for showing visually similar files and more of the same person.
  • Ctrl-click gallery selection for SIFT tooling and face comparison. Two photos can be compared by their closest detected faces; selecting one photo and one indexed video finds the closest indexed face frame and marks the face with a red box.
  • Embedded crop/rotate editor for image edits.
  • On-demand CLIP/face embedding for files that have not already been indexed.

Media Indexer: tools/media_indexer/main.py

The Python indexing pipeline that builds and updates the LanceDB database. It handles:

  • Collection-aware media indexing using <collection_id>/<relative/path> file keys.
  • Collection root mapping through the collection_roots table.
  • A custom OpenCV video hash built from 16 sampled 64-bit DCT pHashes.
  • PySceneDetect ContentDetector still extraction through the OpenCV backend.
  • Custom OpenCV 64-bit DCT pHash generation for images and video stills.
  • Cross-media image-to-video and video-to-image relationships when an image matches a video still.
  • OpenCLIP image embeddings using hf-hub:timm/ViT-L-16-SigLIP2-384 by default.
  • OpenCV SIFT duplicate grouping using SigLIP2 ANN candidates.
  • InsightFace buffalo_l face detection and ArcFace-compatible 512-dimensional embeddings.
  • PaddleOCR PP-OCRv5_mobile_det text detection and EasyOCR text extraction.
  • LanceDB IVF_HNSW_SQ cosine indexes for face, CLIP/SigLIP2, and OCR text search.

See tools/media_indexer/README.md for the full indexing pipeline and stage details.

On-Demand Embeddings: tools/on_demand_embeddings.py

Used by Iris when a file needs CLIP or face vectors but does not already have them in the database.

Example output:

{"ok": true, "clip_embedding": [0.1, 0.2], "face_embeddings": [[0.1, 0.2]]}

Icon Helpers

  • make_transparent.py: Python icon cleanup tool. It removes edge-connected backgrounds and writes a transparent PNG.
  • src/bin/make_transparent.rs: Rust icon utility kept for the Cargo workspace.
  • icon.png: app icon used by the desktop entry.
  • iris.desktop: Linux desktop entry. It uses Icon=iris and StartupWMClass=iris; the app sets the matching native app id.

Database Location

Iris chooses the database directory in this order:

  1. IRIS_DB_DIR, if set.
  2. The repo-local lancedb directory, normally ~/Dev/iris/lancedb when running from this checkout.
  3. Existing discovered lancedb directories on common mounted locations.
  4. ${XDG_DATA_HOME}/iris/lancedb, ${HOME}/.local/share/iris/lancedb, or ./lancedb as fallbacks.

For this repo, the expected default is the repo-local lancedb/. That directory is ignored by Git because it contains generated database tables and extracted still metadata.

Runtime Configuration

Environment variables:

  • IRIS_DB_DIR: override LanceDB directory.
  • IRIS_MEDIA_INDEXER_DIR: override the integrated media indexer/runtime helper directory. Defaults to tools/media_indexer.
  • IRIS_ON_DEMAND_EMBED_SCRIPT: override the on-demand embedding helper path.
  • IRIS_EXIFTOOL: explicit exiftool path.
  • IRIS_FFPROBE: explicit ffprobe path.

External commands used by the viewer:

  • exiftool for image metadata.
  • ffprobe for video metadata.
  • mpv for video playback.
  • dolphin if available for opening folders, with fallback openers otherwise.

Debugging And Diagnostics

The default release build has diagnostics compiled out:

cargo build --release

For a run that may need live inspection, build the observable release. Its private diagnostic socket is available immediately, while diagnostic collection is off unless IRIS_DIAGNOSTICS=1 is set or a running process is activated through --diagnose-pid. Collection expires after 15 minutes by default and writes no diagnostic files unless the explicit IRIS_DIAGNOSTICS_FAILURE_FILE opt-in is set:

cargo build --release --features diagnostics
IRIS_DIAGNOSTICS=1 IRIS_DIAGNOSTICS_TTL_SECS=900 \
  target/release/iris --no-daemon

The observable binary supports --build-info, --capabilities, and --diagnose snapshot|events|activate|deactivate|inject. The inject task_failure ... probe validates the capture path without changing application state. Use --diagnose-pid PID COMMAND when inspecting a specific running process. Each process exposes a private 0600 Unix socket under $XDG_RUNTIME_DIR, with bounded snapshot/event data and independently switchable heartbeat, event, and task categories. To capture an already-running process using external tools:

tools/diagnose_iris.sh PID ./iris-diagnostic-capture

See docs/DEBUGGABILITY.md for the evidence schema, GDB/perf capture, OOM evidence, replay procedure, symbolization, privacy limits, overhead measurement, and indexer status behavior. The machine-readable implementation contract is in debuggability.toml.

Build And Run Iris

To build Iris and record a bounded, content-based baseline for its declared source/build inputs, use make build. The new Makefile wraps the existing cargo build --release --bin iris; build-support/build_receipt.py writes the private, ignored target/release/iris.program-build.json only after a successful build creates or changes that exact artifact. It neither starts Iris nor changes the existing application-version numbering scheme.

The receipt hashes src/, Cargo manifest/lock/configuration, build.rs, the Makefile and the compiled version-helper sources. APP-VERSION remains version-metadata-only, not a source-content change. Receipt checks can distinguish unchanged touched files from same-timestamp content edits and count added/missing regular files within src/. This is explicit partial coverage, not proof of all compiler, dependency, environment or generated inputs. Command arguments and explicit environment values are stored only as hashes. Changing Cargo target directories/profiles requires updating the declared artifact path accordingly.

An up-to-date binary with no previous receipt cannot be retrospectively blessed by a no-op build or touch: the wrapper refuses to create that first baseline. After a genuine content-changing build, a subsequent unchanged normal build retains its existing valid receipt. Direct Cargo builds remain available, but a changed artifact without a matching new receipt is deliberately not trusted as having a current source baseline. Neither command below records a receipt:

cargo run --release -- --no-daemon

Open a file or folder:

cargo run --release -- --no-daemon /path/to/file-or-folder

Open two to six files in comparison mode. Use the left and right arrow keys to switch between them; Iris restores each file's zoom and pan position independently:

cargo run --release -- --no-daemon /path/to/first.jpg /path/to/second.jpg /path/to/third.jpg

The normal Ctrl+O picker opens one file. To enter paths inside Iris, use Compare Paths or Ctrl+Shift+O and enter one path per line. Select one file with Ctrl+O for normal single-file viewing. In comparison mode, Sync View shares the current zoom and pan position across every image; when it is off, each image keeps its own view state. SIFT Align All uses the first image as the reference, computes pairwise SIFT homographies in a background worker, and displays aligned temporary copies without changing the source files. Run SIFT Re-align All to discard the temporary results and recompute every alignment. It is intended for still images; files that cannot produce a reliable homography remain unwarped and are reported in the status.

Large images use a small preview when fitted to the window. Zooming loads a sharper crop of the visible area in the background, including for tall screenshots and aligned comparison images. Nearby pans reuse the decoded source and an overscan margin. Iris keeps one detail texture of at most 4096 x 4096 pixels (64 MiB of RGBA pixels) and one cached decoded source of at most 128 MiB; larger sources are released after each crop. PNG and JPEG files still require a full decode in system memory before cropping. The detail cache is cleared on image changes, leaving the viewer, and saving edits.

The toolbar stays one row high. File contains Filesystem, Open File, and Compare Paths. Gallery and Layout are highlighted when active, and their shortcuts appear in tooltips. The filename uses the remaining width and is shortened with an ellipsis when needed; hover it for the full name, dimensions, and file size. Comparison actions move into More when space is tight. On very narrow windows, controls that no longer fit remain available through File. Keyboard shortcuts are unchanged.

The mouse wheel zooms up to 256 times the fitted view. Use the toolbar's smoothing dropdown, or the right-click menu's Image Smoothing submenu, to choose how enlarged images look. Smooth is the default; Pixel Sharp shows distinct source pixels. Downscaling stays smooth in both modes. The choice applies to the current window, including comparison images, and switches immediately without reloading the image or creating a second GPU texture. At native zoom and above, Iris requires a full-resolution crop instead of reusing a slightly downsampled one. Enlarging the image cannot add detail beyond the original pixels.

Left-drag the image in the main viewer to pan it. Keep holding the button and drag outside the Iris window to turn that gesture into a file drag, then release over another application to drop the original file. Shift + drag starts a file drag immediately. File drag-and-drop currently requires native Wayland.

Video playback opens in mpv from the gallery, context menu, and duplicates sidebar. On Wayland, Iris passes a fresh activation token from the click so the player can take focus when it opens.

Reuse an existing window:

cargo run --release -- --same-window /path/to/file-or-folder

Install the desktop file/icon in the normal Linux locations if you want launcher/taskbar integration. The repo contains the desktop file template, but the actual icon lookup depends on iris being installed into the local icon theme or system icon theme.

Build Or Update The Media Database

Use uv from the media indexer directory:

cd tools/media_indexer
UV_CACHE_DIR="/data/.cache/uv" uv sync

Export the CLIP text model used by Iris text search if it is not already present:

UV_CACHE_DIR="/data/.cache/uv" uv run python tools/export_clip_text_onnx.py --out-dir models/clip-text

Index or incrementally update a collection:

UV_CACHE_DIR="/data/.cache/uv" uv run embedimages /path/to/media \
  --db-dir ../../lancedb \
  --collection-id my_collection

Use stable collection ids. Iris resolves database paths such as my_collection/sub/folder/file.jpg through the collection_roots table, not through hardcoded source paths.

If an indexed tgbackman archive is reorganised, use the committed migration manifest to port Iris without recomputing its AI metadata. Start with the read-only validation pass, then create a separately validated LanceDB:

cd tools/media_indexer
UV_CACHE_DIR="/data/.cache/uv" uv run iris-relocate-collection \
  --db-dir ../../lancedb \
  --manifest /path/to/reorganize.json \
  --collection-id telegram_backup

UV_CACHE_DIR="/data/.cache/uv" uv run iris-relocate-collection \
  --db-dir ../../lancedb \
  --manifest /path/to/reorganize.json \
  --collection-id telegram_backup \
  --output-db-dir ../../lancedb-relocated \
  --apply

The relocation is manifest-, size-, and SHA-256-aware; supports one old path becoming several per-chat paths; preserves computed rows and ANN vectors; and updates path references and collection roots in a shadow database. It never mutates the source database or Telegram files. See tools/media_indexer/README.md for unmapped-row handling and recovery details.

Indexing Stages

The media indexer prints numbered stages and completion status. The concrete implementation used by every stage is:

Stage Purpose Model, algorithm, or tool
0a Scan media files Python Path.rglob filesystem traversal and supported-extension filtering
0b Split images and videos Extension-based classification
0c Open/check the database LanceDB with a PyArrow schema; creates or migrates media_index
0d Ensure the file-name index LanceDB scalar index on file_name
0e Load database rows LanceDB/Apache Arrow table read
0f Normalize rows Python schema normalization into the in-memory record map
0g Check legacy keys Filesystem-to-database key comparison
0h Migrate legacy keys LanceDB row delete/upsert migration
1a Hash videos Iris custom VideoHash: OpenCV VideoCapture, up to 16 evenly spaced frames, a custom 64-bit DCT pHash per frame, then per-bit majority vote
1b Apply video duplicate groups Hamming-distance BK-tree; default duplicate threshold 80%
2 Extract video stills PySceneDetect ContentDetector using the OpenCV backend; defaults: threshold 27, minimum scene length 15, scene-midpoint JPEGs, maximum 100 stills per video
3a Cache image metadata Filesystem stat plus Pillow dimensions
3b Hash images Iris custom OpenCV 64-bit DCT pHash: grayscale, 32x32, DCT, median threshold over the low-frequency 8x8 block
3c Hash video stills The same custom 64-bit DCT pHash used by Stage 3b
3d Apply image pHash groups Hamming-distance BK-tree; default threshold 95%; prefers the highest-resolution image as group master
3e Match images to video frames BK-tree comparison of image pHashes against extracted-video-still pHashes; default threshold 95%
3f Match video frames to images Reverse BK-tree comparison using the same pHashes and cross-media threshold
4a Embed images and video stills OpenCLIP model.encode_image on CUDA; default model hf-hub:timm/ViT-L-16-SigLIP2-384; output vectors are mean-pooled when needed and L2-normalized; default batch size 8
4b Build/delete CLIP/SigLIP2 ANN rows LanceDB side-table sync for changed rows, or a full rebuild when the ANN table is missing/recreated
4c Build/finalize the CLIP/SigLIP2 ANN index LanceDB IVF_HNSW_SQ vector index with cosine distance
5a Shortlist SIFT candidates LanceDB cosine search over the Stage 4b SigLIP2 index; default top 64 eligible image masters
5b Verify and group SIFT matches OpenCV SIFT, L2 brute-force KNN matcher, Lowe ratio test, and homography RANSAC; defaults: ratio 0.75, minimum 10 inliers, minimum inlier ratio 0.75
6a Detect and embed faces InsightFace buffalo_l detection/recognition through ONNX Runtime CUDA; normalized 512-dimensional ArcFace-compatible vectors, with rotation and larger-detector fallback
6b Build/delete face ANN rows LanceDB side-table sync for changed rows, or a full rebuild when the ANN table is missing/recreated
6c Build/finalize the face ANN index LanceDB IVF_HNSW_SQ vector index with cosine distance
7 Detect whether text exists PaddleOCR TextDetection; default model PP-OCRv5_mobile_det, default device gpu:0
8a Extract detected text EasyOCR; default language en, default device CUDA, with reduced-GPU then per-frame CPU fallback after CUDA failure
8b Build/delete OCR ANN rows SentenceTransformers sentence-transformers/all-MiniLM-L6-v2 on CUDA by default; LanceDB side-table sync for changed text rows, or a full rebuild when the ANN table is missing/recreated
8c Build/finalize the OCR ANN index LanceDB IVF_HNSW_SQ vector index with cosine distance

Most stages are incremental. Completed rows are skipped unless a rerun flag is used. Cross-media work writes a resumable work file before final DB application, so a crash during DB upsert can resume from saved 3e/3f results. Search-index sync is also incremental: CLIP, face, and OCR ANN side tables update immediately after the stage that produces their source data, and missing ANN side tables are rebuilt in the relevant 4b/4c, 6b/6c, or 8b/8c stage rather than by a separate final stage.

The application calls Stage 4a and its search mode "CLIP," but its default image embedder is specifically SigLIP2, loaded with open_clip.create_model_and_transforms. Iris text-to-image search uses an ONNX export of the text tower from the same default SigLIP2 model, stored under tools/media_indexer/models/clip-text. On-demand image and face embedding also imports the same OpenCLIP and InsightFace implementations from the media indexer.

Force a stage to rerun:

UV_CACHE_DIR="/data/.cache/uv" uv run embedimages /path/to/media \
  --db-dir ../../lancedb \
  --collection-id my_collection \
  --rerun-stage 3e \
  --rerun-stage 3f

Search Behavior

Filename, CLIP, and OCR share one search UI in Iris.

  • Filename search scans the visible filesystem tree. Folder tiles appear as filenames are discovered, with thumbnails loaded only for visible tiles while the scan continues in the background. The completed folder list uses descending path order. Simply browsing a folder in Filename mode does not load the AI index; database-backed viewing and search actions load it when needed.
  • CLIP search scores embeddings loaded from LanceDB and can search by text, pasted image, or image path. Drop a local file into the CLIP or Filename search field to fill in its path, then press Enter. On Wayland, CLIP search also accepts a dragged image when the source offers image data instead of a path.
  • Advanced adds filters below the regular CLIP or OCR controls. Enter From and Through dates (YYYY-MM-DD), or pick them from the calendars. Both dates are inclusive, and either can be left blank. Iris uses the earliest available EXIF, filesystem creation or modification, or recognized filename date. Files with no known date are excluded when a bound is set.
  • In CLIP, use the normal search field for a description or search image. Advanced also lets you supply an optional Required crop. Iris applies the folder, CLIP threshold and date filters before testing the crop, then shows verified matches as it finds them in descending CLIP-score order. Changing the CLIP cutoff restarts a running advanced CLIP search. Min region match is a separate correlation threshold (80% by default). A video is checked against its best CLIP-matching indexed still rather than every frame. Enable Top third only for headers or status bars.
  • Advanced region search uses OpenCV and Pillow from the media indexer's existing Python environment. It reads source images on demand, so broad searches can be slow on a hard drive. Narrow the folder or raise the CLIP threshold to check fewer files. No database rebuild or thumbnail cache is required.
  • OCR search supports normal multi-term matching and quoted exact phrases.
  • CLIP and OCR searches retrieve every indexed result meeting the Min match threshold; there is no fixed 500-result cap. The existing gallery display still collapses images from the same SIFT duplicate group to one representative. The default is 0%, matching the previous behavior. CLIP uses its similarity score, while OCR uses the fraction of query words found (quoted phrases count as an exact match).
  • Folder scope can be blank for all indexed folders, an absolute path, a collection-relative path, a partial path section, or a single folder segment.

Notes For Public Repo Hygiene

Do not commit:

  • lancedb/ or .lance tables.
  • downloaded/exported model files under tools/media_indexer/models/.
  • extracted video still folders.
  • personal media paths, collection roots, or generated reports.
  • ad-hoc images or screenshots unless they are deliberately part of the app assets.

About

Local-first Rust media browser for large photo and video archives with mpv playback, duplicate detection, and LanceDB CLIP/OCR search

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages