Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
.git
.venv
node_modules
target
__pycache__
**/node_modules
# Rust build output (phash_rs/target is over a gigabyte)
**/target
**/__pycache__
*.pyc
*.pyo
*.pyd
Expand All @@ -28,3 +29,22 @@ credentials.json
# Ignore media directories if running locally
photos/
test/

# Never bake local settings, secrets or working data into the image
.env
.env.*
!.env.example
logs/
d/
s/

# Not needed at runtime
.github/
.pytest_cache/
.ruff_cache/
docs/
tests/
interview-prep/
requirements-dev.txt
explanation.md
todo.md
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ MEDIA_PATH=/home/user/Pictures
# The port the web UI will be accessible on (default 8080)
# CLEAN_BACKUP_PORT=8080

# The web UI has no login, so by default it is reachable from this machine only.
# To reach it from other devices on a network you trust, publish it on all
# interfaces and open it by IP address (http://192.168.x.x:8080):
# CLEAN_BACKUP_BIND=0.0.0.0

# Opening the UI by a hostname other than localhost (e.g. http://nas.local:8080)
# requires listing that hostname here (comma-separated). IP addresses always work.
# CLEAN_BACKUP_ALLOWED_HOSTS=nas.local

# Logging level (debug, info, warning, error)
# CLEAN_BACKUP_LOG_LEVEL=info

Expand Down
34 changes: 28 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ on:
pull_request:
branches: ["main"]

permissions:
contents: read

jobs:
lint:
runs-on: ubuntu-latest
Expand All @@ -20,8 +23,8 @@ jobs:

- name: Lint Python (ruff)
run: |
pip install ruff
ruff check src/ main.py --output-format=github
python -m pip install -r requirements-dev.txt
python -m ruff check src/ main.py tests/ --output-format=github

- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
Expand All @@ -32,7 +35,7 @@ jobs:
working-directory: phash_rs
run: |
cargo fmt --check
cargo clippy -- -D warnings
cargo clippy --locked -- -D warnings

test:
runs-on: ubuntu-latest
Expand All @@ -45,18 +48,20 @@ jobs:

- name: Test Rust module
working-directory: phash_rs
run: cargo test
run: cargo test --locked

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"

- name: Install Python dependencies
run: pip install -r requirements.txt
run: |
python -m pip install -r requirements.txt -r requirements-dev.txt
python -m pip install ./phash_rs

- name: Run Python tests
run: python -m pytest tests/ -v --tb=short || echo "No tests directory found, skipping"
run: python -m pytest tests/ -v --tb=short

docker-build:
runs-on: ubuntu-latest
Expand All @@ -72,6 +77,23 @@ jobs:
with:
context: .
push: false
load: true
tags: clean-backup:ci-test
cache-from: type=gha
cache-to: type=gha,mode=max

- name: Smoke-test the built application
run: |
docker run --detach --publish 127.0.0.1:8080:8080 --name clean-backup-ci clean-backup:ci-test
curl --fail --retry 30 --retry-all-errors --retry-delay 2 --retry-max-time 90 --max-time 5 http://127.0.0.1:8080/api/health \
| python3 -c 'import json, sys; data = json.load(sys.stdin); assert data["ok"] and data["backend"] == "rust (phash_rs)", data'
curl --fail http://127.0.0.1:8080/ \
| python3 -c 'import sys; assert "<div id=\"root\"></div>" in sys.stdin.read(), "Frontend build was not served"'

- name: Show container logs on failure
if: failure()
run: docker logs clean-backup-ci || true

- name: Remove test container
if: always()
run: docker rm --force clean-backup-ci || true
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ build/
dist/
wheels/
*.egg-info
.pytest_cache/

# Virtual environments
.venv
Expand Down
31 changes: 18 additions & 13 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ FROM rust:slim AS rust-builder

WORKDIR /build
# Install build dependencies if needed (e.g. for maturin or setuptools-rust)
RUN apt-get update && apt-get install -y python3 python3-pip python3-venv curl
RUN apt-get update && apt-get install -y --no-install-recommends python3 python3-pip python3-venv \
&& rm -rf /var/lib/apt/lists/*

COPY phash_rs/ phash_rs/
WORKDIR /build/phash_rs
# Compile the rust extension (outputs a .so or .pyd)
# We use maturin to build a wheel, which makes it easy to install in the python image
RUN pip install maturin --break-system-packages
RUN maturin build --release -o dist
RUN maturin build --release --locked -o dist

# ── Stage 2: Frontend Builder ───────────────────────────────────────────
FROM node:20-slim AS frontend-builder
Expand All @@ -30,7 +31,7 @@ FROM python:3.12-slim
WORKDIR /app

# Install system dependencies for OpenCV and ONNX
RUN apt-get update && apt-get install -y \
RUN apt-get update && apt-get install -y --no-install-recommends \
libgl1 \
libglib2.0-0 \
curl \
Expand All @@ -44,22 +45,23 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY --from=rust-builder /build/phash_rs/dist/*.whl /tmp/
RUN pip install --no-cache-dir /tmp/*.whl && rm -f /tmp/*.whl

# Copy application source BEFORE model download so models aren't overwritten
COPY . .

# Copy frontend static build from Stage 2 (overwrites the source web/dist)
COPY --from=frontend-builder /build/web/dist ./web/dist

# Download ONNX models — runs AFTER COPY . . so models persist in the layer
RUN python src/classify/models/download_models.py

# Set up non-root user
# Run as a non-root user. Ownership is set while copying: a later
# `chown -R /app` would store a second copy of every file in a new layer.
RUN useradd -m -u 1000 appuser \
&& mkdir -p /app/data/db /app/data/cache /app/data/config /data/media \
&& chown -R appuser:appuser /app /data/media

USER appuser

# Copy application source BEFORE model download so models aren't overwritten
COPY --chown=appuser:appuser . .

# Copy frontend static build from Stage 2 (overwrites the source web/dist)
COPY --chown=appuser:appuser --from=frontend-builder /build/web/dist ./web/dist

# Download ONNX models (checksum-verified) — runs AFTER COPY . . so they persist
RUN python src/classify/models/download_models.py

# Expose the default port
EXPOSE 8080

Expand All @@ -68,6 +70,9 @@ ENV CLEAN_BACKUP_MEDIA_PATH=/data/media
ENV CLEAN_BACKUP_DB_PATH=/app/data/db/clean_backup.sqlite
ENV CLEAN_BACKUP_CONFIG_DIR=/app/data/config
ENV CLEAN_BACKUP_PORT=8080
# Listen on the container's interfaces; which host interface is exposed is
# decided by the published port (docker-compose.yml defaults to loopback).
ENV CLEAN_BACKUP_HOST=0.0.0.0
ENV CLEAN_BACKUP_LOG_LEVEL=info

# Flask entrypoint
Expand Down
70 changes: 51 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

**Intelligent media organization with perceptual deduplication, AI classification, and a hybrid Rust/Python architecture.**

<!-- Demo GIF placeholder — replace with actual recording once available -->
<!-- ![Demo](docs/demo.gif) -->
![Clean-Backup demonstration: scan for duplicates, compare images, organize by date, and undo the operation](docs/demo.gif)

*A 32-second walkthrough of the running web app: scan nine sample images, review three duplicate groups, organize copies by date, and undo the session. Actual screen captures, edited for pace. [Recording details and sample sources](docs/RECORDING.md).*

[![CI](https://github.com/JayacharanR/Clean-Backup/actions/workflows/ci.yml/badge.svg)](https://github.com/JayacharanR/Clean-Backup/actions/workflows/ci.yml)
[![Release](https://github.com/JayacharanR/Clean-Backup/actions/workflows/release.yml/badge.svg)](https://github.com/JayacharanR/Clean-Backup/actions/workflows/release.yml)
Expand All @@ -28,7 +29,7 @@ The performance-critical image hashing is written in **Rust** (`phash_rs`), the
Run the full stack with zero setup:

```bash
docker run -p 8080:8080 -v ~/Photos:/data/media ghcr.io/jayacharanr/clean-backup:latest
docker run -p 127.0.0.1:8080:8080 -v ~/Photos:/data/media ghcr.io/jayacharanr/clean-backup:latest
```

Then open [http://localhost:8080](http://localhost:8080).
Expand All @@ -44,6 +45,16 @@ cp .env.example .env
docker compose up -d
```

### Network access

The web UI has **no login**. Anyone who can reach it can scan, move and delete files in the mounted library, so by default it is reachable only from the machine it runs on:

- `python main.py --web` listens on `127.0.0.1` (override with `CLEAN_BACKUP_HOST`).
- `docker compose` publishes the port on `127.0.0.1` (override with `CLEAN_BACKUP_BIND=0.0.0.0` on a network you trust).
- Requests are accepted only when addressed to `localhost`, an IP address, or a hostname listed in `CLEAN_BACKUP_ALLOWED_HOSTS` (comma-separated, e.g. `nas.local`). State-changing requests from other websites are refused.

Do not expose it to the internet. To reach it remotely, put it behind a VPN or an authenticating reverse proxy.

## Architecture

```mermaid
Expand Down Expand Up @@ -71,7 +82,7 @@ flowchart TB

subgraph Cloud["Cloud Sync · optional"]
GDrive["Google Drive"]
S3["AWS S3"]
S3["AWS S3 · planned"]
end

UI <-->|polling| API
Expand All @@ -92,36 +103,36 @@ flowchart TB
- **Rust-accelerated pHash**: DCT-based perceptual hashing detects visual duplicates even after resize, recompression, or format conversion — not just byte-identical files.
- **Parallel hash computation**: Leverages Rayon's work-stealing thread pool in Rust for concurrent image hashing (`par_iter`), with automatic CPU core utilization.
- **Tunable sensitivity**: Hamming distance threshold from exact-match (0) to aggressive (10+), persisted between sessions.
- **Name-based detection**: Catches OS-generated duplicates (`file (1).jpg`, `file - Copy.jpg`) across Windows, macOS, and Linux patterns.
- **No name-based guessing**: files such as `photo (1).jpg` or `photo - Copy.jpg` are never dropped because of their names; only content decides, and organization keeps every named variant.
- **Safe review UI**: Grouped duplicate cards with side-by-side comparison, modal full-resolution preview, keyboard navigation, and protected best-image rules.

### Performance & Parallelization

Clean-Backup uses a **two-layer parallelization architecture** to maximize throughput:
Hashing is parallel in Rust; file transfers favour verification over raw speed:

| Layer | Technology | What it parallelizes |
|-------|-----------|---------------------|
| **Rust (native threads)** | Rayon work-stealing thread pool | Image decoding, DCT hash computation, Hamming distance comparisons |
| **Python (process pool)** | `multiprocessing.Pool` (N-1 cores) | File I/O, EXIF extraction, copy/move operations, compression |
| **Python (thread pool)** | `ThreadPoolExecutor` (up to 8 workers) | EXIF / video metadata extraction while organizing. Each copy or move is verified (SHA-256 read-back) and published one at a time. |

- **Rayon `par_iter()` in Rust**: `find_duplicates_parallel()` and `compute_hashes_parallel()` use Rayon's data-parallel iterators to distribute image hashing across all CPU cores. Each image is independently decoded, resized, DCT-transformed, and hashed — a perfectly parallelizable workload.
- **Python multiprocessing for file operations**: The organizer spawns `cpu_count() - 1` worker processes (typically 15 on a 16-core machine) to handle concurrent file copies, moves, and metadata extraction.
- **10× speedup over pure Python**: The Rust pHash engine with Rayon multi-threading outperforms equivalent Python (Pillow + imagehash) implementations by an order of magnitude on batch duplicate scanning.
- **PyO3/Maturin bridge**: Rust functions are exposed as native Python functions via PyO3 with abi3 cross-version compatibility, achieving zero-copy data transfer for hash results.
- **One decode per image**: a scan computes each image's hash and resolution from a single decode and groups those results without touching the files again. On a 320-image, 6-megapixel JPEG test library this cut a web scan from 6.0 s to 2.8 s with identical results.
- **Responsive during scans**: hashing releases Python's GIL, so progress polling is served while Rust works. A pure-Python fallback is used automatically if the extension is not built (much slower).
- **PyO3/Maturin bridge**: Rust functions are exposed as native Python functions via PyO3 with abi3 cross-version compatibility.

### Organization & Classification
- **Date-based organization**: Extracts EXIF `DateTimeOriginal`, video container metadata, and filesystem stats to sort into `Year/Month` hierarchies.
- **AI scene classification**: MobileNetV3 ONNX model tags photos into 15 categories (travel, food, nature, documents, etc.) with configurable confidence thresholds.
- **AI scene classification**: MobileNetV2 ONNX model tags photos into 15 categories (travel, food, nature, documents, etc.) with configurable confidence thresholds.
- **Face detection & recognition**: YuNet face detection + ArcFace embeddings for automatic face grouping. Name people once, and the system recognizes them across your library.
- **Review queue**: Low-confidence classifications and unresolved face matches are surfaced for human review before any files move.

### Compression
- Three compression levels (high quality → maximum compression) for both images and videos.
- Parallel processing using all CPU cores. H.264 + AAC for video, libjpeg-turbo for JPEG.
- Files are processed one at a time. H.264 + AAC for video (requires FFmpeg), Pillow/libjpeg for JPEG. Outputs never replace the source or an existing file.
- Detailed per-file analytics with compression ratios and space savings.

### Cloud Sync
- **Provider-agnostic**: Google Drive (OAuth2) and AWS S3 support via a pluggable `CloudProvider` interface.
- **Pluggable providers**: Google Drive (OAuth2) is implemented behind a `CloudProvider` interface. AWS S3 is a placeholder and not functional yet.
- **Manifest-based incremental sync**: SHA-256 content hashing ensures only changed files are uploaded.
- **Secure credential storage**: OS keyring integration with Fernet-encrypted fallback.
- **Undo support**: Synced files can be removed from the cloud provider via the undo system.
Expand All @@ -134,22 +145,22 @@ Clean-Backup uses a **two-layer parallelization architecture** to maximize throu
### Web Control Panel
- **Complete workflow tabs**: Duplicates, Organize, Compression, Classify, People, Review, Cloud Sync, Watchers, and Settings.
- **Background job execution**: Long-running operations run asynchronously with live progress polling.
- **Transactional undo**: Every file operation is journaled. Full session rollback with crash recovery.
- **Undo observability**: Session filtering, JSON export for auditing and recovery workflows.
- **Journaled undo**: organize, classification apply and Trash operations are recorded in an append-only journal before they take effect, and can be rolled back per session. Permanent deletion and compression outputs are not undoable.
- **Undo history**: sessions can be filtered and reverted individually; conflicts (edited or missing files) are kept and reported instead of overwritten.

## Tech Stack

| Layer | Technology |
|-------|-----------|
| **Performance-critical hashing** | Rust (2021 Edition) + Rayon thread pool via `maturin`/PyO3 |
| **Parallelization** | Rayon (Rust work-stealing threads) + Python `multiprocessing.Pool` |
| **Parallelization** | Rayon (Rust work-stealing threads) + Python `ThreadPoolExecutor` |
| **Backend & ML pipeline** | Python 3.12+, Flask, ONNX Runtime |
| **Frontend** | React + Vite |
| **Database** | SQLite (WAL mode) |
| **ML models** | MobileNetV3 (scene), YuNet (face detect), ArcFace (face embed) |
| **ML models** | MobileNetV2 (scene), YuNet (face detect), ArcFace (face embed) |
| **Image processing** | Pillow, pillow-heif (HEIC), OpenCV |
| **Video metadata** | hachoir, FFmpeg (compression) |
| **Cloud providers** | Google Drive API, AWS S3 (boto3) |
| **Cloud providers** | Google Drive API (AWS S3 planned) |
| **Containerization** | Docker (multi-stage build) |

## Local Development
Expand Down Expand Up @@ -183,12 +194,33 @@ python main.py # CLI mode
python main.py --web # Web GUI at http://localhost:8080
```

Classification models (about 275 MB) are not in the repository. Fetch and checksum-verify them once with `python -m src.classify.models.download_models`; without them the classifier falls back to metadata-only heuristics.

### Checks

After completing local setup, install the development tools and run the same checks as CI:

```bash
pip install -r requirements-dev.txt
python -m ruff check src/ main.py tests/
python -m pytest tests/ -v --tb=short
cargo fmt --manifest-path phash_rs/Cargo.toml --check
cargo clippy --manifest-path phash_rs/Cargo.toml --locked -- -D warnings
cargo test --manifest-path phash_rs/Cargo.toml --locked
```

The Python tests use disposable media, configuration, databases, and undo journals. They require the compiled Rust module and exercise duplicate scanning, image previews, date-based copy/move organization, classification apply, undo and crash recovery, the API's cross-origin and host checks, demo-mode restrictions, and input validation. CI also builds and starts the Docker image, checks its Rust backend health response, and verifies that it serves the frontend. Test failures fail the workflow.

## Privacy

Clean-Backup runs **100% offline**. All machine learning models (ONNX) are baked into the Docker image and require no cloud API calls. Face embeddings and classification tags are stored only in your local SQLite database. No telemetry, no analytics, no data leaves your machine.
Clean-Backup processes your library locally. The machine learning models (ONNX) are downloaded once at image build time, verified against pinned checksums, and need no cloud API calls at runtime. Face embeddings and classification tags are stored only in your local SQLite database. No telemetry, no analytics, no data leaves your machine.

Cloud sync is entirely optional and user-initiated — credentials are stored in your OS keyring or encrypted locally.

## Audit

The most recent engineering audit — findings, fixes, measurements and what remains open — is in [docs/AUDIT_REPORT.md](docs/AUDIT_REPORT.md).

## License

MIT License — see [LICENSE](LICENSE) for details.
Expand Down
5 changes: 5 additions & 0 deletions deploy/demo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ This directory contains everything needed to deploy a read-only demo of Clean-Ba
| `CLEAN_BACKUP_PORT` | `8080` |
| `CLEAN_BACKUP_LOG_LEVEL` | `info` |

The server only answers requests addressed to a hostname it expects. Render's
own `*.onrender.com` name is picked up automatically (`RENDER_EXTERNAL_HOSTNAME`);
for a custom domain also set `CLEAN_BACKUP_ALLOWED_HOSTS=demo.example.com`.
In demo mode the API can only read the seeded media folder.

### 3. Deploy

Render will build using the repo-root `Dockerfile` automatically. The `render.yaml` blueprint in this directory can also be used for one-click deploy.
Expand Down
8 changes: 5 additions & 3 deletions deploy/demo/reset_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,13 @@ def reset_demo():
import sqlite3
conn = sqlite3.connect(str(db_path))
# Delete all user-created data, keep schema
# Children before parents: the schema declares foreign keys.
for table in [
"watcher_events", "watcher_configs",
"classifications", "classification_runs",
"faces", "people", "review_queue",
"cloud_sync_runs", "cloud_sync_files", "cloud_accounts",
"media_tags", "review_queue", "face_embeddings", "people",
"classify_run_config",
"sync_manifest", "sync_runs", "cloud_accounts",
"media_files",
]:
try:
conn.execute(f"DELETE FROM {table}")
Expand Down
Loading