Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
650629d3ed | ||
|
|
d63bcfc10b | ||
|
|
d7dfc1446a | ||
|
|
dfaa03de47 | ||
|
|
9d5741f626 | ||
|
|
d70a246a1c | ||
|
|
51cc7032eb | ||
|
|
105099c819 | ||
|
|
0afc9386c6 | ||
|
|
a59d05e7fd | ||
|
|
d0cb2e17b1 | ||
|
|
2dc26b5a3d | ||
|
|
fe4cfac7b5 | ||
|
|
ec074fd279 | ||
|
|
6018bf7222 | ||
|
|
4eb6e3169b | ||
|
|
f5ec9a0001 | ||
|
|
7dce4a5c71 | ||
|
|
56c802a245 | ||
|
|
cc092ec972 | ||
|
|
d6e4582401 | ||
|
|
a85bc31da9 | ||
|
|
3c602e2ef6 | ||
|
|
96b71798ad | ||
|
|
a7d4504db9 | ||
|
|
e05363f632 | ||
|
|
b276d686f8 | ||
|
|
a3e54dea7a | ||
|
|
f9482eec4d | ||
|
|
694f860b6d | ||
|
|
6e34d41036 | ||
|
|
a9c1114b86 | ||
|
|
19f1a5e03b | ||
|
|
0a8a0c16dd | ||
|
|
eb3abe2cca | ||
|
|
44b717d615 | ||
|
|
168a8e33b5 | ||
|
|
fd0bd213e8 | ||
|
|
7efe283e9a | ||
|
|
2dd911e9ea | ||
|
|
341c6b0e85 | ||
|
|
38fe4d6f0c | ||
|
|
6fb3d2f61d | ||
|
|
9c42da4d37 | ||
|
|
3888a5e6db | ||
|
|
68505aeb0b | ||
|
|
b804b13644 | ||
|
|
62bc1b70c5 | ||
|
|
67f1845687 | ||
|
|
39111d3a6a | ||
|
|
5553877c90 | ||
|
|
e4edf202fa |
@@ -36,15 +36,13 @@ env:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
name: Build (${{ matrix.platform }})
|
name: Build (linux/amd64)
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- platform: linux/amd64
|
- platform: linux/amd64
|
||||||
runner: ubuntu-latest
|
runner: ubuntu-latest
|
||||||
- platform: linux/arm64
|
|
||||||
runner: ubuntu-latest
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
packages: write
|
||||||
@@ -63,10 +61,6 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
ref: ${{ inputs.tag || github.ref }}
|
ref: ${{ inputs.tag || github.ref }}
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
if: matrix.platform == 'linux/arm64'
|
|
||||||
uses: docker/setup-qemu-action@v4
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v4
|
uses: docker/setup-buildx-action@v4
|
||||||
|
|
||||||
@@ -108,7 +102,7 @@ jobs:
|
|||||||
- name: Upload digest
|
- name: Upload digest
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: digest-${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
|
name: digest-amd64
|
||||||
path: /tmp/digests/*
|
path: /tmp/digests/*
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 1
|
retention-days: 1
|
||||||
|
|||||||
@@ -7,6 +7,74 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.4.10] - 2026-06-14
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **`MAX_AUTO_IMAGES` default lowered from `80` to `20`**: 20 diverse images is sufficient for Frigate's face recognition model; the previous default led to diminishing returns and longer runs.
|
||||||
|
|
||||||
|
## [0.4.9] - 2026-06-14
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **`FRIGATE_SCORE_CEILING` is now dynamic by default**: previously defaulted to `0` (disabled). Now unset (default) enables a self-calibrating novelty gate — below-cap candidates are skipped if their pre-upload Frigate score exceeds the most-redundant tracked file's score. This catches conditions already covered by manually-added Frigate images that winnow cannot track. Set `FRIGATE_SCORE_CEILING=0` to disable entirely; set a positive value (e.g. `0.85`) for a fixed hard ceiling.
|
||||||
|
- **Quality replacement branches consolidated**: the Frigate-score and blur-score replacement paths in the upload loop shared identical structure. Merged into a single code path parameterised by score source and comparison direction.
|
||||||
|
- **`MIN_FACE_COUNT` default raised from `0` to `3`**: people with fewer than 3 tagged photos produce degenerate training sets; skipping them by default avoids noisy runs.
|
||||||
|
- **`STRATEGY=adaptive`** is the new primary name for embedding-based diversity selection; `auto` remains a silent alias for backwards compatibility.
|
||||||
|
- **`MERGE_DUPLICATE_PEOPLE` and `TRACE_CROP_SIZE`** added to the README env var table (were in the codebase but undocumented).
|
||||||
|
- **CUDA version corrected** in the image tags table (was 13.3, actual base image is 12.8.1).
|
||||||
|
|
||||||
|
## [0.4.8] - 2026-06-14
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Tracker write-through cache**: `upload_tracker` now keeps an in-memory copy of each JSON file keyed by its resolved path. All reads after the first hit the cache instead of disk; writes go to both disk and cache atomically. Cuts per-person disk I/O in the upload loop from ~90 reads to ~1, with no API or behaviour changes.
|
||||||
|
|
||||||
|
## [0.4.7] - 2026-06-14
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **`_dedup_embeddings` pre-allocated buffer**: replaced the grow-on-keep `np.vstack` pattern with a pre-allocated `(Q, D)` buffer filled row-by-row. Eliminates O(K²) copy work and the GC pressure from K intermediate heap allocations while keeping identical arithmetic for the similarity checks.
|
||||||
|
- **`_kmedoids` cost computation vectorized**: the Python-level `sum(dist_matrix[i, medoids[labels[i]]] for i in range(n))` generator (called once per swap evaluation) is replaced with `dist_matrix[np.arange(n), np.array(medoids)[labels]].sum()` — a single numpy fancy-index + reduction, ~20–50× faster in the swap loop.
|
||||||
|
- **`_reconcile_frigate_mappings` single-write batch**: previously called `record_frigate_file` once per uploaded file, each doing a full JSON load + save (O(L) disk round-trips per person). Now builds the full `{frigate_filename: asset_id}` mapping dict and writes it in one `record_frigate_files_batch` call (O(1) disk round-trip).
|
||||||
|
|
||||||
|
## [0.4.6] - 2026-06-14
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **OOM when Immich returns many pages per person**: `fetch_all_assets` now stops fetching once 5000 assets have been collected — the diversity selection pool is already capped at 3000 items, so fetching up to 1,000,000 was wasteful and could exhaust memory on large libraries. 5000 provides ample headroom for the pool cap while bounding per-person memory to ~2 MB.
|
||||||
|
- **Non-dict items in Immich asset pages silently skipped**: a malformed or partially-null Immich response page could include `null` or non-object items in the assets array. These are now filtered at fetch time rather than causing `AttributeError` downstream.
|
||||||
|
|
||||||
|
## [0.4.5] - 2026-06-14
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Near-duplicate dedup O(N²) allocation**: `np.vstack(kept_normed)` was rebuilt on every loop iteration even for candidates that would be dropped; the stack is now rebuilt only when a new item is kept, reducing memory pressure significantly for large pools.
|
||||||
|
- **`quality_score` falsy-zero in dedup sort**: the sort key used `c.get("quality_score") or 0.0`, which treated a legitimate `quality_score=0.0` identically to a missing key. Changed to an explicit `None` check so zero is preserved as-is, and object-mode candidates (which have no `quality_score`) continue to sort stably to the back.
|
||||||
|
- **Post-dedup pool not re-checked against limit**: after near-duplicate removal the pool could silently shrink below the requested limit with no warning. A second `len < limit` guard now fires after dedup and emits the same "Only N embeddings" warning that the pre-dedup guard does.
|
||||||
|
- **`mark_rejected` could miss plain-text 400 bodies longer than 100 bytes**: `error_detail = resp.text[:100]` was being searched for the keyword `"face"` to gate `mark_rejected()`, so a response body with `"face"` after byte 100 would never mark the asset rejected and it would be retried on every future run. The `"face"` check now uses the full response body; truncation is kept only for the displayed snippet.
|
||||||
|
- **`_safe_person_dir` raised ValueError for all person names when `output_dir` resolved to `/`**: `base + os.sep` produced `"//"` when base was `"/"`, and valid paths like `/alice` don't start with `"//"`. Fixed by using `base` directly as the prefix when `base == os.sep`.
|
||||||
|
|
||||||
|
## [0.4.4] - 2026-06-14
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **`RESET_PERSON=*` bulk reset**: resets every tracked person at once (deletes their Frigate training files and clears tracker data). Any other value still resets that specific person by name. If a person is literally named `*` they are reset as part of the bulk operation, and a warning is printed to clarify this.
|
||||||
|
- **Near-duplicate removal before diversity selection**: a greedy dedup pass now runs after embedding collection and before clustering. Candidates within 0.20 cosine distance of a higher-quality image are dropped, eliminating burst shots and same-event lookalike photos that produce redundant training images. The best-quality frame from each near-identical group is kept. Dropped count is logged per person.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **HTTP 500 upload errors no longer show Frigate's misleading "Try restarting Frigate" message**: the response body is now logged at debug level only. HTTP 400 detail (e.g. "No face was detected") is still shown since it is actionable.
|
||||||
|
- **`RuntimeWarning: Mean of empty slice`** when a person has only one image after quality filtering: `_compute_adaptive_threshold` now returns the floor value immediately when there are no pairwise distances to sample, and the k-medoids cluster count is floored at 1 to prevent `k=0`.
|
||||||
|
- **Path traversal guard on output directory**: person names with `../` sequences or absolute paths (e.g. `/etc`) are now rejected before any filesystem operation, logging an error and skipping the job rather than writing outside the output tree.
|
||||||
|
|
||||||
|
## [0.4.3] - 2026-06-14
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **InsightFace landmark-based face crop alignment**: face crops for Frigate training are now aligned using InsightFace's `norm_crop` (ArcFace 112×112 alignment with 5-point facial landmarks). Previously, Immich's API returned only bounding boxes with no landmarks, so `align_face()` was dead code and crops were plain bbox slices — resulting in misaligned or partial crops (e.g. foreheads). The fix runs InsightFace detection on an expanded region around the Immich bbox, finds the nearest face, and uses its keypoints for proper alignment. Controlled by `ENABLE_FACE_ALIGNMENT` (default `true`).
|
||||||
|
- **Duplicate Immich person detection and handling**: when multiple Immich person records share the same name, winnow now detects this at startup and warns with a per-group summary. Without handling, two jobs would run for the same Frigate folder and overwrite each other's output. By default (`MERGE_DUPLICATE_PEOPLE=false`) only the first person per name is processed. Set `MERGE_DUPLICATE_PEOPLE=true` to permanently merge duplicate records inside Immich (keeps the person with the most assets).
|
||||||
|
|
||||||
## [0.4.2] - 2026-06-13
|
## [0.4.2] - 2026-06-13
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -36,6 +36,10 @@ CI runs both on every push and PR to `main` and `dev`. PRs must pass before merg
|
|||||||
- Keep the `CHANGELOG.md` entry in the `[Unreleased]` section updated.
|
- Keep the `CHANGELOG.md` entry in the `[Unreleased]` section updated.
|
||||||
- Commit messages should be plain English describing what changed and why.
|
- Commit messages should be plain English describing what changed and why.
|
||||||
|
|
||||||
|
## Development Tooling
|
||||||
|
|
||||||
|
Development uses Claude Code (Anthropic) for implementation assistance. All code is reviewed and the final call on design, behavior, and what ships is made by the maintainer. Contributions from humans are equally welcome.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
By submitting a contribution you agree that your work will be released under the project's [AGPLv3+ license](LICENSE).
|
By submitting a contribution you agree that your work will be released under the project's [AGPLv3+ license](LICENSE).
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
[](https://github.com/sudolulo/winnow/actions/workflows/docker-publish.yml) [](https://github.com/sudolulo/winnow/actions/workflows/test.yml) [](https://github.com/sudolulo/winnow/releases/latest) [](LICENSE) [](https://immich.app) [](https://frigate.video)
|
[](https://github.com/sudolulo/winnow/actions/workflows/docker-publish.yml) [](https://github.com/sudolulo/winnow/actions/workflows/test.yml) [](https://github.com/sudolulo/winnow/releases/latest) [](LICENSE) [](https://immich.app) [](https://frigate.video)
|
||||||
|
|
||||||
|
> **Note:** winnow's approach to training Frigate face recognition is not an officially documented workflow — results may vary.
|
||||||
|
|
||||||
> **Early Development — Use With Caution**
|
> **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.
|
> 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.
|
||||||
|
|
||||||
@@ -41,26 +43,34 @@ Immich library
|
|||||||
• Objects → SigLIP (Vision Transformer) → 768-dim vector
|
• Objects → SigLIP (Vision Transformer) → 768-dim vector
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
5. Diversity selection
|
5. Near-duplicate removal — greedy cosine-distance pass drops burst shots
|
||||||
|
and near-identical photos before clustering runs; the highest-quality
|
||||||
|
image from each near-duplicate group is kept
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
6. Diversity selection
|
||||||
• K-Medoids clustering → one representative per natural group
|
• K-Medoids clustering → one representative per natural group
|
||||||
• Farthest Point Sampling → fill remaining slots with maximally spread picks
|
• Farthest Point Sampling → fill remaining slots with maximally spread picks
|
||||||
• Hard example weighting — unusual angles and low-confidence detections
|
• Hard example weighting — low-confidence detections get a distance boost
|
||||||
are biased toward selection, since those are where models tend to fail
|
so unusual angles and harder looks are preferred over easy frontals
|
||||||
• Auto mode: stops when similarity to the existing set exceeds a threshold
|
• Adaptive mode: stops when the next candidate is too similar to those already
|
||||||
(20 % of median pairwise distance for faces, 10 % for objects)
|
selected (distance threshold = 20 % of median pairwise distance for
|
||||||
|
faces, 10 % for objects)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
6. Download full-resolution originals from Immich
|
7. Download full-resolution originals from Immich
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
7. Crop and process
|
8. Crop and process
|
||||||
• Face mode: EXIF-corrected, landmark-aligned 112×112 crop (ArcFace format)
|
• Face mode: EXIF-corrected, landmark-aligned 112×112 crop (ArcFace format)
|
||||||
• Object mode: YOLOv9c detection → one crop per matched instance
|
• Object mode: YOLOv9c detection → one crop per matched instance
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
8. Deliver
|
9. Deliver
|
||||||
• Face mode: upload crops to Frigate's face registration API
|
• Face mode: upload crops to Frigate's face registration API
|
||||||
↳ below MAX_AUTO_IMAGES — upload freely
|
↳ below MAX_AUTO_IMAGES — upload, unless the novelty gate
|
||||||
|
(FRIGATE_SCORE_CEILING) determines the candidate is already
|
||||||
|
covered by the current training set
|
||||||
↳ at cap + QUALITY_REPLACEMENT=true — with Frigate scoring active,
|
↳ at cap + QUALITY_REPLACEMENT=true — with Frigate scoring active,
|
||||||
swap the most redundant tracked image (highest pre-upload recognize
|
swap the most redundant tracked image (highest pre-upload recognize
|
||||||
score) if the candidate is more novel (lower score); falling back to
|
score) if the candidate is more novel (lower score); falling back to
|
||||||
@@ -70,7 +80,7 @@ Immich library
|
|||||||
• Object mode: save crops to disk → place into your Frigate data directory
|
• Object mode: save crops to disk → place into your Frigate data directory
|
||||||
```
|
```
|
||||||
|
|
||||||
Uploaded and rejected asset IDs are persisted across runs. The same image is never processed twice; Frigate rejections are permanently skipped unless `RETRY_REJECTED=true`.
|
Uploaded and rejected asset IDs are persisted across runs. The same image is never processed twice; rejected assets are permanently skipped unless `RETRY_REJECTED=true`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -88,7 +98,7 @@ Uploaded and rejected asset IDs are persisted across runs. The same image is nev
|
|||||||
|
|
||||||
| Tag | Arch | Acceleration |
|
| Tag | Arch | Acceleration |
|
||||||
| :-- | :-- | :-- |
|
| :-- | :-- | :-- |
|
||||||
| `:latest` | amd64 + arm64 | NVIDIA CUDA 13.3 (amd64) · requires [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) |
|
| `:latest` | amd64 + arm64 | NVIDIA CUDA 12.8 (amd64) · requires [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) |
|
||||||
| `:rocm` | amd64 | AMD ROCm · pass `/dev/kfd` + `/dev/dri` |
|
| `:rocm` | amd64 | AMD ROCm · pass `/dev/kfd` + `/dev/dri` |
|
||||||
| `:intel` | amd64 | Intel Arc / iGPU via OpenVINO · pass `/dev/dri`, set `OPENVINO_DEVICE=GPU` |
|
| `:intel` | amd64 | Intel Arc / iGPU via OpenVINO · pass `/dev/dri`, set `OPENVINO_DEVICE=GPU` |
|
||||||
| `:cpu` | amd64 + arm64 | CPU only · ~2 GB smaller · no GPU required |
|
| `:cpu` | amd64 + arm64 | CPU only · ~2 GB smaller · no GPU required |
|
||||||
@@ -171,10 +181,10 @@ In scheduled mode the process (and loaded models) stays resident between runs. T
|
|||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `TRAINING_MODE` | `face` | `face` — upload crops to Frigate; `object` — save crops to disk |
|
| `TRAINING_MODE` | `face` | `face` — upload crops to Frigate; `object` — save crops to disk |
|
||||||
| `STRATEGY` | `auto` | `auto` (embedding-based adaptive), `standard` (30 images), `broad` (100 images) |
|
| `STRATEGY` | `adaptive` | `adaptive` — embedding-based diversity selection, stops when candidates become redundant; `standard` — fixed 30 images; `broad` — fixed 100 images |
|
||||||
| `LIMIT` | *(unset)* | Exact image count — overrides `STRATEGY` |
|
| `LIMIT` | *(unset)* | Exact image count — overrides `STRATEGY` |
|
||||||
| `OBJECT_CLASS` | `dog` | Target class for object mode (any YOLO class: `dog`, `cat`, `car`, etc.) |
|
| `OBJECT_CLASS` | `dog` | Target class for object mode (any YOLO class: `dog`, `cat`, `car`, etc.) |
|
||||||
| `AUTO_MODE` | *(auto)* | Force non-interactive mode in a terminal; auto-detected otherwise |
|
| `AUTO_MODE` | *(auto)* | Skip interactive prompts and process all people unattended — auto-detected when no TTY is present (Docker, cron); set `true` to force in a terminal |
|
||||||
| `VERBOSE` | `false` | Enable DEBUG-level console output (log file is always DEBUG) |
|
| `VERBOSE` | `false` | Enable DEBUG-level console output (log file is always DEBUG) |
|
||||||
|
|
||||||
### People Filtering
|
### People Filtering
|
||||||
@@ -183,23 +193,31 @@ In scheduled mode the process (and loaded models) stays resident between runs. T
|
|||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `ONLY_PEOPLE` | *(unset)* | Comma-separated whitelist — process only these people |
|
| `ONLY_PEOPLE` | *(unset)* | Comma-separated whitelist — process only these people |
|
||||||
| `SKIP_PEOPLE` | *(unset)* | Comma-separated list — skip these people |
|
| `SKIP_PEOPLE` | *(unset)* | Comma-separated list — skip these people |
|
||||||
| `MIN_FACE_COUNT` | `0` | Skip people with fewer than N tagged assets in Immich |
|
| `MIN_FACE_COUNT` | `3` | Skip people with fewer than N tagged assets in Immich |
|
||||||
|
| `MERGE_DUPLICATE_PEOPLE` | `false` | When Immich has duplicate entries for the same person (same face split across multiple names), merge their asset pools before processing. Without this, each duplicate group emits a warning and is skipped |
|
||||||
| `YEARS_FILTER` | `10` | Ignore images older than N years |
|
| `YEARS_FILTER` | `10` | Ignore images older than N years |
|
||||||
|
|
||||||
### Image Quality
|
### Image Quality
|
||||||
|
|
||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
|
| `MAX_AUTO_IMAGES` | `20` | Maximum training images per person in Frigate |
|
||||||
|
| `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 |
|
||||||
|
|
||||||
|
#### Advanced Tuning *(calibrated — do not adjust)*
|
||||||
|
|
||||||
|
These defaults are tuned for Frigate's ArcFace requirements. winnow will warn on launch if any are set. Image quality issues caused by non-default values will not be investigated.
|
||||||
|
|
||||||
|
| Variable | Default | Description |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `ENABLE_FRIGATE_SCORES` | `true` | Call Frigate's recognize endpoint pre-upload to store diversity scores used for quality replacement. Adds ~200 ms per upload. Disabling also disables the below-cap novelty gate |
|
||||||
|
| `FRIGATE_SCORE_CEILING` | *(unset)* | Below-cap novelty gate. Unset: dynamic — skips candidates whose Frigate score exceeds the most-redundant tracked file's score, auto-calibrates each run. `0`: disable entirely. Positive value (e.g. `0.85`): fixed hard ceiling |
|
||||||
| `MIN_FACE_WIDTH` | `90` | 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) |
|
| `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 |
|
| `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 |
|
| `USE_FULL_RESOLUTION` | `true` | Download full-resolution originals rather than preview thumbnails |
|
||||||
| `MIN_CONFIDENCE` | `0.7` | Minimum Immich face detection confidence |
|
| `MIN_CONFIDENCE` | `0.7` | Minimum Immich face detection confidence |
|
||||||
| `BLUR_THRESHOLD` | `120.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 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
|
### GPU & Models
|
||||||
|
|
||||||
@@ -223,8 +241,9 @@ In scheduled mode the process (and loaded models) stays resident between runs. T
|
|||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `DRY_RUN` | `false` | Preview selection without downloading or uploading |
|
| `DRY_RUN` | `false` | Preview selection without downloading or uploading |
|
||||||
| `RETRY_REJECTED` | `false` | Re-attempt assets previously rejected by Frigate |
|
| `RETRY_REJECTED` | `false` | Re-attempt all previously rejected assets (low-confidence skips, Frigate rejections, and other permanent exclusions) |
|
||||||
| `RESET_PERSON` | *(unset)* | Clear upload history for one person and delete their winnow-managed Frigate training files so the next run starts fresh. Manually added Frigate files are never touched |
|
| `RESET_PERSON` | *(unset)* | Set to a person's name to clear their upload history and delete their winnow-managed Frigate training files so the next run starts fresh. Set to `*` to reset all tracked people at once. Manually added Frigate files are never touched |
|
||||||
|
| `TRACE_CROP_SIZE` | *(unset)* | Debug: print all tracked crops whose width or height matches this pixel value, then exit |
|
||||||
|
|
||||||
### Scheduling
|
### Scheduling
|
||||||
|
|
||||||
@@ -245,7 +264,7 @@ uv run winnow
|
|||||||
|
|
||||||
Requires Python 3.13+ and [uv](https://astral.sh/uv). An NVIDIA, AMD, or Intel GPU is recommended — CPU mode works but embedding computation is slower.
|
Requires Python 3.13+ and [uv](https://astral.sh/uv). An NVIDIA, AMD, or Intel GPU is recommended — CPU mode works but embedding computation is slower.
|
||||||
|
|
||||||
When run with a terminal attached, winnow starts an interactive session: select which people to process and choose a strategy (auto, standard, broad, or a custom count) per person. Without a TTY — Docker, cron, or `AUTO_MODE=true` — it processes all people automatically using the configured defaults.
|
When run with a terminal attached, winnow starts an interactive session: select which people to process and choose a strategy (adaptive, standard, broad, or a custom count) per person. Without a TTY — Docker, cron, or `AUTO_MODE=true` — it processes all people unattended using the configured defaults.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ services:
|
|||||||
# - SKIP_PEOPLE=Unknown # Comma-separated; skip these people
|
# - SKIP_PEOPLE=Unknown # Comma-separated; skip these people
|
||||||
# - MIN_FACE_COUNT=5 # Skip people with fewer than N assets in Immich
|
# - MIN_FACE_COUNT=5 # Skip people with fewer than N assets in Immich
|
||||||
# - YEARS_FILTER=10 # Only include images from the last N years (default: 10)
|
# - YEARS_FILTER=10 # Only include images from the last N years (default: 10)
|
||||||
|
# - MERGE_DUPLICATE_PEOPLE=true # Auto-merge Immich people with the same name (keeps most assets)
|
||||||
|
|
||||||
# ── Image Quality ─────────────────────────────────────────────────────
|
# ── Image Quality ─────────────────────────────────────────────────────
|
||||||
# - MIN_FACE_WIDTH=50 # Minimum face width in pixels (default: 50)
|
# - MIN_FACE_WIDTH=50 # Minimum face width in pixels (default: 50)
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "0.4.2"
|
version = "0.4.10"
|
||||||
description = "Selects diverse, high-quality photos from Immich as training data for Frigate face recognition and object classification."
|
description = "Selects diverse, high-quality photos from Immich as training data for Frigate face recognition and object classification."
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
requires-python = ">=3.13"
|
requires-python = ">=3.13"
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ def test_config_loads_defaults(monkeypatch):
|
|||||||
assert cfg.OUTPUT_DIR == "./frigate_train"
|
assert cfg.OUTPUT_DIR == "./frigate_train"
|
||||||
assert cfg.YEARS_FILTER == 10
|
assert cfg.YEARS_FILTER == 10
|
||||||
assert cfg.MIN_FACE_WIDTH == 90
|
assert cfg.MIN_FACE_WIDTH == 90
|
||||||
assert cfg.MIN_FACE_COUNT == 0
|
assert cfg.MIN_FACE_COUNT == 3
|
||||||
assert cfg.BLUR_THRESHOLD == 120.0
|
assert cfg.BLUR_THRESHOLD == 120.0
|
||||||
assert cfg.MIN_CONFIDENCE == 0.7
|
assert cfg.MIN_CONFIDENCE == 0.7
|
||||||
assert cfg.MAX_AUTO_IMAGES == 80
|
assert cfg.MAX_AUTO_IMAGES == 20
|
||||||
assert cfg.QUALITY_REPLACEMENT is True
|
assert cfg.QUALITY_REPLACEMENT is True
|
||||||
assert cfg.FACE_MARGIN == 0.15
|
assert cfg.FACE_MARGIN == 0.15
|
||||||
assert cfg.USE_FULL_RESOLUTION is True
|
assert cfg.USE_FULL_RESOLUTION is True
|
||||||
|
|||||||
@@ -2348,7 +2348,7 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "0.4.1"
|
version = "0.4.8"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "croniter" },
|
{ name = "croniter" },
|
||||||
|
|||||||
+122
-2
@@ -9,7 +9,7 @@ from rich.prompt import Confirm
|
|||||||
|
|
||||||
from .config import Config, ConfigManager
|
from .config import Config, ConfigManager
|
||||||
from .executor import execute_jobs, upload_to_frigate
|
from .executor import execute_jobs, upload_to_frigate
|
||||||
from .immich_api import get_people
|
from .immich_api import get_people, merge_people
|
||||||
from .jobs import _show_preview, auto_configure, interactive_configure
|
from .jobs import _show_preview, auto_configure, interactive_configure
|
||||||
from .log_config import console, setup_logging
|
from .log_config import console, setup_logging
|
||||||
from .upload_tracker import find_by_crop_dimension, get_person_summary, reset_person
|
from .upload_tracker import find_by_crop_dimension, get_person_summary, reset_person
|
||||||
@@ -51,6 +51,97 @@ def _handle_trace_crop(size_str: str) -> None:
|
|||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_duplicate_people(people: list[dict]) -> list[dict]:
|
||||||
|
"""Warn about or merge Immich people that share the same name.
|
||||||
|
|
||||||
|
Duplicates arise when Immich creates separate person records for the same
|
||||||
|
individual (e.g. unmerged face clusters). Without handling, winnow would
|
||||||
|
run multiple jobs for the same Frigate folder and overwrite its own output,
|
||||||
|
leaving far fewer training images than expected.
|
||||||
|
|
||||||
|
With MERGE_DUPLICATE_PEOPLE=false (default): prints a warning, skips the
|
||||||
|
smaller duplicates so only the person with the most assets is processed,
|
||||||
|
and returns a deduplicated people list.
|
||||||
|
With MERGE_DUPLICATE_PEOPLE=true: merges each duplicate group inside
|
||||||
|
Immich via its API (permanently combines the face records), then
|
||||||
|
re-fetches the people list so the rest of the run sees the merged state.
|
||||||
|
"""
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
by_name: dict[str, list[dict]] = defaultdict(list)
|
||||||
|
for p in people:
|
||||||
|
name = (p.get("name") or "").strip()
|
||||||
|
if name:
|
||||||
|
by_name[name].append(p)
|
||||||
|
|
||||||
|
duplicates = {name: ps for name, ps in by_name.items() if len(ps) > 1}
|
||||||
|
if not duplicates:
|
||||||
|
return people
|
||||||
|
|
||||||
|
if not Config.MERGE_DUPLICATE_PEOPLE:
|
||||||
|
rprint("\n[bold yellow]⚠ Duplicate person names detected in Immich:[/bold yellow]")
|
||||||
|
for name, ps in sorted(duplicates.items()):
|
||||||
|
ordered = sorted(ps, key=lambda x: x.get("assetCount", 0), reverse=True)
|
||||||
|
entries = ", ".join(
|
||||||
|
f"[dim]{p['id'][:8]}…[/dim] ({p.get('assetCount', 0)} assets)"
|
||||||
|
for p in ordered
|
||||||
|
)
|
||||||
|
rprint(f" [yellow]{name}[/yellow] → {len(ps)} people: {entries}")
|
||||||
|
skipped = ordered[1:]
|
||||||
|
rprint(
|
||||||
|
f" [dim] Processing largest only "
|
||||||
|
f"({ordered[0].get('assetCount', 0)} assets). "
|
||||||
|
f"Skipping {len(skipped)} smaller duplicate(s) to avoid overwriting output.[/dim]"
|
||||||
|
)
|
||||||
|
rprint(
|
||||||
|
" [dim]Set MERGE_DUPLICATE_PEOPLE=true to permanently merge duplicates "
|
||||||
|
"inside Immich (keeps the person with the most assets).[/dim]\n"
|
||||||
|
)
|
||||||
|
# Return deduplicated list — keep only the largest per name so that
|
||||||
|
# downstream job creation never runs two jobs for the same Frigate folder.
|
||||||
|
skip_ids = {
|
||||||
|
p["id"]
|
||||||
|
for ps in duplicates.values()
|
||||||
|
for p in sorted(ps, key=lambda x: x.get("assetCount", 0), reverse=True)[1:]
|
||||||
|
}
|
||||||
|
return [p for p in people if p["id"] not in skip_ids]
|
||||||
|
|
||||||
|
# Auto-merge: survivor = largest asset count, rest merge into it inside Immich
|
||||||
|
merged_any = False
|
||||||
|
for name, ps in sorted(duplicates.items()):
|
||||||
|
ordered = sorted(ps, key=lambda x: x.get("assetCount", 0), reverse=True)
|
||||||
|
survivor = ordered[0]
|
||||||
|
merge_ids = [p["id"] for p in ordered[1:]]
|
||||||
|
rprint(
|
||||||
|
f" [cyan]Merging {name!r} inside Immich:[/cyan] keeping "
|
||||||
|
f"[dim]{survivor['id'][:8]}…[/dim] ({survivor.get('assetCount', 0)} assets), "
|
||||||
|
f"absorbing {len(merge_ids)} smaller duplicate(s)..."
|
||||||
|
)
|
||||||
|
if merge_people(survivor["id"], merge_ids):
|
||||||
|
rprint(f" [green]✓ Merged {name!r}[/green]")
|
||||||
|
merged_any = True
|
||||||
|
else:
|
||||||
|
rprint(f" [red]✗ Failed to merge {name!r}[/red]")
|
||||||
|
|
||||||
|
if merged_any:
|
||||||
|
rprint(" [dim]Re-fetching people after merge...[/dim]")
|
||||||
|
return get_people()
|
||||||
|
|
||||||
|
return people
|
||||||
|
|
||||||
|
|
||||||
|
_UNSUPPORTED_VARS = [
|
||||||
|
"ENABLE_FRIGATE_SCORES",
|
||||||
|
"FRIGATE_SCORE_CEILING",
|
||||||
|
"MIN_FACE_WIDTH",
|
||||||
|
"FACE_MARGIN",
|
||||||
|
"ENABLE_FACE_ALIGNMENT",
|
||||||
|
"USE_FULL_RESOLUTION",
|
||||||
|
"MIN_CONFIDENCE",
|
||||||
|
"BLUR_THRESHOLD",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
"""Entry point for winnow CLI."""
|
"""Entry point for winnow CLI."""
|
||||||
try:
|
try:
|
||||||
@@ -66,6 +157,17 @@ def main() -> None:
|
|||||||
[dim]Immich -> Frigate Training Data Curator[/dim]
|
[dim]Immich -> Frigate Training Data Curator[/dim]
|
||||||
""")
|
""")
|
||||||
|
|
||||||
|
set_unsupported = [v for v in _UNSUPPORTED_VARS if os.environ.get(v)]
|
||||||
|
if set_unsupported:
|
||||||
|
console.print(
|
||||||
|
f"[bold yellow]⚠ Advanced tuning vars set: "
|
||||||
|
f"{', '.join(set_unsupported)}[/bold yellow]"
|
||||||
|
)
|
||||||
|
console.print(
|
||||||
|
"[dim] These defaults are calibrated for Frigate's ArcFace requirements. "
|
||||||
|
"Image quality issues caused by non-default values will not be investigated.[/dim]\n"
|
||||||
|
)
|
||||||
|
|
||||||
ConfigManager.get().interactive_setup()
|
ConfigManager.get().interactive_setup()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -77,9 +179,25 @@ def main() -> None:
|
|||||||
rprint(f"Server: [dim]{Config.IMMICH_URL}[/dim]")
|
rprint(f"Server: [dim]{Config.IMMICH_URL}[/dim]")
|
||||||
rprint(f"Output: [dim]{Config.OUTPUT_DIR}[/dim]")
|
rprint(f"Output: [dim]{Config.OUTPUT_DIR}[/dim]")
|
||||||
|
|
||||||
# Handle RESET_PERSON before anything else
|
# Handle RESET_PERSON before anything else.
|
||||||
|
# RESET_PERSON=* resets every tracked person; any other value resets
|
||||||
|
# that specific person by name.
|
||||||
reset_person_name = os.environ.get("RESET_PERSON", "").strip()
|
reset_person_name = os.environ.get("RESET_PERSON", "").strip()
|
||||||
if reset_person_name:
|
if reset_person_name:
|
||||||
|
if reset_person_name == "*":
|
||||||
|
names = list(get_person_summary().keys())
|
||||||
|
if "*" in names:
|
||||||
|
rprint(
|
||||||
|
"[yellow]Note: a person literally named '*' exists in the tracker "
|
||||||
|
"and will be reset along with everyone else.[/yellow]"
|
||||||
|
)
|
||||||
|
if names:
|
||||||
|
for name in names:
|
||||||
|
reset_person(name)
|
||||||
|
rprint(f"[bold yellow]Reset tracking data for all {len(names)} people.[/bold yellow]")
|
||||||
|
else:
|
||||||
|
rprint("[dim]No tracking data to reset.[/dim]")
|
||||||
|
else:
|
||||||
reset_person(reset_person_name)
|
reset_person(reset_person_name)
|
||||||
rprint(f"[bold yellow]Reset tracking data for: {reset_person_name}[/bold yellow]")
|
rprint(f"[bold yellow]Reset tracking data for: {reset_person_name}[/bold yellow]")
|
||||||
|
|
||||||
@@ -103,6 +221,8 @@ def main() -> None:
|
|||||||
rprint("[bold red]Could not fetch people from Immich. Check URL/Key.[/bold red]")
|
rprint("[bold red]Could not fetch people from Immich. Check URL/Key.[/bold red]")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
people = _handle_duplicate_people(people)
|
||||||
|
|
||||||
# Auto mode when no TTY (Docker, cron, pipes) — the primary use case.
|
# Auto mode when no TTY (Docker, cron, pipes) — the primary use case.
|
||||||
# A TTY means local interactive use; AUTO_MODE=true overrides that for scripting.
|
# A TTY means local interactive use; AUTO_MODE=true overrides that for scripting.
|
||||||
auto_mode = not sys.stdin.isatty() or os.environ.get("AUTO_MODE", "").lower() in ("true", "1", "yes")
|
auto_mode = not sys.stdin.isatty() or os.environ.get("AUTO_MODE", "").lower() in ("true", "1", "yes")
|
||||||
|
|||||||
+9
-6
@@ -29,13 +29,14 @@ class _Config:
|
|||||||
MIN_FACE_WIDTH: int = 90
|
MIN_FACE_WIDTH: int = 90
|
||||||
BLUR_THRESHOLD: float = 120.0
|
BLUR_THRESHOLD: float = 120.0
|
||||||
MIN_CONFIDENCE: float = 0.7
|
MIN_CONFIDENCE: float = 0.7
|
||||||
MAX_AUTO_IMAGES: int = 80
|
MAX_AUTO_IMAGES: int = 20
|
||||||
QUALITY_REPLACEMENT: bool = True
|
QUALITY_REPLACEMENT: bool = True
|
||||||
FRIGATE_SCORE_CEILING: float = 0.0
|
FRIGATE_SCORE_CEILING: float | None = None
|
||||||
ENABLE_FRIGATE_SCORES: bool = True
|
ENABLE_FRIGATE_SCORES: bool = True
|
||||||
|
|
||||||
# People filtering
|
# People filtering
|
||||||
MIN_FACE_COUNT: int = 0
|
MIN_FACE_COUNT: int = 3
|
||||||
|
MERGE_DUPLICATE_PEOPLE: bool = False
|
||||||
|
|
||||||
# Output quality
|
# Output quality
|
||||||
FACE_MARGIN: float = 0.15
|
FACE_MARGIN: float = 0.15
|
||||||
@@ -59,12 +60,14 @@ class _Config:
|
|||||||
self.OUTPUT_DIR = os.getenv("OUTPUT_DIR", "./frigate_train")
|
self.OUTPUT_DIR = os.getenv("OUTPUT_DIR", "./frigate_train")
|
||||||
self.YEARS_FILTER = int(os.getenv("YEARS_FILTER", "10"))
|
self.YEARS_FILTER = int(os.getenv("YEARS_FILTER", "10"))
|
||||||
self.MIN_FACE_WIDTH = int(os.getenv("MIN_FACE_WIDTH", "90"))
|
self.MIN_FACE_WIDTH = int(os.getenv("MIN_FACE_WIDTH", "90"))
|
||||||
self.MIN_FACE_COUNT = int(os.getenv("MIN_FACE_COUNT", "0"))
|
self.MIN_FACE_COUNT = int(os.getenv("MIN_FACE_COUNT", "3"))
|
||||||
|
self.MERGE_DUPLICATE_PEOPLE = os.getenv("MERGE_DUPLICATE_PEOPLE", "false").lower() in ("true", "1", "yes")
|
||||||
self.BLUR_THRESHOLD = float(os.getenv("BLUR_THRESHOLD", "120.0"))
|
self.BLUR_THRESHOLD = float(os.getenv("BLUR_THRESHOLD", "120.0"))
|
||||||
self.MIN_CONFIDENCE = float(os.getenv("MIN_CONFIDENCE", "0.7"))
|
self.MIN_CONFIDENCE = float(os.getenv("MIN_CONFIDENCE", "0.7"))
|
||||||
self.MAX_AUTO_IMAGES = int(os.getenv("MAX_AUTO_IMAGES", "80"))
|
self.MAX_AUTO_IMAGES = int(os.getenv("MAX_AUTO_IMAGES", "20"))
|
||||||
self.QUALITY_REPLACEMENT = os.getenv("QUALITY_REPLACEMENT", "true").lower() in ("true", "1", "yes")
|
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"))
|
_ceiling_env = os.getenv("FRIGATE_SCORE_CEILING", "").strip()
|
||||||
|
self.FRIGATE_SCORE_CEILING = float(_ceiling_env) if _ceiling_env else None
|
||||||
self.ENABLE_FRIGATE_SCORES = os.getenv("ENABLE_FRIGATE_SCORES", "true").lower() in ("true", "1", "yes")
|
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.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.USE_FULL_RESOLUTION = os.getenv("USE_FULL_RESOLUTION", "true").lower() in ("true", "1", "yes")
|
||||||
|
|||||||
+77
-4
@@ -281,7 +281,21 @@ def _select_by_embedding(
|
|||||||
logger.warning(f"Only {len(valid_candidates)} valid embeddings. Returning all.")
|
logger.warning(f"Only {len(valid_candidates)} valid embeddings. Returning all.")
|
||||||
return valid_candidates
|
return valid_candidates
|
||||||
|
|
||||||
# --- Phase 5: Cluster-aware selection ---
|
# --- Phase 5: Near-duplicate removal ---
|
||||||
|
# Burst shots and repeated near-identical photos produce embeddings that are
|
||||||
|
# close but not identical, so FPS doesn't filter them out on its own.
|
||||||
|
# Greedily drop any candidate within DEDUP_THRESHOLD cosine distance of a
|
||||||
|
# higher-quality image already in the kept set.
|
||||||
|
embeddings, valid_candidates, confidence_scores = _dedup_embeddings(
|
||||||
|
embeddings, valid_candidates, confidence_scores
|
||||||
|
)
|
||||||
|
|
||||||
|
# Re-check after dedup: pool may have shrunk below limit
|
||||||
|
if limit != "auto" and len(valid_candidates) < limit:
|
||||||
|
logger.warning(f"Only {len(valid_candidates)} embeddings after near-duplicate removal. Returning all.")
|
||||||
|
return valid_candidates
|
||||||
|
|
||||||
|
# --- Phase 6: Cluster-aware selection ---
|
||||||
return _cluster_aware_selection(
|
return _cluster_aware_selection(
|
||||||
embeddings,
|
embeddings,
|
||||||
valid_candidates,
|
valid_candidates,
|
||||||
@@ -291,6 +305,63 @@ def _select_by_embedding(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# Near-Duplicate Removal
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
_DEDUP_THRESHOLD = 0.20 # cosine distance — burst shots ~0.01-0.05, same-event similar shots ~0.10-0.20
|
||||||
|
|
||||||
|
|
||||||
|
def _dedup_embeddings(
|
||||||
|
embeddings: list,
|
||||||
|
candidates: list,
|
||||||
|
confidence_scores: list,
|
||||||
|
) -> tuple[list, list, list]:
|
||||||
|
"""Greedy near-duplicate removal before clustering.
|
||||||
|
|
||||||
|
Sorts by quality score descending (best first), then for each candidate
|
||||||
|
drops it if any already-kept embedding is within _DEDUP_THRESHOLD cosine
|
||||||
|
distance. This eliminates burst-shot near-duplicates while preserving the
|
||||||
|
highest-quality representative from each near-identical group.
|
||||||
|
"""
|
||||||
|
if len(embeddings) < 2:
|
||||||
|
return embeddings, candidates, confidence_scores
|
||||||
|
|
||||||
|
emb_matrix = np.vstack(embeddings)
|
||||||
|
norms = np.linalg.norm(emb_matrix, axis=1, keepdims=True)
|
||||||
|
emb_normed = emb_matrix / np.maximum(norms, 1e-8)
|
||||||
|
|
||||||
|
# Sort by quality descending so the best image in each near-duplicate group wins.
|
||||||
|
# Use explicit None check so a legitimate quality_score=0.0 isn't treated as missing.
|
||||||
|
quality_scores = [qs if (qs := c.get("quality_score")) is not None else 0.0 for c in candidates]
|
||||||
|
order = sorted(range(len(candidates)), key=lambda i: quality_scores[i], reverse=True)
|
||||||
|
|
||||||
|
kept_indices = []
|
||||||
|
# Pre-allocate a max-size buffer and fill row-by-row — eliminates the O(K²)
|
||||||
|
# copy overhead from vstack-on-keep while keeping identical arithmetic.
|
||||||
|
kept_buf = np.empty((len(order), emb_normed.shape[1]), dtype=emb_normed.dtype)
|
||||||
|
n_kept = 0
|
||||||
|
|
||||||
|
for i in order:
|
||||||
|
if n_kept > 0:
|
||||||
|
sims = emb_normed[i] @ kept_buf[:n_kept].T
|
||||||
|
if np.any(sims > 1 - _DEDUP_THRESHOLD):
|
||||||
|
continue
|
||||||
|
kept_buf[n_kept] = emb_normed[i]
|
||||||
|
n_kept += 1
|
||||||
|
kept_indices.append(i)
|
||||||
|
|
||||||
|
dropped = len(embeddings) - len(kept_indices)
|
||||||
|
if dropped:
|
||||||
|
logger.info(f"Near-duplicate removal dropped {dropped} images (threshold {_DEDUP_THRESHOLD}).")
|
||||||
|
|
||||||
|
return (
|
||||||
|
[embeddings[i] for i in kept_indices],
|
||||||
|
[candidates[i] for i in kept_indices],
|
||||||
|
[confidence_scores[i] for i in kept_indices],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# K-Medoids (Lightweight Implementation)
|
# K-Medoids (Lightweight Implementation)
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -322,7 +393,7 @@ def _kmedoids(dist_matrix: np.ndarray, k: int, max_iter: int = 50) -> tuple[list
|
|||||||
# Iterative swap step
|
# Iterative swap step
|
||||||
medoids = list(medoids)
|
medoids = list(medoids)
|
||||||
labels = np.argmin(dist_matrix[:, medoids], axis=1)
|
labels = np.argmin(dist_matrix[:, medoids], axis=1)
|
||||||
cost = sum(dist_matrix[i, medoids[labels[i]]] for i in range(n))
|
cost = dist_matrix[np.arange(n), np.array(medoids)[labels]].sum()
|
||||||
|
|
||||||
for _ in range(max_iter):
|
for _ in range(max_iter):
|
||||||
improved = False
|
improved = False
|
||||||
@@ -337,7 +408,7 @@ def _kmedoids(dist_matrix: np.ndarray, k: int, max_iter: int = 50) -> tuple[list
|
|||||||
new_medoids = medoids.copy()
|
new_medoids = medoids.copy()
|
||||||
new_medoids[m_idx] = cand
|
new_medoids[m_idx] = cand
|
||||||
new_labels = np.argmin(dist_matrix[:, new_medoids], axis=1)
|
new_labels = np.argmin(dist_matrix[:, new_medoids], axis=1)
|
||||||
new_cost = sum(dist_matrix[i, new_medoids[new_labels[i]]] for i in range(n))
|
new_cost = dist_matrix[np.arange(n), np.array(new_medoids)[new_labels]].sum()
|
||||||
if new_cost < cost:
|
if new_cost < cost:
|
||||||
medoids = new_medoids
|
medoids = new_medoids
|
||||||
labels = new_labels
|
labels = new_labels
|
||||||
@@ -373,6 +444,8 @@ def _compute_adaptive_threshold(emb_normed: np.ndarray, entity_type: str) -> flo
|
|||||||
# Compute pairwise cosine distances for the sample
|
# Compute pairwise cosine distances for the sample
|
||||||
pairwise = 1 - sample @ sample.T
|
pairwise = 1 - sample @ sample.T
|
||||||
upper_tri = pairwise[np.triu_indices(len(sample), k=1)]
|
upper_tri = pairwise[np.triu_indices(len(sample), k=1)]
|
||||||
|
if len(upper_tri) == 0:
|
||||||
|
return 0.05
|
||||||
median_dist = float(np.median(upper_tri))
|
median_dist = float(np.median(upper_tri))
|
||||||
|
|
||||||
# Faces: 20% of median (tighter — want fewer, more distinct images)
|
# Faces: 20% of median (tighter — want fewer, more distinct images)
|
||||||
@@ -421,7 +494,7 @@ def _cluster_aware_selection(
|
|||||||
target = Config.MAX_AUTO_IMAGES if limit == "auto" else limit
|
target = Config.MAX_AUTO_IMAGES if limit == "auto" else limit
|
||||||
|
|
||||||
# --- Stage 1: K-Medoids clustering ---
|
# --- Stage 1: K-Medoids clustering ---
|
||||||
k = min(max(5, target // 4), n // 3, n) # e.g., 5-20 clusters
|
k = min(max(5, target // 4), max(1, n // 3), n) # e.g., 1-20 clusters
|
||||||
logger.debug(f"Clustering {n} embeddings into {k} groups (K-Medoids)...")
|
logger.debug(f"Clustering {n} embeddings into {k} groups (K-Medoids)...")
|
||||||
|
|
||||||
# Compute full cosine distance matrix
|
# Compute full cosine distance matrix
|
||||||
|
|||||||
+106
-64
@@ -31,13 +31,29 @@ from .upload_tracker import (
|
|||||||
has_frigate_scores,
|
has_frigate_scores,
|
||||||
mark_rejected,
|
mark_rejected,
|
||||||
mark_uploaded,
|
mark_uploaded,
|
||||||
record_frigate_file,
|
record_frigate_files_batch,
|
||||||
remove_frigate_file,
|
remove_frigate_file,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_person_dir(output_dir: str, person_name: str) -> str:
|
||||||
|
"""Return the output subdirectory for a person, raising ValueError on path traversal.
|
||||||
|
|
||||||
|
os.path.join silently discards output_dir when person_name is absolute,
|
||||||
|
and '../..' sequences resolve outside the tree. Both are rejected here.
|
||||||
|
"""
|
||||||
|
candidate = os.path.realpath(os.path.join(output_dir, person_name))
|
||||||
|
base = os.path.realpath(output_dir)
|
||||||
|
# Use the base path as its own prefix when it's the filesystem root ("/"),
|
||||||
|
# otherwise append os.sep — avoids the false "//" double-slash when base == "/".
|
||||||
|
base_prefix = base if base == os.sep else base + os.sep
|
||||||
|
if not candidate.startswith(base_prefix) and candidate != base:
|
||||||
|
raise ValueError(f"Person name {person_name!r} escapes output directory — skipping")
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
def _reconcile_frigate_mappings(
|
def _reconcile_frigate_mappings(
|
||||||
person_name: str,
|
person_name: str,
|
||||||
known_files_before: set[str],
|
known_files_before: set[str],
|
||||||
@@ -84,10 +100,12 @@ def _reconcile_frigate_mappings(
|
|||||||
except (ValueError, IndexError):
|
except (ValueError, IndexError):
|
||||||
return 0.0
|
return 0.0
|
||||||
|
|
||||||
for (fname, asset_id), frigate_file in zip(uploaded, sorted(new_files, key=_ts)):
|
mappings = {
|
||||||
if asset_id:
|
frigate_file: asset_id
|
||||||
record_frigate_file(person_name, frigate_file, asset_id)
|
for (_, asset_id), frigate_file in zip(uploaded, sorted(new_files, key=_ts))
|
||||||
logger.debug(f"{person_name}: batch-mapped {target} Frigate file(s)")
|
if asset_id
|
||||||
|
}
|
||||||
|
record_frigate_files_batch(person_name, mappings)
|
||||||
elif len(new_files) > target:
|
elif len(new_files) > target:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"{person_name}: {len(new_files)} new Frigate files for {target} uploads"
|
f"{person_name}: {len(new_files)} new Frigate files for {target} uploads"
|
||||||
@@ -155,6 +173,18 @@ def execute_jobs(jobs: list[dict]) -> None:
|
|||||||
|
|
||||||
use_full_res = Config.USE_FULL_RESOLUTION
|
use_full_res = Config.USE_FULL_RESOLUTION
|
||||||
|
|
||||||
|
# Load InsightFace app for landmark-based crop alignment (face mode only).
|
||||||
|
# The model is already resident from the diversity/embedding phase, so this
|
||||||
|
# is just a singleton lookup — no load cost.
|
||||||
|
insightface_app = None
|
||||||
|
if any(j["config"].get("mode", "face") == "face" for j in jobs) and Config.ENABLE_FACE_ALIGNMENT:
|
||||||
|
try:
|
||||||
|
from .embeddings import get_insightface_app
|
||||||
|
|
||||||
|
insightface_app = get_insightface_app()
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"InsightFace unavailable for crop alignment: {e}")
|
||||||
|
|
||||||
with Progress(
|
with Progress(
|
||||||
SpinnerColumn(),
|
SpinnerColumn(),
|
||||||
TextColumn("[progress.description]{task.description}"),
|
TextColumn("[progress.description]{task.description}"),
|
||||||
@@ -170,7 +200,11 @@ def execute_jobs(jobs: list[dict]) -> None:
|
|||||||
name, mode = person["name"], config.get("mode", "face")
|
name, mode = person["name"], config.get("mode", "face")
|
||||||
|
|
||||||
job_task = progress.add_task(f"Processing {name}...", total=len(assets))
|
job_task = progress.add_task(f"Processing {name}...", total=len(assets))
|
||||||
person_dir = os.path.join(Config.OUTPUT_DIR, name)
|
try:
|
||||||
|
person_dir = _safe_person_dir(Config.OUTPUT_DIR, name)
|
||||||
|
except ValueError as e:
|
||||||
|
logger.error(str(e))
|
||||||
|
continue
|
||||||
# Face crops are transient (uploaded then discarded); wipe before each run.
|
# Face crops are transient (uploaded then discarded); wipe before each run.
|
||||||
# Object crops are the deliverable; preserve them across runs.
|
# Object crops are the deliverable; preserve them across runs.
|
||||||
if mode == "face" and os.path.isdir(person_dir):
|
if mode == "face" and os.path.isdir(person_dir):
|
||||||
@@ -197,6 +231,7 @@ def execute_jobs(jobs: list[dict]) -> None:
|
|||||||
f"[yellow]Skipped {asset['id']}"
|
f"[yellow]Skipped {asset['id']}"
|
||||||
f" (detection confidence {conf:.2f} < {Config.MIN_CONFIDENCE})[/yellow]"
|
f" (detection confidence {conf:.2f} < {Config.MIN_CONFIDENCE})[/yellow]"
|
||||||
)
|
)
|
||||||
|
mark_rejected(asset["id"], person_name=name)
|
||||||
progress.advance(job_task)
|
progress.advance(job_task)
|
||||||
progress.advance(overall_task)
|
progress.advance(overall_task)
|
||||||
continue
|
continue
|
||||||
@@ -216,7 +251,7 @@ def execute_jobs(jobs: list[dict]) -> None:
|
|||||||
progress.console.print(f"[red]Failed download {asset['id']}[/red]")
|
progress.console.print(f"[red]Failed download {asset['id']}[/red]")
|
||||||
else:
|
else:
|
||||||
saved = (
|
saved = (
|
||||||
process_face_mode(img, asset, person, person_dir, count)
|
process_face_mode(img, asset, person, person_dir, count, insightface_app=insightface_app)
|
||||||
if mode == "face"
|
if mode == "face"
|
||||||
else process_object_mode(img, config, person_dir, count)
|
else process_object_mode(img, config, person_dir, count)
|
||||||
if mode == "object"
|
if mode == "object"
|
||||||
@@ -293,7 +328,11 @@ def upload_to_frigate(jobs: list[dict]) -> None:
|
|||||||
object_jobs = [j for j in jobs if j["config"].get("mode") == "object"]
|
object_jobs = [j for j in jobs if j["config"].get("mode") == "object"]
|
||||||
for job in object_jobs:
|
for job in object_jobs:
|
||||||
name = job["person"]["name"]
|
name = job["person"]["name"]
|
||||||
person_dir = os.path.join(Config.OUTPUT_DIR, name)
|
try:
|
||||||
|
person_dir = _safe_person_dir(Config.OUTPUT_DIR, name)
|
||||||
|
except ValueError as e:
|
||||||
|
logger.error(str(e))
|
||||||
|
continue
|
||||||
rprint(f" [dim]📁 {name} (object): crops saved to {person_dir} — copy to Frigate manually[/dim]")
|
rprint(f" [dim]📁 {name} (object): crops saved to {person_dir} — copy to Frigate manually[/dim]")
|
||||||
|
|
||||||
frigate_url = os.environ.get("FRIGATE_URL", "")
|
frigate_url = os.environ.get("FRIGATE_URL", "")
|
||||||
@@ -343,7 +382,11 @@ def upload_to_frigate(jobs: list[dict]) -> None:
|
|||||||
if " " in name:
|
if " " in name:
|
||||||
progress.console.print(f" ℹ️ URL-encoded name for Frigate API: '{name}' → '{encoded_name}'")
|
progress.console.print(f" ℹ️ URL-encoded name for Frigate API: '{name}' → '{encoded_name}'")
|
||||||
|
|
||||||
person_dir = os.path.join(Config.OUTPUT_DIR, name)
|
try:
|
||||||
|
person_dir = _safe_person_dir(Config.OUTPUT_DIR, name)
|
||||||
|
except ValueError as e:
|
||||||
|
logger.error(str(e))
|
||||||
|
continue
|
||||||
if not os.path.isdir(person_dir):
|
if not os.path.isdir(person_dir):
|
||||||
progress.console.print(f" [dim]⏭️ {name}: no output directory, skipping[/dim]")
|
progress.console.print(f" [dim]⏭️ {name}: no output directory, skipping[/dim]")
|
||||||
continue
|
continue
|
||||||
@@ -364,6 +407,8 @@ def upload_to_frigate(jobs: list[dict]) -> None:
|
|||||||
# Snapshot live Frigate files for post-upload reconciliation diff only.
|
# Snapshot live Frigate files for post-upload reconciliation diff only.
|
||||||
# effective_count is sourced from the tracker (mapped files) so that
|
# effective_count is sourced from the tracker (mapped files) so that
|
||||||
# manually-added Frigate files don't consume winnow's managed quota.
|
# manually-added Frigate files don't consume winnow's managed quota.
|
||||||
|
# Replacement targets also come exclusively from the tracker, so manually
|
||||||
|
# added files are never selected for deletion — only winnow-uploaded ones.
|
||||||
_snapshot = (
|
_snapshot = (
|
||||||
all_frigate_files.get(name, []) if all_frigate_files is not None
|
all_frigate_files.get(name, []) if all_frigate_files is not None
|
||||||
else get_frigate_person_files(name)
|
else get_frigate_person_files(name)
|
||||||
@@ -438,14 +483,28 @@ def upload_to_frigate(jobs: list[dict]) -> None:
|
|||||||
if _result is not None and (_result[0] or "").casefold() == name.casefold():
|
if _result is not None and (_result[0] or "").casefold() == name.casefold():
|
||||||
pre_fscore = _result[1]
|
pre_fscore = _result[1]
|
||||||
|
|
||||||
# Ceiling check: skip if the existing training set already covers this
|
# Below-cap novelty gate: skip candidates already covered by the Frigate model,
|
||||||
# face condition well. Applies below cap only — at cap, replacement logic
|
# including conditions learned from manually-added images winnow can't track.
|
||||||
# drives the decision.
|
# pre_fscore is None on the first run (pre_run_count == 0 skips recognize_face
|
||||||
if not at_cap and Config.FRIGATE_SCORE_CEILING > 0 and pre_run_count > 0:
|
# above), so this block never fires on the first run without an extra guard.
|
||||||
if pre_fscore is not None and pre_fscore > Config.FRIGATE_SCORE_CEILING:
|
if not at_cap and pre_fscore is not None:
|
||||||
|
_ceiling = Config.FRIGATE_SCORE_CEILING
|
||||||
|
if _ceiling is None:
|
||||||
|
# Dynamic default: bar = most-redundant tracked file's Frigate score.
|
||||||
|
# Falls back to uploading freely when no tracked scores exist yet.
|
||||||
|
_bar = get_most_redundant_mapped_file(name)
|
||||||
|
_skip = _bar is not None and pre_fscore > _bar[2]
|
||||||
|
_bar_str = f"most redundant tracked {_bar[2]:.2f}" if _bar else ""
|
||||||
|
elif _ceiling == 0.0:
|
||||||
|
_skip = False # explicitly disabled
|
||||||
|
_bar_str = ""
|
||||||
|
else:
|
||||||
|
_skip = pre_fscore > _ceiling
|
||||||
|
_bar_str = f"ceiling {_ceiling:.2f}"
|
||||||
|
if _skip:
|
||||||
progress.console.print(
|
progress.console.print(
|
||||||
f" [dim]⏭ {fname}: Frigate score {pre_fscore:.2f}"
|
f" [dim]⏭ {fname}: Frigate score {pre_fscore:.2f}"
|
||||||
f" > ceiling {Config.FRIGATE_SCORE_CEILING:.2f}, already covered[/dim]"
|
f" > {_bar_str}, already covered[/dim]"
|
||||||
)
|
)
|
||||||
progress.advance(upload_task)
|
progress.advance(upload_task)
|
||||||
continue
|
continue
|
||||||
@@ -459,65 +518,45 @@ def upload_to_frigate(jobs: list[dict]) -> None:
|
|||||||
using_fscore = person_has_fscores and Config.ENABLE_FRIGATE_SCORES
|
using_fscore = person_has_fscores and Config.ENABLE_FRIGATE_SCORES
|
||||||
if using_fscore:
|
if using_fscore:
|
||||||
candidate_score = pre_fscore
|
candidate_score = pre_fscore
|
||||||
if candidate_score is None:
|
get_target = get_most_redundant_mapped_file
|
||||||
progress.console.print(
|
score_label, better_note = "frigate", " (more novel)"
|
||||||
f" [dim]⏭ {fname}: Frigate recognize unavailable, skipping replacement[/dim]"
|
no_score_msg = "Frigate recognize unavailable, skipping replacement"
|
||||||
)
|
|
||||||
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" 🔄 {fname}: frigate {candidate_score:.3f} < {target_score:.3f},"
|
|
||||||
f" replacing {target_frigate_file} (more novel)"
|
|
||||||
)
|
|
||||||
if delete_frigate_person_files(name, [target_frigate_file]):
|
|
||||||
remove_frigate_file(name, target_frigate_file)
|
|
||||||
person_has_fscores = has_frigate_scores(name)
|
|
||||||
effective_count -= 1
|
|
||||||
# clear any blur-mode slot floor — Frigate uses a different score metric
|
|
||||||
min_quality_score_for_slot = None
|
|
||||||
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:
|
else:
|
||||||
candidate_score = score_map.get(fname)
|
candidate_score = score_map.get(fname)
|
||||||
|
get_target = get_lowest_quality_mapped_file
|
||||||
|
score_label, better_note = "blur", ""
|
||||||
|
no_score_msg = "no quality score, skipping replacement"
|
||||||
|
|
||||||
if candidate_score is None:
|
if candidate_score is None:
|
||||||
|
progress.console.print(f" [dim]⏭ {fname}: {no_score_msg}[/dim]")
|
||||||
|
progress.advance(upload_task)
|
||||||
|
continue
|
||||||
|
|
||||||
|
target = get_target(name, exclude=failed_deletes)
|
||||||
|
not_better = target is None or (
|
||||||
|
candidate_score >= target[2] if using_fscore else candidate_score <= target[2]
|
||||||
|
)
|
||||||
|
if not_better:
|
||||||
|
target_str = f"{target[2]:.3f}" if target is not None else "N/A"
|
||||||
|
op = "<" if using_fscore else ">"
|
||||||
progress.console.print(
|
progress.console.print(
|
||||||
f" [dim]⏭ {fname}: no quality score, skipping replacement[/dim]"
|
f" [dim]⏭ {fname}: {score_label} {candidate_score:.3f}"
|
||||||
)
|
f" not {op} {target_str}, skipping[/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)
|
progress.advance(upload_task)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
target_frigate_file, _target_asset_id, target_score = target
|
target_frigate_file, _target_asset_id, target_score = target
|
||||||
|
op = "<" if using_fscore else ">"
|
||||||
progress.console.print(
|
progress.console.print(
|
||||||
f" 🔄 {fname}: blur {candidate_score:.3f} > {target_score:.3f},"
|
f" 🔄 {fname}: {score_label} {candidate_score:.3f} {op} {target_score:.3f},"
|
||||||
f" replacing {target_frigate_file}"
|
f" replacing {target_frigate_file}{better_note}"
|
||||||
)
|
)
|
||||||
if delete_frigate_person_files(name, [target_frigate_file]):
|
if delete_frigate_person_files(name, [target_frigate_file]):
|
||||||
remove_frigate_file(name, target_frigate_file)
|
remove_frigate_file(name, target_frigate_file)
|
||||||
person_has_fscores = has_frigate_scores(name)
|
person_has_fscores = has_frigate_scores(name)
|
||||||
effective_count -= 1
|
effective_count -= 1
|
||||||
min_quality_score_for_slot = score_map.get(fname)
|
min_quality_score_for_slot = None if using_fscore else candidate_score
|
||||||
else:
|
else:
|
||||||
logger.warning(f"Failed to delete {target_frigate_file} for {name}, skipping replacement")
|
logger.warning(f"Failed to delete {target_frigate_file} for {name}, skipping replacement")
|
||||||
failed_deletes.add(target_frigate_file)
|
failed_deletes.add(target_frigate_file)
|
||||||
@@ -564,13 +603,16 @@ def upload_to_frigate(jobs: list[dict]) -> None:
|
|||||||
progress.console.print(
|
progress.console.print(
|
||||||
f" [red]✗ {fname}: HTTP {resp.status_code} (after {max_retries} attempts)[/red]"
|
f" [red]✗ {fname}: HTTP {resp.status_code} (after {max_retries} attempts)[/red]"
|
||||||
)
|
)
|
||||||
|
full_body = resp.text
|
||||||
try:
|
try:
|
||||||
error_detail = resp.json().get("message", resp.text[:100])
|
error_detail = resp.json().get("message", full_body[:100])
|
||||||
progress.console.print(f" [dim]{error_detail}[/dim]")
|
|
||||||
except Exception:
|
except Exception:
|
||||||
error_detail = resp.text[:100]
|
error_detail = full_body[:100]
|
||||||
|
if resp.status_code == 400:
|
||||||
progress.console.print(f" [dim]{error_detail}[/dim]")
|
progress.console.print(f" [dim]{error_detail}[/dim]")
|
||||||
if resp.status_code == 400 and "face" in error_detail.lower():
|
else:
|
||||||
|
logger.debug(f"{fname} HTTP {resp.status_code}: {error_detail}")
|
||||||
|
if resp.status_code == 400 and "face" in full_body.lower():
|
||||||
asset_id = asset_map.get(fname)
|
asset_id = asset_map.get(fname)
|
||||||
if asset_id:
|
if asset_id:
|
||||||
mark_rejected(asset_id, person_name=name)
|
mark_rejected(asset_id, person_name=name)
|
||||||
|
|||||||
@@ -69,13 +69,15 @@ def process_face_mode(
|
|||||||
output_dir: str,
|
output_dir: str,
|
||||||
count: int,
|
count: int,
|
||||||
min_width: int | None = None,
|
min_width: int | None = None,
|
||||||
|
insightface_app=None,
|
||||||
) -> tuple[int, int] | None:
|
) -> tuple[int, int] | None:
|
||||||
"""Crop face based on Immich metadata and save to output directory.
|
"""Crop face based on Immich metadata and save to output directory.
|
||||||
|
|
||||||
Returns (width, height) of the saved crop, or None if no crop was saved.
|
Returns (width, height) of the saved crop, or None if no crop was saved.
|
||||||
If face alignment is enabled and landmarks are available, produces
|
When insightface_app is provided and ENABLE_FACE_ALIGNMENT is True,
|
||||||
an aligned 112x112 crop. Otherwise falls back to bounding box crop
|
re-detects the face in the Immich bbox region using InsightFace to get
|
||||||
with configurable margin.
|
precise landmarks for a proper 112x112 aligned crop. Falls back to
|
||||||
|
bounding box crop with configurable margin if alignment is unavailable.
|
||||||
"""
|
"""
|
||||||
min_width = min_width or Config.MIN_FACE_WIDTH
|
min_width = min_width or Config.MIN_FACE_WIDTH
|
||||||
|
|
||||||
@@ -109,18 +111,51 @@ def process_face_mode(
|
|||||||
logger.debug(f"Face too small ({face_w:.1f}x{face_h:.1f})")
|
logger.debug(f"Face too small ({face_w:.1f}x{face_h:.1f})")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Try face alignment if enabled and landmarks available
|
# Re-detect face with InsightFace for landmark-based alignment.
|
||||||
|
# Immich's /api/faces endpoint does not include landmarks, so the
|
||||||
|
# align_face fallback below never fires without this step.
|
||||||
|
if insightface_app is not None and Config.ENABLE_FACE_ALIGNMENT:
|
||||||
|
try:
|
||||||
|
# Expand the Immich bbox by 50% to give InsightFace enough context
|
||||||
|
# for detection and alignment, then search for the face nearest the
|
||||||
|
# centre of that region (handles group photos at the boundary).
|
||||||
|
pad_x, pad_y = face_w * 0.5, face_h * 0.5
|
||||||
|
search_box = (
|
||||||
|
max(0, x1 - pad_x),
|
||||||
|
max(0, y1 - pad_y),
|
||||||
|
min(img_w, x2 + pad_x),
|
||||||
|
min(img_h, y2 + pad_y),
|
||||||
|
)
|
||||||
|
search_crop = img.crop(search_box)
|
||||||
|
detected = insightface_app.get(np.asarray(search_crop))
|
||||||
|
if detected:
|
||||||
|
cx, cy = search_crop.width / 2, search_crop.height / 2
|
||||||
|
best = min(
|
||||||
|
detected,
|
||||||
|
key=lambda f: abs((f.bbox[0] + f.bbox[2]) / 2 - cx)
|
||||||
|
+ abs((f.bbox[1] + f.bbox[3]) / 2 - cy),
|
||||||
|
)
|
||||||
|
kps = getattr(best, "kps", None)
|
||||||
|
if kps is not None and np.asarray(kps).shape == (5, 2):
|
||||||
|
aligned = align_face(search_crop, kps)
|
||||||
|
if aligned is not None:
|
||||||
|
_save_jpeg(aligned, os.path.join(output_dir, f"{count}.jpg"))
|
||||||
|
return aligned.size
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"InsightFace re-detection failed for {asset.get('id')}: {e}")
|
||||||
|
|
||||||
|
# Landmark alignment from Immich metadata (Immich does not currently
|
||||||
|
# expose landmarks, so this path is a future-proofing fallback)
|
||||||
if Config.ENABLE_FACE_ALIGNMENT:
|
if Config.ENABLE_FACE_ALIGNMENT:
|
||||||
landmarks = face_info.get("landmarks") or face_info.get("landmark")
|
landmarks = face_info.get("landmarks") or face_info.get("landmark")
|
||||||
if landmarks:
|
if landmarks:
|
||||||
# Scale landmarks
|
|
||||||
scaled_landmarks = [[lm[0] * scale_x, lm[1] * scale_y] for lm in landmarks]
|
scaled_landmarks = [[lm[0] * scale_x, lm[1] * scale_y] for lm in landmarks]
|
||||||
aligned = align_face(img, scaled_landmarks)
|
aligned = align_face(img, scaled_landmarks)
|
||||||
if aligned is not None:
|
if aligned is not None:
|
||||||
_save_jpeg(aligned, os.path.join(output_dir, f"{count}.jpg"))
|
_save_jpeg(aligned, os.path.join(output_dir, f"{count}.jpg"))
|
||||||
return aligned.size
|
return aligned.size
|
||||||
|
|
||||||
# Fall back to bounding box crop with configurable margin
|
# Final fallback: bounding box crop with configurable margin
|
||||||
margin = Config.FACE_MARGIN
|
margin = Config.FACE_MARGIN
|
||||||
margin_x, margin_y = face_w * margin, face_h * margin
|
margin_x, margin_y = face_w * margin, face_h * margin
|
||||||
crop_box = (
|
crop_box = (
|
||||||
|
|||||||
+23
-2
@@ -14,6 +14,7 @@ from .config import Config, get_headers
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
MAX_PAGES = 1000 # Safety limit for pagination
|
MAX_PAGES = 1000 # Safety limit for pagination
|
||||||
|
_MAX_ASSETS_PER_PERSON = 5000 # Stop fetching after this many — diversity pool is capped at 3000 anyway
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -45,6 +46,26 @@ def get_people() -> list[dict]:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def merge_people(survivor_id: str, merge_ids: list[str]) -> bool:
|
||||||
|
"""Merge duplicate people into survivor via Immich's merge endpoint.
|
||||||
|
|
||||||
|
The survivor (identified by survivor_id) absorbs all faces and assets
|
||||||
|
from the people in merge_ids, which are then removed from Immich.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
resp = requests.put(
|
||||||
|
f"{Config.IMMICH_URL}/api/people/{survivor_id}/merge",
|
||||||
|
headers={**get_headers(), "Content-Type": "application/json"},
|
||||||
|
json={"ids": merge_ids},
|
||||||
|
timeout=30,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return True
|
||||||
|
except requests.RequestException as e:
|
||||||
|
logger.error(f"Failed to merge people into {survivor_id}: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def fetch_all_assets(person: dict) -> list[dict]:
|
def fetch_all_assets(person: dict) -> list[dict]:
|
||||||
"""Fetch all assets for a person with pagination."""
|
"""Fetch all assets for a person with pagination."""
|
||||||
name = person.get("name", "Unknown")
|
name = person.get("name", "Unknown")
|
||||||
@@ -75,10 +96,10 @@ def fetch_all_assets(person: dict) -> list[dict]:
|
|||||||
if not page_assets:
|
if not page_assets:
|
||||||
break
|
break
|
||||||
|
|
||||||
assets.extend(page_assets)
|
assets.extend(a for a in page_assets if isinstance(a, dict))
|
||||||
logger.debug(f"Fetched page {page}, total: {len(assets)}")
|
logger.debug(f"Fetched page {page}, total: {len(assets)}")
|
||||||
|
|
||||||
if len(page_assets) < page_size:
|
if len(page_assets) < page_size or len(assets) >= _MAX_ASSETS_PER_PERSON:
|
||||||
break
|
break
|
||||||
|
|
||||||
except (requests.RequestException, ValueError) as e:
|
except (requests.RequestException, ValueError) as e:
|
||||||
|
|||||||
+4
-3
@@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
# Strategy presets: (limit, mode_name)
|
# Strategy presets: (limit, mode_name)
|
||||||
STRATEGY_PRESETS = {
|
STRATEGY_PRESETS = {
|
||||||
"1": ("auto", "Auto Diversity"),
|
"1": ("auto", "Adaptive Diversity"),
|
||||||
"2": (30, "Standard (30)"),
|
"2": (30, "Standard (30)"),
|
||||||
"3": (100, "Broad (100)"),
|
"3": (100, "Broad (100)"),
|
||||||
}
|
}
|
||||||
@@ -31,7 +31,7 @@ def _get_strategy_choice(has_embedding: bool, entity_type: str) -> tuple[int | s
|
|||||||
model_name = "InsightFace" if entity_type == "face" else "SigLIP"
|
model_name = "InsightFace" if entity_type == "face" else "SigLIP"
|
||||||
|
|
||||||
if has_embedding:
|
if has_embedding:
|
||||||
rprint(" [bold]1.[/bold] Auto (Objective Diversity) [green][Recommended][/green]")
|
rprint(" [bold]1.[/bold] Adaptive Diversity [green][Recommended][/green]")
|
||||||
rprint(" [dim]• Dynamically selects images until redundancy starts[/dim]")
|
rprint(" [dim]• Dynamically selects images until redundancy starts[/dim]")
|
||||||
rprint(" [bold]2.[/bold] Standard (30 images)")
|
rprint(" [bold]2.[/bold] Standard (30 images)")
|
||||||
rprint(" [bold]3.[/bold] Broad (100 images)")
|
rprint(" [bold]3.[/bold] Broad (100 images)")
|
||||||
@@ -77,7 +77,8 @@ def _resolve_strategy(strategy: str, has_embedding: bool) -> tuple[int | str, st
|
|||||||
return int(custom_limit), "smart"
|
return int(custom_limit), "smart"
|
||||||
|
|
||||||
strategy_map = {
|
strategy_map = {
|
||||||
"auto": ("auto", "smart"),
|
"adaptive": ("auto", "smart"),
|
||||||
|
"auto": ("auto", "smart"), # legacy alias for adaptive
|
||||||
"standard": (30, "smart"),
|
"standard": (30, "smart"),
|
||||||
"broad": (100, "smart"),
|
"broad": (100, "smart"),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,11 @@ logger = logging.getLogger(__name__)
|
|||||||
UPLOAD_TRACKER_FILE = "frigate_uploaded_ids.json"
|
UPLOAD_TRACKER_FILE = "frigate_uploaded_ids.json"
|
||||||
REJECT_TRACKER_FILE = "frigate_rejected_ids.json"
|
REJECT_TRACKER_FILE = "frigate_rejected_ids.json"
|
||||||
|
|
||||||
|
# Write-through in-memory cache keyed by the resolved file path.
|
||||||
|
# Reduces per-call JSON reads from O(calls) to O(1) after the first load.
|
||||||
|
# Keyed by full path so tests with isolated tmp dirs never share entries.
|
||||||
|
_cache: dict[str, dict] = {}
|
||||||
|
|
||||||
|
|
||||||
def _tracker_path(filename: str) -> Path:
|
def _tracker_path(filename: str) -> Path:
|
||||||
try:
|
try:
|
||||||
@@ -50,18 +55,23 @@ def _tracker_path(filename: str) -> Path:
|
|||||||
|
|
||||||
def _load(filename: str) -> dict:
|
def _load(filename: str) -> dict:
|
||||||
path = _tracker_path(filename)
|
path = _tracker_path(filename)
|
||||||
if not path.exists():
|
key = str(path)
|
||||||
return {}
|
if key in _cache:
|
||||||
|
return _cache[key]
|
||||||
|
data: dict = {}
|
||||||
|
if path.exists():
|
||||||
try:
|
try:
|
||||||
with open(path) as f:
|
with open(path) as f:
|
||||||
return json.load(f)
|
data = json.load(f)
|
||||||
except (json.JSONDecodeError, OSError) as e:
|
except (json.JSONDecodeError, OSError) as e:
|
||||||
logger.warning(f"Could not load tracker {filename}: {e}")
|
logger.warning(f"Could not load tracker {filename}: {e}")
|
||||||
return {}
|
_cache[key] = data
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
def _save(filename: str, data: dict) -> None:
|
def _save(filename: str, data: dict) -> None:
|
||||||
path = _tracker_path(filename)
|
path = _tracker_path(filename)
|
||||||
|
_cache[str(path)] = data # keep cache consistent with what we write
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(path, "w") as f:
|
with open(path, "w") as f:
|
||||||
json.dump(data, f, indent=2)
|
json.dump(data, f, indent=2)
|
||||||
@@ -161,6 +171,19 @@ def record_frigate_file(person_name: str, frigate_filename: str, asset_id: str)
|
|||||||
logger.debug(f"Mapped Frigate file {frigate_filename} → {asset_id} ({person_name})")
|
logger.debug(f"Mapped Frigate file {frigate_filename} → {asset_id} ({person_name})")
|
||||||
|
|
||||||
|
|
||||||
|
def record_frigate_files_batch(person_name: str, mappings: dict[str, str]) -> None:
|
||||||
|
"""Record multiple Frigate filename → asset_id mappings in a single load/save."""
|
||||||
|
if not mappings:
|
||||||
|
return
|
||||||
|
data = _load(UPLOAD_TRACKER_FILE)
|
||||||
|
by_person = data.setdefault("by_person", {})
|
||||||
|
entry = _migrate_entry(by_person.get(person_name, {}))
|
||||||
|
entry["frigate_files"].update(mappings)
|
||||||
|
by_person[person_name] = entry
|
||||||
|
_save(UPLOAD_TRACKER_FILE, data)
|
||||||
|
logger.debug(f"Batch-mapped {len(mappings)} Frigate file(s) for {person_name}")
|
||||||
|
|
||||||
|
|
||||||
def remove_frigate_file(person_name: str, frigate_filename: str) -> None:
|
def remove_frigate_file(person_name: str, frigate_filename: str) -> None:
|
||||||
"""Remove a Frigate filename from the mapping after it has been deleted.
|
"""Remove a Frigate filename from the mapping after it has been deleted.
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user