diff --git a/.env.example b/.env.example index 480fa46..9aa6d33 100644 --- a/.env.example +++ b/.env.example @@ -28,8 +28,11 @@ STRATEGY=auto # ENABLE_FACE_ALIGNMENT=true # Align face before cropping (default: true) # USE_FULL_RESOLUTION=true # Use full-res images vs thumbnails (default: true) # MIN_CONFIDENCE=0.7 # Minimum face detection confidence (default: 0.7) -# BLUR_THRESHOLD=100.0 # Laplacian blur threshold; lower = accept more blur (default: 100.0) +# BLUR_THRESHOLD=120.0 # Laplacian blur threshold; lower = accept more blur (default: 120.0) # MAX_AUTO_IMAGES=80 # Hard cap on auto-diversity selection (default: 80) +# QUALITY_REPLACEMENT=true # At cap, replace a weaker tracked image with a better candidate (default: true) +# FRIGATE_SCORE_CEILING=0.0 # Skip uploads already well-covered (pre-upload score > ceiling = redundant; 0 = disabled; requires at least one prior run) +# ENABLE_FRIGATE_SCORES=true # Call Frigate's recognize endpoint pre-upload to store diversity scores (default: true; adds ~200ms per upload) # ── Caching & Models ────────────────────────────────────────────────────────── # FORCE_CPU=true # Disable GPU, fall back to CPU diff --git a/CHANGELOG.md b/CHANGELOG.md index a23d354..484bcd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.4.0] - 2026-06-13 + +### Added + +- **Pre-upload Frigate recognition scores**: `recognize_face` is now called before each upload to measure how novel the candidate is relative to the existing training set. The score is stored in the tracker (`frigate_scores` field) and drives quality replacement in subsequent runs. Adds ~200 ms per upload. +- **`ENABLE_FRIGATE_SCORES`** (default `true`): controls all pre-upload Frigate recognize calls. Set `false` to use blur-score replacement only and skip the Frigate round-trip entirely. +- **`FRIGATE_SCORE_CEILING`** (default `0.0`): skip uploads whose pre-upload recognize score already exceeds this value — those face conditions are already well-covered by the training set. `0` disables (no ceiling); requires at least one prior run to have stored scores. +- **`get_most_redundant_mapped_file()`**: new upload-tracker function that returns the mapped file with the highest Frigate pre-upload score. High score = the training set already covers that face condition well = the best deletion target for quality replacement. +- **Cold-start notice**: first run (no existing Frigate model) now logs a clear message explaining why Frigate scores are unavailable and that they will populate on subsequent runs. +- **4 new tests** for `get_most_redundant_mapped_file` covering score ordering, ties, excludes, and no-score cases. + +### Changed + +- **Quality replacement now uses Frigate scores**: when Frigate scores are available, at-cap replacement targets the _most redundant_ mapped file (highest pre-upload score) and replaces it only when the candidate is _more novel_ (lower score). Falls back to blur-score comparison when no Frigate scores have been stored yet. +- **`recognize_face` returns `(face_name, score) | None`** instead of `float | None`: the caller now validates that the recognized person matches the expected person before using the score. Wrong-person scores no longer drive ceiling skips or replacement decisions. +- **Bootstrap fix**: recognize was previously called below-cap only when `FRIGATE_SCORE_CEILING > 0`, so `frigate_scores` was never populated with default settings and the Frigate replacement path never activated. Recognize is now called for all below-cap uploads when `ENABLE_FRIGATE_SCORES=true`, seeding scores for future at-cap runs regardless of ceiling setting. +- **Batch GET `/api/faces`**: Frigate file-count lookups are now batched to reduce round-trip overhead on runs with many people. +- **Skip candidate download on low Frigate confidence**: candidates where the Immich detection confidence is below threshold are now filtered before the full-resolution download, saving bandwidth. + +### Removed + +- **Post-upload quality gate (`FRIGATE_SCORE_THRESHOLD`)**: enforcement of a Frigate score threshold after upload has been removed. Post-upload scores are taken after the image is already in the training set, so the model has already retrained on it — deleting it at that point is wasteful and disrupts the model for the next Frigate run. Pre-upload scoring (`FRIGATE_SCORE_CEILING`) provides a cleaner signal at the right moment. + +### Fixed + +- **Frigate replacement path never activated with default settings**: with `FRIGATE_SCORE_CEILING=0.0` (default), the bootstrap call to `recognize_face` was gated behind `CEILING > 0`, so `frigate_scores` stayed empty, `has_frigate_scores` was always False, and the Frigate replacement branch was permanently unreachable. Removing the ceiling guard from the below-cap recognize call breaks the circular dependency. +- **Schema comment contradiction**: `upload_tracker.py` line-16 comment described `frigate_scores` as "post-upload" while the block comment on lines 22–24 said "pre-upload". Corrected to "pre-upload" throughout. +- **README default values**: `MIN_FACE_WIDTH` was documented as `50` (actual default: `90`); `BLUR_THRESHOLD` was documented as `100.0` (actual default: `120.0`). Both corrected. +- **README missing env vars**: `FRIGATE_SCORE_CEILING` and `ENABLE_FRIGATE_SCORES` were present in `config.py` and `.env.example` but absent from the README env var table. Both added. +- **README quality-replacement description**: Step 8 and the `QUALITY_REPLACEMENT` row now document the dual-mode behaviour (Frigate-score path and blur-score fallback) instead of describing only the original blur-score path. + ## [0.3.3] - 2026-06-13 ### Fixed diff --git a/README.md b/README.md index 5273dff..5641f39 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ [![Docker](https://github.com/sudolulo/winnow/actions/workflows/docker-publish.yml/badge.svg)](https://github.com/sudolulo/winnow/actions/workflows/docker-publish.yml) [![Test](https://github.com/sudolulo/winnow/actions/workflows/test.yml/badge.svg)](https://github.com/sudolulo/winnow/actions/workflows/test.yml) [![GitHub release](https://img.shields.io/github/v/release/sudolulo/winnow)](https://github.com/sudolulo/winnow/releases/latest) [![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](LICENSE) [![Immich](https://img.shields.io/badge/Immich-v1.106%2B-blueviolet)](https://immich.app) [![Frigate](https://img.shields.io/badge/Frigate-Ready-brightgreen)](https://frigate.video) +> **Early Development — Use With Caution** +> winnow is functional but still maturing. Features that modify your Frigate training data — quality replacement, stale mapping cleanup — can remove images from your dataset and are not yet battle-tested at scale. Review the logs after each run and keep backups of your Frigate face training directory until you are confident in the results. + **Docs:** [Setup](https://github.com/sudolulo/winnow/wiki/Setup) · [Troubleshooting](https://github.com/sudolulo/winnow/wiki/Troubleshooting) · [FAQ](https://github.com/sudolulo/winnow/wiki/FAQ) `winnow` pulls photos from your [Immich](https://immich.app) library, selects the most diverse and highest-quality subset using AI embeddings, and delivers them as training data for [Frigate](https://frigate.video)'s face recognition and object classification models. @@ -56,9 +59,11 @@ Immich library 8. Deliver • Face mode: upload crops to Frigate's face registration API ↳ below MAX_AUTO_IMAGES — upload freely - ↳ at cap + QUALITY_REPLACEMENT=true — swap the lowest-scoring tracked - image if the new candidate scores higher; manually added files are - never touched + ↳ at cap + QUALITY_REPLACEMENT=true — with Frigate scoring active, + swap the most redundant tracked image (highest pre-upload recognize + score) if the candidate is more novel (lower score); falling back to + blur-score comparison when no Frigate scores are available; manually + added files are never touched ↳ at cap + QUALITY_REPLACEMENT=false — skip this person • Object mode: save crops to disk → place into your Frigate data directory ``` @@ -183,14 +188,16 @@ In scheduled mode the process (and loaded models) stays resident between runs. T | Variable | Default | Description | | :--- | :--- | :--- | -| `MIN_FACE_WIDTH` | `50` | Minimum face crop width in pixels | +| `MIN_FACE_WIDTH` | `90` | Minimum face crop width in pixels | | `FACE_MARGIN` | `0.15` | Padding around bounding box crop (fraction of face size) | | `ENABLE_FACE_ALIGNMENT` | `true` | Align to ArcFace 112×112 format using facial landmarks | | `USE_FULL_RESOLUTION` | `true` | Download full-resolution originals rather than preview thumbnails | | `MIN_CONFIDENCE` | `0.7` | Minimum Immich face detection confidence | -| `BLUR_THRESHOLD` | `100.0` | Laplacian variance threshold — lower accepts more blur | +| `BLUR_THRESHOLD` | `120.0` | Laplacian variance threshold — lower accepts more blur | | `MAX_AUTO_IMAGES` | `80` | Maximum training images per person in Frigate | -| `QUALITY_REPLACEMENT` | `true` | When at cap, swap the lowest-scoring tracked image for a better candidate. Never touches manually added Frigate files. Set `false` to skip people already at cap | +| `QUALITY_REPLACEMENT` | `true` | When at cap, swap a weaker tracked image for a better candidate. With Frigate scoring active, targets the most redundant image (highest pre-upload recognize score); otherwise uses blur score. Never touches manually added Frigate files. Set `false` to skip people at cap | +| `FRIGATE_SCORE_CEILING` | `0.0` | Skip uploads whose pre-upload Frigate recognize score exceeds this value — they are already well-covered. `0` disables; requires at least one prior run to have scores | +| `ENABLE_FRIGATE_SCORES` | `true` | Call Frigate's recognize endpoint pre-upload to store diversity scores used for quality replacement. Adds ~200 ms per upload. Disable to use blur-score replacement only | ### GPU & Models diff --git a/pyproject.toml b/pyproject.toml index fa16cc8..e65e885 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "winnow" -version = "0.3.3" +version = "0.4.0" description = "Selects diverse, high-quality photos from Immich as training data for Frigate face recognition and object classification." license = "AGPL-3.0-or-later" requires-python = ">=3.13" diff --git a/tests/test_config.py b/tests/test_config.py index e729763..5d700d4 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -19,7 +19,7 @@ def test_config_loads_defaults(monkeypatch): assert cfg.YEARS_FILTER == 10 assert cfg.MIN_FACE_WIDTH == 90 assert cfg.MIN_FACE_COUNT == 0 - assert cfg.BLUR_THRESHOLD == 100.0 + assert cfg.BLUR_THRESHOLD == 120.0 assert cfg.MIN_CONFIDENCE == 0.7 assert cfg.MAX_AUTO_IMAGES == 80 assert cfg.QUALITY_REPLACEMENT is True diff --git a/tests/test_upload_tracker.py b/tests/test_upload_tracker.py index fcdd37c..f5afb9c 100644 --- a/tests/test_upload_tracker.py +++ b/tests/test_upload_tracker.py @@ -218,3 +218,45 @@ def test_get_lowest_quality_exclude_all_returns_none(): mark_uploaded("asset-a", person_name="Alice", score=0.50) record_frigate_file("Alice", "Alice-a.webp", "asset-a") assert get_lowest_quality_mapped_file("Alice", exclude={"Alice-a.webp"}) is None + + +# ── get_most_redundant_mapped_file ──────────────────────────────────────────── + +def test_get_most_redundant_none_when_no_frigate_scores(): + from winnow.upload_tracker import get_most_redundant_mapped_file, mark_uploaded, record_frigate_file + mark_uploaded("asset-a", person_name="Alice", score=0.80) + record_frigate_file("Alice", "Alice-a.webp", "asset-a") + # blur score only, no frigate_score → no candidates + assert get_most_redundant_mapped_file("Alice") is None + + +def test_get_most_redundant_returns_highest_frigate_score(): + from winnow.upload_tracker import get_most_redundant_mapped_file, mark_uploaded, record_frigate_file + mark_uploaded("asset-novel", person_name="Alice", score=0.50, frigate_score=0.31) + mark_uploaded("asset-redundant", person_name="Alice", score=0.90, frigate_score=0.88) + record_frigate_file("Alice", "Alice-novel.webp", "asset-novel") + record_frigate_file("Alice", "Alice-redundant.webp", "asset-redundant") + result = get_most_redundant_mapped_file("Alice") + assert result is not None + frigate_filename, asset_id, score = result + assert frigate_filename == "Alice-redundant.webp" + assert asset_id == "asset-redundant" + assert score == pytest.approx(0.88, abs=0.001) + + +def test_get_most_redundant_exclude_skips_file(): + from winnow.upload_tracker import get_most_redundant_mapped_file, mark_uploaded, record_frigate_file + mark_uploaded("asset-hi", person_name="Alice", score=0.9, frigate_score=0.85) + mark_uploaded("asset-lo", person_name="Alice", score=0.5, frigate_score=0.40) + record_frigate_file("Alice", "Alice-hi.webp", "asset-hi") + record_frigate_file("Alice", "Alice-lo.webp", "asset-lo") + result = get_most_redundant_mapped_file("Alice", exclude={"Alice-hi.webp"}) + assert result is not None + assert result[1] == "asset-lo" # hi excluded; lo is next highest + + +def test_get_most_redundant_exclude_all_returns_none(): + from winnow.upload_tracker import get_most_redundant_mapped_file, mark_uploaded, record_frigate_file + mark_uploaded("asset-a", person_name="Alice", score=0.5, frigate_score=0.70) + record_frigate_file("Alice", "Alice-a.webp", "asset-a") + assert get_most_redundant_mapped_file("Alice", exclude={"Alice-a.webp"}) is None diff --git a/winnow/cli.py b/winnow/cli.py index 24e5b5c..007875e 100644 --- a/winnow/cli.py +++ b/winnow/cli.py @@ -41,6 +41,8 @@ def _handle_trace_crop(size_str: str) -> None: rprint(f" Immich URL: {immich_url}/photos/{m['asset_id']}") blur = m.get("blur_score") rprint(f" Blur score: {blur:.1f}" if blur is not None else " Blur score: unknown") + fscore = m.get("frigate_score") + rprint(f" Frigate score: {fscore:.2f}" if fscore is not None else " Frigate score: unknown") if m.get("frigate_filename"): rprint(f" Frigate file: {m['frigate_filename']}") else: diff --git a/winnow/config.py b/winnow/config.py index 30f5776..198a030 100644 --- a/winnow/config.py +++ b/winnow/config.py @@ -27,10 +27,12 @@ class _Config: # Quality filtering MIN_FACE_WIDTH: int = 90 - BLUR_THRESHOLD: float = 100.0 + BLUR_THRESHOLD: float = 120.0 MIN_CONFIDENCE: float = 0.7 MAX_AUTO_IMAGES: int = 80 QUALITY_REPLACEMENT: bool = True + FRIGATE_SCORE_CEILING: float = 0.0 + ENABLE_FRIGATE_SCORES: bool = True # People filtering MIN_FACE_COUNT: int = 0 @@ -58,10 +60,12 @@ class _Config: self.YEARS_FILTER = int(os.getenv("YEARS_FILTER", "10")) self.MIN_FACE_WIDTH = int(os.getenv("MIN_FACE_WIDTH", "90")) self.MIN_FACE_COUNT = int(os.getenv("MIN_FACE_COUNT", "0")) - self.BLUR_THRESHOLD = float(os.getenv("BLUR_THRESHOLD", "100.0")) + self.BLUR_THRESHOLD = float(os.getenv("BLUR_THRESHOLD", "120.0")) self.MIN_CONFIDENCE = float(os.getenv("MIN_CONFIDENCE", "0.7")) self.MAX_AUTO_IMAGES = int(os.getenv("MAX_AUTO_IMAGES", "80")) self.QUALITY_REPLACEMENT = os.getenv("QUALITY_REPLACEMENT", "true").lower() in ("true", "1", "yes") + self.FRIGATE_SCORE_CEILING = float(os.getenv("FRIGATE_SCORE_CEILING", "0.0")) + self.ENABLE_FRIGATE_SCORES = os.getenv("ENABLE_FRIGATE_SCORES", "true").lower() in ("true", "1", "yes") self.FACE_MARGIN = float(os.getenv("FACE_MARGIN", "0.15")) self.USE_FULL_RESOLUTION = os.getenv("USE_FULL_RESOLUTION", "true").lower() in ("true", "1", "yes") self.ENABLE_FACE_ALIGNMENT = os.getenv("ENABLE_FACE_ALIGNMENT", "true").lower() in ("true", "1", "yes") diff --git a/winnow/executor.py b/winnow/executor.py index 2c2bdfe..4b01046 100644 --- a/winnow/executor.py +++ b/winnow/executor.py @@ -13,15 +13,17 @@ from rich import print as rprint from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn from .config import Config, get_headers -from .frigate_api import delete_frigate_person_files, get_frigate_person_files +from .frigate_api import delete_frigate_person_files, get_all_frigate_person_files, get_frigate_person_files, recognize_face from .image_processing import process_face_mode, process_full_mode, process_object_mode from .immich_api import fetch_face_data, fetch_full_image from .log_config import console from .quality import assess_quality from .upload_tracker import ( get_lowest_quality_mapped_file, + get_most_redundant_mapped_file, get_tracked_frigate_file_count, get_tracked_frigate_filenames, + has_frigate_scores, mark_rejected, mark_uploaded, record_frigate_file, @@ -182,6 +184,17 @@ def execute_jobs(jobs: list[dict]) -> None: # from the Immich faces API (not included in search/metadata results) if mode == "face": asset = _enrich_asset_with_face_data(asset, person) + # Skip download if detection confidence already disqualifies + # the asset — avoids fetching a large image we'll discard. + conf = asset.get("face_confidence") + if conf is not None and conf < Config.MIN_CONFIDENCE: + progress.console.print( + f"[yellow]Skipped {asset['id']}" + f" (detection confidence {conf:.2f} < {Config.MIN_CONFIDENCE})[/yellow]" + ) + progress.advance(job_task) + progress.advance(overall_task) + continue # Use full-resolution for final output when configured if use_full_res: @@ -305,6 +318,10 @@ def upload_to_frigate(jobs: list[dict]) -> None: uploaded, failed = 0, 0 max_retries = 2 + # Fetch all Frigate training files once — avoids one GET /api/faces per person. + # Falls back to per-person calls inside the loop if this fetch fails. + all_frigate_files = get_all_frigate_person_files() + with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), @@ -342,7 +359,10 @@ def upload_to_frigate(jobs: list[dict]) -> None: # Snapshot live Frigate files for post-upload reconciliation diff only. # effective_count is sourced from the tracker (mapped files) so that # manually-added Frigate files don't consume winnow's managed quota. - _snapshot = get_frigate_person_files(name) + _snapshot = ( + all_frigate_files.get(name, []) if all_frigate_files is not None + else get_frigate_person_files(name) + ) if _snapshot is None: # Frigate GET is down; fall back to the tracker's mapped filenames # as the pre-upload baseline. reconciliation will still work unless @@ -354,8 +374,24 @@ def upload_to_frigate(jobs: list[dict]) -> None: known_frigate_files_at_start: set[str] = get_tracked_frigate_filenames(name) else: known_frigate_files_at_start: set[str] = set(_snapshot) + # Remove tracker mappings for files that no longer exist in Frigate + # (manually deleted, or cleaned up outside winnow). This corrects the + # effective_count so those slots are available for new uploads. + stale = get_tracked_frigate_filenames(name) - known_frigate_files_at_start + for stale_fn in stale: + remove_frigate_file(name, stale_fn) + if stale: + progress.console.print( + f" [dim]{name}: cleared {len(stale)} stale mapping(s)" + " (file(s) no longer in Frigate)[/dim]" + ) effective_count = get_tracked_frigate_file_count(name) + pre_run_count = effective_count quality_replacement = job.get("config", {}).get("quality_replacement", False) + if Config.ENABLE_FRIGATE_SCORES and pre_run_count == 0: + progress.console.print( + f" [dim]{name}: first run — Frigate diversity scoring will apply from the next run[/dim]" + ) actually_uploaded: list[tuple[str, str | None]] = [] failed_deletes: set[str] = set() min_quality_score_for_slot: float | None = None @@ -378,40 +414,106 @@ def upload_to_frigate(jobs: list[dict]) -> None: continue at_cap = effective_count >= Config.MAX_AUTO_IMAGES + + # Pre-upload Frigate score — clean measurement (image not yet in training set). + # Called for all below-cap uploads (seeds frigate_scores for future at-cap + # replacement) and for at-cap uploads when scores already exist. Skipped on + # the first run (pre_run_count == 0) since Frigate has no model yet. + # recognize_face returns (face_name, score); we only use the score when the + # best match is for the correct person. Mismatches (or "unknown") are treated + # as None so a wrong-person score never drives a ceiling skip or replacement. + # Frigate rebuilds its model asynchronously after any delete (clear + background + # thread), so the first recognize call after a deletion returns None — our code + # handles this conservatively by skipping that candidate until the next run. + pre_fscore: float | None = None + if Config.ENABLE_FRIGATE_SCORES and pre_run_count > 0: + if not at_cap or has_frigate_scores(name): + _result = recognize_face(fpath) + if _result is not None and _result[0] == name: + pre_fscore = _result[1] + + # Ceiling check: skip if the existing training set already covers this + # face condition well. Applies below cap only — at cap, replacement logic + # drives the decision. + if not at_cap and Config.FRIGATE_SCORE_CEILING > 0 and pre_run_count > 0: + if pre_fscore is not None and pre_fscore > Config.FRIGATE_SCORE_CEILING: + progress.console.print( + f" [dim]⏭ {fname}: Frigate score {pre_fscore:.2f}" + f" > ceiling {Config.FRIGATE_SCORE_CEILING:.2f}, already covered[/dim]" + ) + progress.advance(upload_task) + continue + if at_cap: if not quality_replacement: progress.console.print(f" [dim]⏭ {fname}: at cap, quality replacement disabled[/dim]") progress.advance(upload_task) continue - new_score = score_map.get(fname) - if new_score is None: - progress.console.print(f" [dim]⏭ {fname}: no confidence score, skipping replacement[/dim]") - progress.advance(upload_task) - continue - worst = get_lowest_quality_mapped_file(name, exclude=failed_deletes) - if worst is None or new_score <= worst[2]: - worst_score_str = f"{worst[2]:.3f}" if worst is not None else "N/A" + + using_fscore = has_frigate_scores(name) and Config.ENABLE_FRIGATE_SCORES + if using_fscore: + candidate_score = pre_fscore + if candidate_score is None: + progress.console.print( + f" [dim]⏭ {fname}: Frigate recognize unavailable, skipping replacement[/dim]" + ) + progress.advance(upload_task) + continue + # Low score = more novel than the most redundant mapped file = replace + target = get_most_redundant_mapped_file(name, exclude=failed_deletes) + if target is None or candidate_score >= target[2]: + target_score_str = f"{target[2]:.3f}" if target is not None else "N/A" + progress.console.print( + f" [dim]⏭ {fname}: frigate {candidate_score:.3f} ≥ most redundant" + f" {target_score_str}, not more novel[/dim]" + ) + progress.advance(upload_task) + continue + target_frigate_file, _target_asset_id, target_score = target progress.console.print( - f" [dim]⏭ {fname}: score {new_score:.3f} ≤ worst mapped" - f" {worst_score_str}, skipping[/dim]" + f" 🔄 {fname}: frigate {candidate_score:.3f} < {target_score:.3f}," + f" replacing {target_frigate_file} (more novel)" ) - progress.advance(upload_task) - continue - # Delete the worst mapped file to make room for the better one - worst_frigate_file, _worst_asset_id, worst_score = worst - progress.console.print( - f" 🔄 {fname}: score {new_score:.3f} > {worst_score:.3f}," - f" replacing {worst_frigate_file}" - ) - if delete_frigate_person_files(name, [worst_frigate_file]): - remove_frigate_file(name, worst_frigate_file) - effective_count -= 1 - min_quality_score_for_slot = worst_score + if delete_frigate_person_files(name, [target_frigate_file]): + remove_frigate_file(name, target_frigate_file) + effective_count -= 1 + min_quality_score_for_slot = None # clear any blur-mode slot floor — Frigate uses a different score metric + else: + logger.warning(f"Failed to delete {target_frigate_file} for {name}, skipping replacement") + failed_deletes.add(target_frigate_file) + progress.advance(upload_task) + continue else: - logger.warning(f"Failed to delete {worst_frigate_file} for {name}, skipping replacement") - failed_deletes.add(worst_frigate_file) - progress.advance(upload_task) - continue + candidate_score = score_map.get(fname) + if candidate_score is None: + progress.console.print( + f" [dim]⏭ {fname}: no quality score, skipping replacement[/dim]" + ) + progress.advance(upload_task) + continue + target = get_lowest_quality_mapped_file(name, exclude=failed_deletes) + if target is None or candidate_score <= target[2]: + target_score_str = f"{target[2]:.3f}" if target is not None else "N/A" + progress.console.print( + f" [dim]⏭ {fname}: blur {candidate_score:.3f} ≤ worst" + f" {target_score_str}, skipping[/dim]" + ) + progress.advance(upload_task) + continue + target_frigate_file, _target_asset_id, target_score = target + progress.console.print( + f" 🔄 {fname}: blur {candidate_score:.3f} > {target_score:.3f}," + f" replacing {target_frigate_file}" + ) + if delete_frigate_person_files(name, [target_frigate_file]): + remove_frigate_file(name, target_frigate_file) + effective_count -= 1 + min_quality_score_for_slot = score_map.get(fname) + else: + logger.warning(f"Failed to delete {target_frigate_file} for {name}, skipping replacement") + failed_deletes.add(target_frigate_file) + progress.advance(upload_task) + continue for attempt in range(1, max_retries + 1): try: @@ -434,6 +536,7 @@ def upload_to_frigate(jobs: list[dict]) -> None: person_name=name, score=score_map.get(fname), crop_dims=dims_map.get(fname), + frigate_score=pre_fscore, ) actually_uploaded.append((fname, asset_id)) diff --git a/winnow/frigate_api.py b/winnow/frigate_api.py index b6d4950..0fc4f24 100644 --- a/winnow/frigate_api.py +++ b/winnow/frigate_api.py @@ -40,6 +40,22 @@ def get_frigate_face_counts() -> dict[str, int] | None: } +def get_all_frigate_person_files() -> dict[str, list[str]] | None: + """Return {person_name: [filename, ...]} for every person in Frigate. + + Single call used to build per-person snapshots before the upload loop, + avoiding one GET /api/faces per person. Returns None if unavailable. + """ + data = _get_faces_data() + if data is None: + return None + return { + name: files + for name, files in data.items() + if name != "train" and isinstance(files, list) + } + + def get_frigate_person_files(person_name: str) -> list[str] | None: """Return the list of training filenames for a person in Frigate. @@ -53,6 +69,38 @@ def get_frigate_person_files(person_name: str) -> list[str] | None: return files if isinstance(files, list) else [] +def recognize_face(file_path: str) -> tuple[str | None, float] | None: + """Submit an image to Frigate's recognize endpoint. + + Returns (face_name, score) where face_name is the best-matching person + (may be "unknown" if below Frigate's confidence threshold) and score is + the sigmoid-mapped cosine similarity (0-1) against that person's mean + embedding. + + Returns None if FRIGATE_URL is unset, the API is unreachable, no face is + detected, or face recognition is not enabled in Frigate. + """ + frigate_url = os.environ.get("FRIGATE_URL", "").rstrip("/") + if not frigate_url: + return None + try: + with open(file_path, "rb") as f: + resp = requests.post( + f"{frigate_url}/api/faces/recognize", + files={"file": (os.path.basename(file_path), f, "image/jpeg")}, + timeout=15, + ) + if not resp.ok: + return None + data = resp.json() + if data.get("success") and "score" in data: + return (data.get("face_name"), round(float(data["score"]), 4)) + return None + except Exception as e: + logger.debug(f"Frigate recognize failed for {file_path}: {e}") + return None + + def delete_frigate_person_files(person_name: str, filenames: list[str]) -> bool: """Delete specific training files for a person from Frigate. diff --git a/winnow/upload_tracker.py b/winnow/upload_tracker.py index 79d128b..3213c3b 100644 --- a/winnow/upload_tracker.py +++ b/winnow/upload_tracker.py @@ -11,13 +11,18 @@ Both are excluded from future candidate pools. To reset: by_person schema (frigate_uploaded_ids.json): { - "asset_ids": ["immich-id-1", ...], # all assets we attempted to upload - "scores": {"immich-id-1": 450.3}, # Laplacian blur variance at upload time - "frigate_files": {"PersonName-123.webp": "immich-id-1"}, # Frigate filename → asset ID - "crop_dims": {"immich-id-1": [640, 480]}, # crop pixel dimensions at upload time - "frigate_count": 42 # last known Frigate training image count + "asset_ids": ["immich-id-1", ...], # all assets we attempted to upload + "scores": {"immich-id-1": 450.3}, # Laplacian blur variance at upload time + "frigate_scores": {"immich-id-1": 0.87}, # Frigate recognition confidence (0-1) pre-upload + "frigate_files": {"PersonName-123.webp": "immich-id-1"}, # Frigate filename → asset ID + "crop_dims": {"immich-id-1": [640, 480]}, # crop pixel dimensions at upload time + "frigate_count": 42 # last known Frigate training image count } +frigate_scores stores pre-upload recognize scores (0-1 sigmoid-mapped cosine +similarity). High score = the existing training set already covers this face +condition well. Low score = a gap — novel/diverse for the training set. + frigate_files only contains files winnow uploaded — files added manually through Frigate's UI are never mapped here and are never touched by quality replacement. """ @@ -77,9 +82,10 @@ def _get_ids(entry: list | dict) -> list[str]: def _migrate_entry(entry: list | dict) -> dict: """Ensure by_person entry is in the current dict format.""" if isinstance(entry, list): - return {"asset_ids": sorted(entry), "scores": {}, "frigate_files": {}, "crop_dims": {}} + return {"asset_ids": sorted(entry), "scores": {}, "frigate_scores": {}, "frigate_files": {}, "crop_dims": {}} entry.setdefault("asset_ids", []) entry.setdefault("scores", {}) + entry.setdefault("frigate_scores", {}) entry.setdefault("frigate_files", {}) entry.setdefault("crop_dims", {}) return entry @@ -91,6 +97,7 @@ def _mark( person_name: str | None, score: float | None = None, crop_dims: tuple[int, int] | None = None, + frigate_score: float | None = None, ) -> None: data = _load(filename) flat_key = _flat_key(filename) @@ -107,6 +114,8 @@ def _mark( entry["scores"][asset_id] = round(score, 4) if crop_dims is not None: entry["crop_dims"][asset_id] = [crop_dims[0], crop_dims[1]] + if frigate_score is not None: + entry["frigate_scores"][asset_id] = round(frigate_score, 4) by_person[person_name] = entry _save(filename, data) @@ -126,8 +135,9 @@ def mark_uploaded( person_name: str | None = None, score: float | None = None, crop_dims: tuple[int, int] | None = None, + frigate_score: float | None = None, ) -> None: - _mark(UPLOAD_TRACKER_FILE, asset_id, person_name, score=score, crop_dims=crop_dims) + _mark(UPLOAD_TRACKER_FILE, asset_id, person_name, score=score, crop_dims=crop_dims, frigate_score=frigate_score) logger.debug(f"Marked {asset_id} as uploaded ({person_name})") @@ -136,6 +146,7 @@ def mark_rejected(asset_id: str, person_name: str | None = None) -> None: logger.debug(f"Marked {asset_id} as rejected ({person_name})") + def record_frigate_file(person_name: str, frigate_filename: str, asset_id: str) -> None: """Record the mapping from a Frigate training filename to an Immich asset ID.""" data = _load(UPLOAD_TRACKER_FILE) @@ -184,29 +195,78 @@ def get_tracked_frigate_filenames(person_name: str) -> set[str]: return set(entry["frigate_files"].keys()) +def has_frigate_scores(person_name: str) -> bool: + """Return True if any mapped file for this person has a stored Frigate recognition score.""" + data = _load(UPLOAD_TRACKER_FILE) + entry = _migrate_entry(data.get("by_person", {}).get(person_name, {})) + frigate_files = entry.get("frigate_files", {}) + frigate_scores = entry.get("frigate_scores", {}) + return any(asset_id in frigate_scores for asset_id in frigate_files.values()) + + def get_lowest_quality_mapped_file( person_name: str, exclude: set[str] | None = None ) -> tuple[str, str, float] | None: """Return (frigate_filename, asset_id, score) for the mapped file with the lowest - quality score, or None if no mapped files with known scores exist. + blur score, or None if no mapped files with known scores exist. - Pass `exclude` to skip files that failed to delete this run without removing - them from the tracker — they remain candidates on the next run. + Used for quality replacement when no Frigate scores are available. + Pass `exclude` to skip files that failed to delete this run. """ data = _load(UPLOAD_TRACKER_FILE) entry = _migrate_entry(data.get("by_person", {}).get(person_name, {})) frigate_files = entry.get("frigate_files", {}) - scores = entry.get("scores", {}) + blur_scores = entry.get("scores", {}) + candidates = [ - (frigate_filename, asset_id, scores[asset_id]) - for frigate_filename, asset_id in frigate_files.items() - if asset_id in scores and (exclude is None or frigate_filename not in exclude) + (ff, asset_id, blur_scores[asset_id]) + for ff, asset_id in frigate_files.items() + if (exclude is None or ff not in exclude) + and asset_id in blur_scores ] + if not candidates: return None return min(candidates, key=lambda x: x[2]) +def get_most_redundant_mapped_file( + person_name: str, exclude: set[str] | None = None +) -> tuple[str, str, float] | None: + """Return (frigate_filename, asset_id, score) for the mapped file with the highest + Frigate recognition score, or None if no mapped files with Frigate scores exist. + + High Frigate score = the training set already covers this face condition well + = the most redundant file and therefore the best replacement target. + Pass `exclude` to skip files that failed to delete this run. + """ + data = _load(UPLOAD_TRACKER_FILE) + entry = _migrate_entry(data.get("by_person", {}).get(person_name, {})) + frigate_files = entry.get("frigate_files", {}) + frigate_scores = entry.get("frigate_scores", {}) + + candidates = [ + (ff, asset_id, frigate_scores[asset_id]) + for ff, asset_id in frigate_files.items() + if (exclude is None or ff not in exclude) + and asset_id in frigate_scores + ] + + if not candidates: + return None + return max(candidates, key=lambda x: x[2]) + + +def get_frigate_filename_for_asset(person_name: str, asset_id: str) -> str | None: + """Return the Frigate training filename mapped to this asset ID, or None.""" + data = _load(UPLOAD_TRACKER_FILE) + entry = _migrate_entry(data.get("by_person", {}).get(person_name, {})) + for frigate_filename, aid in entry["frigate_files"].items(): + if aid == asset_id: + return frigate_filename + return None + + def find_by_crop_dimension(size: int) -> list[dict]: """Return all tracked crops whose width or height matches `size` pixels. @@ -220,6 +280,7 @@ def find_by_crop_dimension(size: int) -> list[dict]: scores = entry.get("scores", {}) frigate_files = entry.get("frigate_files", {}) asset_to_frigate = {v: k for k, v in frigate_files.items()} + frigate_scores = entry.get("frigate_scores", {}) for asset_id, dims in entry.get("crop_dims", {}).items(): w, h = dims[0], dims[1] if w == size or h == size: @@ -229,6 +290,7 @@ def find_by_crop_dimension(size: int) -> list[dict]: "width": w, "height": h, "blur_score": scores.get(asset_id), + "frigate_score": frigate_scores.get(asset_id), "frigate_filename": asset_to_frigate.get(asset_id), }) return results