From faa7f5f61a7d92b02188230e7d30882d72983c93 Mon Sep 17 00:00:00 2001 From: Daniel Date: Sun, 22 Nov 2026 11:22:12 +0100 Subject: [PATCH] feat: date-from-ocr workflow, assets ocr, and structured search filters Add `client-workflow date-from-ocr`, which sets an asset's capture year from a year Immich's OCR found in the image (e.g. on scanned prints): - sources: --album-id/--album-name, asset IDs or Immich web links (positional or --ids-file), or --all (whole library, pre-filtered server-side by one OCR search per year, then an OCR check of each hit) - report by default (with web links, --json); --yes applies only unambiguous single-asset changes (YYYY-06-01, tag immich-admin-cli/date-from-ocr) and is refused with --all - --interactive (terminal only) reviews hits grouped by album: [s]kip [t]his [a]lbum [n]ext album [y]ear [o]pen [q]uit; [a]lbum lists every album asset with old -> new date and asks again, tagging propagated assets immich-admin-cli/date-from-ocr-album Also: - new `assets ocr` command (getAssetOcr) - every command that takes asset IDs now also accepts Immich asset links - `search metadata` now uses only the structured filter/orderBy shape. The deprecated flat fields made every filtered search fail with 400 on current servers, because --order sent orderBy alongside them. Trashed assets stay excluded (trashedAt eq null), --taken-after/--taken-before now actually filter, and --type/--order are validated - SearchPager never sends the deprecated page field with the new shape Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- docs/client-workflows.md | 21 + immich-admin-cli/SKILL.md | 77 ++- internal/commands/assets.go | 1 + internal/commands/assets_ocr.go | 72 +++ internal/commands/clientworkflow.go | 1 + .../commands/clientworkflow_datefromocr.go | 530 ++++++++++++++++++ .../clientworkflow_datefromocr_test.go | 186 ++++++ .../commands/datefromocr_integration_test.go | 85 +++ internal/commands/helpers.go | 23 +- internal/commands/search.go | 123 ++-- internal/commands/search_test.go | 98 ++++ internal/commands/skill_best_practices.md | 20 +- internal/workflows/datefromocr.go | 275 +++++++++ internal/workflows/datefromocr_test.go | 63 +++ internal/workflows/progress.go | 5 +- internal/workflows/searchcursor.go | 8 +- internal/workflows/searchcursor_test.go | 19 + internal/workflows/searchfilter.go | 36 ++ 19 files changed, 1572 insertions(+), 79 deletions(-) create mode 100644 internal/commands/assets_ocr.go create mode 100644 internal/commands/clientworkflow_datefromocr.go create mode 100644 internal/commands/clientworkflow_datefromocr_test.go create mode 100644 internal/commands/datefromocr_integration_test.go create mode 100644 internal/commands/search_test.go create mode 100644 internal/workflows/datefromocr.go create mode 100644 internal/workflows/datefromocr_test.go create mode 100644 internal/workflows/searchfilter.go diff --git a/README.md b/README.md index 8956473..8d66a66 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ | Albums and sharing | Create, rename, delete, and manage album assets; add users to matching albums in bulk; merge albums; download or mirror an album locally | `albums --help`, `cw add-users-to-album-with-pattern`, `cw merge-album`, `cw download-album` | | Find and organize | Search by filename, type, camera, location, date, status, OCR, or description; emit pipeable asset IDs; manage tags and tag assignments | `search metadata --help`, `tags --help` | | Repair and replace | Replace an asset while preserving its Immich metadata; locate missing thumbnails; repair malformed JPEG/TIFF files; remove Google Takeout JSON sidecars | `cw replace-asset`, `cw find-no-thumbhash`, `cw repair-assets` | -| Date and duplicate assistance | Check and correct assets that do not fit date-named albums; find visually similar library assets for a local image | `cw fix-album-dates`, `cw find-similar` | +| Date and duplicate assistance | Check and correct assets that do not fit date-named albums; set capture years from years printed in scanned photos (OCR); find visually similar library assets for a local image | `cw fix-album-dates`, `cw date-from-ocr`, `cw find-similar` | | Watch folders | Watch local folders and upload new files, or download matching assets as they appear | `cw watch-upload`, `cw watch-download` | | Server workflows and users | List, inspect, and read logs for Immich server-side workflows; look up users and the authenticated account | `immich-workflow --help`, `users --help` | | Automation | Preview changes with `--dry-run`, bypass prompts with `--yes`, pass IDs through files or stdin, use JSON/IDs-only output, and retrieve agent instructions from the binary | `immich-admin return-agent-skill` | @@ -64,7 +64,7 @@ Release binaries are named `immich-admin__[.exe]` without a version nu -**28 of 253 endpoints implemented** (24 deprecated and 2 internal endpoints omitted per project policy). +**29 of 253 endpoints implemented** (24 deprecated and 2 internal endpoints omitted per project policy).
API keys (0/6) @@ -126,7 +126,7 @@ Release binaries are named `immich-admin__[.exe]` without a version nu
-Assets (7/24) +Assets (8/24) | Impl | Method | Path | Operation | State | |:----:|--------|------|-----------|-------| @@ -146,7 +146,7 @@ Release binaries are named `immich-admin__[.exe]` without a version nu | | PUT | `/assets/{id}/metadata` | `updateAssetMetadata` | Stable | | | DELETE | `/assets/{id}/metadata/{key}` | `deleteAssetMetadata` | Stable | | | GET | `/assets/{id}/metadata/{key}` | `getAssetMetadataByKey` | Stable | -| | GET | `/assets/{id}/ocr` | `getAssetOcr` | Stable | +| ✅ | GET | `/assets/{id}/ocr` | `getAssetOcr` | Stable | | ✅ | GET | `/assets/{id}/original` | `downloadAsset` | Stable | | ✅ | GET | `/assets/{id}/thumbnail` | `viewAsset` | Stable | | | GET | `/assets/{id}/video/playback` | `playAssetVideo` | Stable | diff --git a/docs/client-workflows.md b/docs/client-workflows.md index f51263b..b8282c8 100644 --- a/docs/client-workflows.md +++ b/docs/client-workflows.md @@ -18,6 +18,7 @@ Run destructive workflows with `--dry-run` first. Workflows show their planned a | `cw find-no-thumbhash` | Find assets for which Immich has no thumbnail hash | | `cw repair-assets` | Repair supported JPEG/TIFF defects or delete confirmed Google Takeout JSON sidecars | | `cw fix-album-dates` | Check date-named albums and optionally correct exact-day capture dates | +| `cw date-from-ocr` | Set capture years from a year printed in the image (OCR), per asset or interactively per album | | `cw download-album` | Export or synchronize an album to a local folder | | `cw find-similar` | Find visually similar Immich assets for a local image through immich-clip-probe | | `cw merge-album` | Merge album contents and metadata | @@ -110,6 +111,26 @@ immich-admin cw fix-album-dates --interactive Without `--interactive`, one confirmation applies to every reported asset. Use `--yes` only when that bulk behavior is intended. +## Set Capture Years from OCR + +`date-from-ocr` is for scanned or re-photographed prints whose real year is printed in the image. It reads Immich's OCR boxes (`assets ocr`) and finds standalone 4-digit years. An asset with exactly one year that differs from its capture year is a `change` candidate: its date becomes `YYYY-06-01 00:00` (mid-year) and it is tagged `immich-admin-cli/date-from-ocr`. Several distinct years are `ambiguous` and never changed automatically. Every hit is printed with its web link; asset links are accepted as input too. + +```sh +# Report only (default): status, OCR text, old -> new date, link +immich-admin cw date-from-ocr --album-name "Scans 1980er" + +# Apply only the unambiguous single-asset changes +immich-admin cw date-from-ocr --album-name "Scans 1980er" --yes + +# Review hits grouped by album (terminal required) +immich-admin cw date-from-ocr https://immich.example.com/photos/ --interactive + +# Whole library: one OCR search per year, then review (skips assets whose year already matches) +immich-admin cw date-from-ocr --all --interactive +``` + +`--interactive` offers `[s]kip`, `[t]his -> YYYY`, `[a]lbum -> YYYY`, `[n]ext album` (skip the rest of this album), `[y]ear...` (type another year), `[o]pen` (browser) and `[q]uit`. `[a]lbum` lists every asset of the album with its current and new date and asks again (default No); assets that are already in that year are kept, and the propagated ones are tagged `immich-admin-cli/date-from-ocr-album`. `--all` finds many numbers that are not dates (e.g. "seit 1938", "2000 qm"), so it is refused together with `--yes`; review the `--all --json` report or use `--all --interactive`. Album-wide changes are not available outside `--interactive`. Like `fix-album-dates`, this uses the deprecated `updateAsset` endpoint. + ## Download or Mirror an Album `download-album` resolves exactly one album by `--album-id` or `--album-name`, downloads its assets, and can optionally keep a local folder synchronized. diff --git a/immich-admin-cli/SKILL.md b/immich-admin-cli/SKILL.md index 16c2b42..14fa894 100644 --- a/immich-admin-cli/SKILL.md +++ b/immich-admin-cli/SKILL.md @@ -18,14 +18,14 @@ Asset operations Show information about one or more assets (GET /assets/{id}) Args: `[ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--json` (bool): print the raw responses as a JSON array ### assets update ⚠ DEPRECATED upstream: update one or more assets (PUT /assets/{id}) Args: `[ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--date-time-original` (string): set the asset's original date and time - `--description` (string): set the asset description - `--is-favorite` (string): mark as favorite: true or false @@ -39,7 +39,7 @@ Args: `[ASSET_ID ...]` Download original asset files (GET /assets/{id}/original) Args: `[ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--out-dir` (string): directory to save downloaded files into (default: current working directory) - `--quiet` (bool): disable per-file progress bars on stderr @@ -47,7 +47,7 @@ Args: `[ASSET_ID ...]` Download thumbnail/preview images for asset files (GET /assets/{id}/thumbnail) Args: `[ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--out-dir` (string): directory to save downloaded files into (default: current working directory) - `--size` (string): media size: fullsize, preview, or thumbnail (see the AssetMediaSize spec enum; 'original' is not accepted here — the spec deprecates size=original on this endpoint, use 'assets download-original' instead) [default: "preview"] - `--edited` (bool): return the edited version of the asset if available @@ -84,7 +84,7 @@ Args: `[FILE|DIR ...]` Delete one or more assets (DELETE /assets) Args: `[ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--force` (bool): permanently delete instead of moving to trash - `--dry-run` (bool): print the assets that would be deleted without changing anything - `--yes` (bool): skip the confirmation prompt before deleting assets @@ -99,6 +99,13 @@ Args: `SOURCE_ID TARGET_ID` - `--sidecar` (string): copy sidecar file: true or false - `--stack` (string): copy stack association: true or false +### assets ocr + +Show the OCR text boxes Immich recognized in one or more assets (GET /assets/{id}/ocr) +Args: `[ASSET_ID|ASSET_URL ...]` +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) +- `--json` (bool): print {assetId: [boxes]} as JSON (text, textScore, boxScore, normalized x1..y4) + ## albums Album operations @@ -117,7 +124,7 @@ List albums (GET /albums) Show one or more albums by ID, including members (GET /albums/{id}) Args: `[ALBUM_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--json` (bool): print the raw responses as a JSON array ### albums assets @@ -149,7 +156,7 @@ Rename an album (PATCH /albums/{id}) Add assets to an album (PUT /albums/{id}/assets) Args: `ALBUM_ID [ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--dry-run` (bool): print the assets that would be added without changing anything - `--yes` (bool): skip the confirmation prompt before adding assets @@ -157,7 +164,7 @@ Args: `ALBUM_ID [ASSET_ID ...]` Remove assets from an album (DELETE /albums/{id}/assets) Args: `ALBUM_ID [ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--dry-run` (bool): print the assets that would be removed without changing anything - `--yes` (bool): skip the confirmation prompt before removing assets @@ -171,7 +178,7 @@ Create an album (POST /albums) Delete one or more albums by ID (DELETE /albums/{id}) Args: `[ALBUM_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--force` (bool): also delete albums that still contain assets (otherwise non-empty albums are refused) - `--dry-run` (bool): print the albums that would be deleted without changing anything - `--yes` (bool): skip the confirmation prompt before deleting albums @@ -198,8 +205,8 @@ Search assets by metadata criteria (POST /search/metadata) - `--lens-model` (string): filter by lens model - `--taken-after` (string): filter by taken date after (RFC3339, e.g. 2024-01-01T00:00:00Z) - `--taken-before` (string): filter by taken date before (RFC3339, e.g. 2024-12-31T23:59:59Z) -- `--ocr` (string): filter by OCR text content -- `--description` (string): filter by description text +- `--ocr` (string): filter by OCR text recognized in the image (fuzzy word match, e.g. a year printed on a scan) +- `--description` (string): filter by description text (substring match) - `--order` (string): sort order: asc or desc (default: desc) [default: "desc"] - `--page-size` (int): number of results per page (max 1000) [default: 100] - `--all` (bool): fetch all pages automatically (overrides --page-size limit) @@ -219,14 +226,14 @@ List all tags (GET /tags) Show one or more tags by ID (GET /tags/{id}) Args: `[TAG_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--json` (bool): print the raw responses as a JSON array ### tags delete Delete one or more tags by ID (DELETE /tags/{id}) Args: `[TAG_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--dry-run` (bool): print the tags that would be deleted without changing anything - `--yes` (bool): skip the confirmation prompt before deleting tags @@ -240,7 +247,7 @@ Args: `[TAG_VALUE ...]` Add multiple tags to multiple assets in one request (PUT /tags/assets) Args: `[ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--tag-id` (string): tag `ID` to add (repeatable) - `--dry-run` (bool): print what would be tagged without changing anything @@ -248,7 +255,7 @@ Args: `[ASSET_ID ...]` Add one tag to multiple assets (PUT /tags/{id}/assets) Args: `TAG_ID [ASSET_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--dry-run` (bool): print what would be tagged without changing anything ## users @@ -269,7 +276,7 @@ List all users on the server (GET /users) Show one or more users by ID (GET /users/{id}) Args: `[USER_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--json` (bool): print the raw responses as a JSON array ## client-workflow @@ -333,7 +340,7 @@ Find HEIC/HEIF assets whose dimensions trigger a known Immich thumbnail-corrupti Repair corrupt image assets and re-import them, keeping metadata Args: `[ASSET_ID ...]` - `--mode` (string): repair mode: all | marker | tiff-tags | takeout-json [default: "all"] -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--check-all-assets` (bool): attempt repair on every IMAGE asset with no thumbhash (cannot be combined with explicit IDs) - `--album-id` (string): attempt repair on every IMAGE asset with no thumbhash in this album `UUID` (cannot be combined with explicit IDs or --check-all-assets) - `--keep-original` (bool): repair and re-import but keep the original asset instead of removing it @@ -350,6 +357,20 @@ Check assets in date-named albums against the date implied by the album name, an - `--interactive, -i` (bool): ask once per album (y/N) instead of one bulk confirmation; --yes overrides this and skips all prompts - `--yes` (bool): skip the confirmation prompt(s) before fixing dates +### client-workflow date-from-ocr + +Set an asset's capture year from a year Immich's OCR found in the image (e.g. scanned prints) +Args: `[ASSET_ID|ASSET_URL ...]` +- `--album-id` (string): scan every asset in this album `UUID` +- `--album-name` (string): scan every asset in the album with this exact `NAME` +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) +- `--all` (bool): scan the whole library: one server-side OCR search per year (1800–now, trash excluded), then check each hit; report or --interactive only (not with --yes), interactive skips already-matching assets +- `--min-score` (float): minimum OCR textScore (0–1) for a text box to count [default: 0.8] +- `--interactive, -i` (bool): review each hit grouped by album: [s]kip [t]his [a]lbum [n]ext album [y]ear [o]pen [q]uit (needs a terminal) +- `--dry-run` (bool): never change anything (also inside --interactive) +- `--yes` (bool): apply the unambiguous single-asset changes without asking (never whole albums) +- `--json` (bool): print the report as JSON (report only; not with --yes/--interactive) + ### client-workflow download-album Download all original files or a smaller variant (preview/thumbnail/fullsize) from one album into a local folder, optionally kept in sync @@ -441,7 +462,7 @@ List server workflows (GET /workflows) Show one or more server workflows by ID (GET /workflows/{id}) Args: `[WORKFLOW_ID ...]` -- `--ids-file` (string): read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment) +- `--ids-file` (string): read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment) - `--json` (bool): print the raw responses as a JSON array ### immich-workflow logs @@ -488,7 +509,8 @@ Check for and install the latest release from GitHub next command or save it: `search metadata --all -q > ids.txt`. - `--ids-file FILE` reads IDs back (one UUID per line, `#`/`//` comments and blank lines skipped, `-` means stdin). Positional IDs and - `--ids-file` combine. + `--ids-file` combine. Immich web links to an asset (e.g. + `https://immich.example.com/photos/`) are accepted wherever an asset ID is. - Bulk commands continue on per-ID errors and exit non-zero with a `N of M failed` summary — inspect stderr, don't assume all-or-nothing. @@ -556,7 +578,9 @@ albums separate, or rename instead of merging blindly. Always run - **Search → act**: `search metadata` filters by name, type, favorite, album membership, location, camera, dates, OCR (`--all` pages the whole library). Useful sets: `--is-not-in-album true` (orphans), - `--is-offline true`, `--make/--model`, `--city/--taken-after`. + `--is-offline true`, `--make/--model`, `--city/--taken-after`, + `--ocr 1986 -q` (scans with that year printed → pipe into `cw date-from-ocr --ids-file -`). + Name/path/description match substrings; city/camera fields match exactly; trashed assets are excluded. - **Replace**: `client-workflow replace-asset ` uploads, checksum-verifies, copies metadata (albums, favorite, shared links, sidecar, stack), then trashes the original. Aborts on checksum @@ -573,6 +597,19 @@ albums separate, or rename instead of merging blindly. Always run resume); `--size preview` + `--resize`/`--resize-video-preset` for small shareable copies. `fix-album-dates` reconciles date-named albums (report-only for year albums). `add-users-to-album-with-pattern` bulk-shares. +- **Dates from OCR** (scanned prints with a visible year): `assets ocr ID|LINK [--json]` + shows Immich's OCR boxes. `client-workflow date-from-ocr (--album-id|--album-name|ID|LINK...|--ids-file|--all) + [--min-score 0.8]` reports each asset whose OCR contains a 4-digit year, with its web link. + `--all` covers the whole library in seconds (one server-side OCR search per year, then OCR check of the + hits) but finds many non-date numbers ("seit 1938", "2000 qm"), so it is refused with `--yes`: use it + as `--all --json` report (pick IDs → `--ids-file … --yes`) or `--all --interactive`. Statuses: + `change` (one year, differs → would become `YYYY-06-01 00:00`), `matches`, `ambiguous` (several years). + No flags = report only; `--json` for agents. `--yes` applies only unambiguous single-asset changes + (tag `immich-admin-cli/date-from-ocr`), never whole albums. Album-wide changes exist only in + `--interactive` (a human at a terminal; refused without one): `[a]lbum` lists every album asset with + old → new date and asks again; those assets get `immich-admin-cli/date-from-ocr-album`; `[n]` skips the rest + of an album. Agents should + run the report, show it to the user, and leave `--interactive` to them. - **Tags**: `tags upsert`, `tags bulk-tag`, `tags tag` for assignment; `client-workflow tag-delete --include/--exclude` for regex bulk deletion (permanent — dry-run first). diff --git a/internal/commands/assets.go b/internal/commands/assets.go index 53eab71..068de19 100644 --- a/internal/commands/assets.go +++ b/internal/commands/assets.go @@ -41,6 +41,7 @@ func Assets() *cli.Command { assetsCheckRemoteExistsCommand(), assetsDeleteCommand(), assetsCopyCommand(), + assetsOcrCommand(), }, } } diff --git a/internal/commands/assets_ocr.go b/internal/commands/assets_ocr.go new file mode 100644 index 0000000..dce9ac8 --- /dev/null +++ b/internal/commands/assets_ocr.go @@ -0,0 +1,72 @@ +package commands + +import ( + "context" + "encoding/json" + "fmt" + "os" + + "github.com/urfave/cli/v3" + + "github.com/dhcgn/immich-admin-cli/internal/immichapi" + "github.com/dhcgn/immich-admin-cli/internal/workflows" +) + +// assetsOcrCommand exposes GET /assets/{id}/ocr (getAssetOcr), also driven by +// `client-workflow date-from-ocr`. +func assetsOcrCommand() *cli.Command { + return &cli.Command{ + Name: "ocr", + Usage: "Show the OCR text boxes Immich recognized in one or more assets (GET /assets/{id}/ocr)", + ArgsUsage: "[ASSET_ID|ASSET_URL ...]", + Flags: []cli.Flag{ + idsFileFlag(), + &cli.BoolFlag{ + Name: "json", + Usage: "print {assetId: [boxes]} as JSON (text, textScore, boxScore, normalized x1..y4)", + }, + }, + Action: assetsOcr, + } +} + +func assetsOcr(ctx context.Context, cmd *cli.Command) error { + ids, err := collectIDs(cmd) + if err != nil { + return err + } + c, err := newClient(ctx, cmd) + if err != nil { + return err + } + + all := map[string][]immichapi.AssetOcrResponseDto{} + failures := 0 + for _, id := range ids { + boxes, err := workflows.FetchAssetOCR(ctx, c, id) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: asset %s: %v\n", id, err) + failures++ + continue + } + all[id.String()] = boxes + if !cmd.Bool("json") { + fmt.Printf("%s %d box(es)\n", id, len(boxes)) + for _, b := range boxes { + fmt.Printf(" text=%.2f box=%.2f at x=%.2f y=%.2f %q\n", b.TextScore, b.BoxScore, b.X1, b.Y1, b.Text) + } + } + } + + if cmd.Bool("json") { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + if err := enc.Encode(all); err != nil { + return err + } + } + if failures > 0 { + return fmt.Errorf("%d of %d assets failed", failures, len(ids)) + } + return nil +} diff --git a/internal/commands/clientworkflow.go b/internal/commands/clientworkflow.go index a521817..4653aeb 100644 --- a/internal/commands/clientworkflow.go +++ b/internal/commands/clientworkflow.go @@ -41,6 +41,7 @@ func ClientWorkflow() *cli.Command { findHEICTileDefectCommand(), repairAssetsCommand(), fixAlbumDatesCommand(), + dateFromOCRCommand(), downloadAlbumCommand(), mergeAlbumCommand(), findSimilarCommand(), diff --git a/internal/commands/clientworkflow_datefromocr.go b/internal/commands/clientworkflow_datefromocr.go new file mode 100644 index 0000000..f168a51 --- /dev/null +++ b/internal/commands/clientworkflow_datefromocr.go @@ -0,0 +1,530 @@ +package commands + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "runtime" + "slices" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + openapi_types "github.com/oapi-codegen/runtime/types" + "github.com/urfave/cli/v3" + + "github.com/dhcgn/immich-admin-cli/internal/immichapi" + "github.com/dhcgn/immich-admin-cli/internal/workflows" +) + +func dateFromOCRCommand() *cli.Command { + return &cli.Command{ + Name: "date-from-ocr", + Usage: "Set an asset's capture year from a year Immich's OCR found in the image (e.g. scanned prints)", + ArgsUsage: "[ASSET_ID|ASSET_URL ...]", + Description: "Reads the OCR text boxes (GET /assets/{id}/ocr) of every asset in --album-id/--album-name, " + + "of the given asset IDs/links, or with --all of the whole library (pre-filtered server-side by one " + + "OCR search per year, so only likely hits are fetched), and finds 4-digit years (1800–current year) in boxes with " + + "textScore ≥ --min-score. Each hit is printed with its web link. An asset whose single OCR year " + + "differs from its capture year is a 'change' candidate; the fix sets the capture date to " + + "YYYY-06-01 00:00 (mid-year) and tags the asset " + workflows.DateFromOCRTag + ".\n" + + "Without flags it only reports. --yes applies the unambiguous single-asset changes only " + + "(never whole albums). --interactive (terminal required) walks the hits grouped by album with " + + "[s]kip, [t]his asset → YYYY, [a]lbum → YYYY (lists every asset with old/new date and asks again; " + + "album-propagated assets are tagged " + workflows.DateFromOCRAlbumTag + "), [n]ext album (skip the " + + "rest of this album's hits; an asset also in another album is still shown there), [y] enter another year, " + + "[o]pen in browser, [q]uit.\n" + + "Setting the date uses the deprecated PUT /assets/{id} (updateAsset), the only Immich API that can " + + "set a capture date (documented exception).", + Flags: []cli.Flag{ + &cli.StringFlag{Name: "album-id", Usage: "scan every asset in this album `UUID`"}, + &cli.StringFlag{Name: "album-name", Usage: "scan every asset in the album with this exact `NAME`"}, + idsFileFlag(), + &cli.BoolFlag{ + Name: "all", + Usage: "scan the whole library: one server-side OCR search per year (1800–now, trash excluded), then check each hit; report or --interactive only (not with --yes), interactive skips already-matching assets", + }, + &cli.FloatFlag{ + Name: "min-score", + Usage: "minimum OCR textScore (0–1) for a text box to count", + Value: workflows.DefaultOCRMinScore, + }, + &cli.BoolFlag{ + Name: "interactive", + Aliases: []string{"i"}, + Usage: "review each hit grouped by album: [s]kip [t]his [a]lbum [n]ext album [y]ear [o]pen [q]uit (needs a terminal)", + }, + &cli.BoolFlag{Name: "dry-run", Usage: "never change anything (also inside --interactive)"}, + &cli.BoolFlag{Name: "yes", Usage: "apply the unambiguous single-asset changes without asking (never whole albums)"}, + &cli.BoolFlag{Name: "json", Usage: "print the report as JSON (report only; not with --yes/--interactive)"}, + }, + Action: clientWorkflowDateFromOCR, + } +} + +func clientWorkflowDateFromOCR(ctx context.Context, cmd *cli.Command) error { + albumIDStr, albumName := cmd.String("album-id"), cmd.String("album-name") + interactive, yes, dryRun, asJSON := cmd.Bool("interactive"), cmd.Bool("yes"), cmd.Bool("dry-run"), cmd.Bool("json") + hasIDs := cmd.Args().Len() > 0 || cmd.String("ids-file") != "" + all := cmd.Bool("all") + + if albumIDStr != "" && albumName != "" { + return fmt.Errorf("pass only one of --album-id or --album-name") + } + sources := 0 + for _, set := range []bool{albumIDStr != "" || albumName != "", hasIDs, all} { + if set { + sources++ + } + } + if sources != 1 { + return fmt.Errorf("pass exactly one source: --album-id/--album-name, asset IDs/links (arguments or --ids-file), or --all") + } + if all && yes { + // Library-wide hits include many non-dates ("seit 1938", "2000 qm", + // "Geeicht bis 2021"); measured on a real library: ~470 'change' hits, + // a large share of them false. Review them instead of bulk-applying. + return fmt.Errorf("--all cannot be combined with --yes (library-wide OCR hits include many non-date numbers); use --all --interactive, or review --all --json and pass the chosen IDs via --ids-file with --yes") + } + if interactive && yes { + return fmt.Errorf("--interactive and --yes are mutually exclusive") + } + if asJSON && (interactive || yes) { + return fmt.Errorf("--json is report-only and cannot be combined with --interactive or --yes") + } + if interactive && !workflows.IsTerminal(os.Stdin) { + return fmt.Errorf("--interactive needs a terminal on stdin; use the report (no flags) or --yes instead") + } + + c, err := newClient(ctx, cmd) + if err != nil { + return err + } + + // Collect the assets to scan. + var assets []immichapi.AssetResponseDto + var album *immichapi.AlbumResponseDto + var fetchErr error + switch { + case all: + if assets, err = workflows.FindAssetsWithOCRYears(ctx, c, time.Now().Year()); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "OCR search found %d candidate asset(s); checking their OCR text...\n", len(assets)) + case hasIDs: + ids, err := collectIDs(cmd) + if err != nil { + return err + } + assets, fetchErr = workflows.FetchAssets(ctx, c, ids) + default: + var albumID *openapi_types.UUID + if albumIDStr != "" { + id, err := uuid.Parse(albumIDStr) + if err != nil { + return fmt.Errorf("invalid --album-id %q: %w", albumIDStr, err) + } + albumID = &id + } + a, err := resolveDownloadAlbum(ctx, c, albumID, albumName, yes) + if err != nil { + return err + } + album = &a + if assets, err = workflows.FetchAlbumAssets(ctx, c, a.Id); err != nil { + return err + } + } + + cands, scanErr := workflows.ScanOCRYears(ctx, c, assets, cmd.Float("min-score")) + slices.SortFunc(cands, func(a, b workflows.OCRYearCandidate) int { + return strings.Compare(a.Asset.OriginalFileName, b.Asset.OriginalFileName) + }) + + if asJSON { + return joinErrs(printOCRReportJSON(os.Stdout, cands, c.Server), fetchErr, scanErr) + } + + if interactive { + if all { + // Library-wide, already-matching assets would mean hundreds of + // pointless prompts; only review what may need a change. + cands = withoutMatching(cands) + } + fmt.Println("Note: setting dates uses the deprecated PUT /assets/{id} endpoint — Immich has no replacement for setting a capture date.") + groups, err := groupOCRCandidates(cands, album, func(id openapi_types.UUID) ([]immichapi.AlbumResponseDto, error) { + return workflows.AlbumsForAsset(ctx, c, id) + }) + if err != nil { + return err + } + r := &ocrReview{ + in: bufio.NewScanner(os.Stdin), out: os.Stdout, server: c.Server, + albumAssets: func(id openapi_types.UUID) ([]immichapi.AssetResponseDto, error) { + return workflows.FetchAlbumAssets(ctx, c, id) + }, + setYear: func(as []immichapi.AssetResponseDto, year int, tag string) error { + return workflows.SetAssetsYear(ctx, c, as, year, tag, dryRun) + }, + open: openBrowser, + } + return joinErrs(r.run(groups), fetchErr, scanErr) + } + + changes := printOCRReport(os.Stdout, cands, len(assets), c.Server) + if len(changes) == 0 || dryRun || !yes { + if len(changes) > 0 && !dryRun { + fmt.Println("Report only. Rerun with --yes to apply the single-asset changes above, or --interactive to review (incl. whole albums).") + } + return joinErrs(fetchErr, scanErr) + } + fmt.Println("Note: setting dates uses the deprecated PUT /assets/{id} endpoint — Immich has no replacement for setting a capture date.") + failures := 0 + for _, cand := range changes { + y, _ := cand.ProposedYear() + if err := workflows.SetAssetsYear(ctx, c, []immichapi.AssetResponseDto{cand.Asset}, y, workflows.DateFromOCRTag, false); err != nil { + fmt.Fprintf(os.Stderr, "Error: %s: %v\n", cand.Asset.OriginalFileName, err) + failures++ + } + } + var applyErr error + if failures > 0 { + applyErr = fmt.Errorf("%d of %d change(s) failed", failures, len(changes)) + } + return joinErrs(applyErr, fetchErr, scanErr) +} + +// withoutMatching drops candidates whose OCR year already equals the capture +// year (status "matches"). +func withoutMatching(cands []workflows.OCRYearCandidate) []workflows.OCRYearCandidate { + return slices.DeleteFunc(slices.Clone(cands), func(c workflows.OCRYearCandidate) bool { + return c.Status() == workflows.OCRStatusMatches + }) +} + +// joinErrs returns the first non-nil error; later ones were already logged. +func joinErrs(errs ...error) error { + for _, err := range errs { + if err != nil { + return err + } + } + return nil +} + +func assetLink(server string, id openapi_types.UUID) string { + return fmt.Sprintf("%s/photos/%s", server, id) +} + +const ocrTimeFmt = "2006-01-02 15:04:05" + +// printOCRReport prints one block per candidate and returns the "change" +// candidates (the ones --yes would apply). +func printOCRReport(w io.Writer, cands []workflows.OCRYearCandidate, scanned int, server string) []workflows.OCRYearCandidate { + var changes []workflows.OCRYearCandidate + matches, ambiguous := 0, 0 + for _, cand := range cands { + a := cand.Asset + line := fmt.Sprintf("%-9s %s OCR %q now %s", cand.Status(), a.OriginalFileName, strings.Join(cand.Texts, " | "), a.LocalDateTime.Format(ocrTimeFmt)) + switch cand.Status() { + case workflows.OCRStatusChange: + y, _ := cand.ProposedYear() + line += " -> " + workflows.OCRTargetDate(y).Format(ocrTimeFmt) + changes = append(changes, cand) + case workflows.OCRStatusMatches: + matches++ + default: + line += fmt.Sprintf(" (years %v, skipped)", cand.Years) + ambiguous++ + } + fmt.Fprintln(w, line) + fmt.Fprintf(w, " %s\n", assetLink(server, a.Id)) + } + fmt.Fprintf(w, "--- %d asset(s) scanned, %d with an OCR year: %d change, %d already matching, %d ambiguous ---\n", + scanned, len(cands), len(changes), matches, ambiguous) + return changes +} + +type ocrReportRow struct { + AssetID openapi_types.UUID `json:"assetId"` + FileName string `json:"originalFileName"` + Link string `json:"link"` + LocalDateTime string `json:"localDateTime"` + OCRTexts []string `json:"ocrTexts"` + OCRYears []int `json:"ocrYears"` + Status string `json:"status"` + TargetDate string `json:"targetDate,omitempty"` +} + +func printOCRReportJSON(w io.Writer, cands []workflows.OCRYearCandidate, server string) error { + rows := make([]ocrReportRow, 0, len(cands)) + for _, cand := range cands { + row := ocrReportRow{ + AssetID: cand.Asset.Id, FileName: cand.Asset.OriginalFileName, Link: assetLink(server, cand.Asset.Id), + LocalDateTime: cand.Asset.LocalDateTime.Format(ocrTimeFmt), OCRTexts: cand.Texts, OCRYears: cand.Years, + Status: cand.Status(), + } + if row.Status == workflows.OCRStatusChange { + row.TargetDate = workflows.OCRTargetDate(cand.Years[0]).Format(ocrTimeFmt) + } + rows = append(rows, row) + } + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(rows) +} + +// ocrGroup is the interactive review unit: the candidates of one album +// (Album nil = assets in no album, where only [t]his is possible). +type ocrGroup struct { + Album *immichapi.AlbumResponseDto + Cands []workflows.OCRYearCandidate +} + +// groupOCRCandidates groups candidates by album. With a known source album +// every candidate belongs to it; otherwise albumsOf is asked per candidate +// and an asset in several albums appears in each of them. +func groupOCRCandidates(cands []workflows.OCRYearCandidate, album *immichapi.AlbumResponseDto, albumsOf func(openapi_types.UUID) ([]immichapi.AlbumResponseDto, error)) ([]ocrGroup, error) { + if len(cands) == 0 { + return nil, nil + } + if album != nil { + return []ocrGroup{{Album: album, Cands: cands}}, nil + } + var groups []ocrGroup + index := map[openapi_types.UUID]int{} + var noAlbum []workflows.OCRYearCandidate + for _, cand := range cands { + albums, err := albumsOf(cand.Asset.Id) + if err != nil { + return nil, err + } + if len(albums) == 0 { + noAlbum = append(noAlbum, cand) + } + for _, a := range albums { + i, ok := index[a.Id] + if !ok { + i = len(groups) + index[a.Id] = i + groups = append(groups, ocrGroup{Album: &a}) + } + groups[i].Cands = append(groups[i].Cands, cand) + } + } + slices.SortFunc(groups, func(a, b ocrGroup) int { return strings.Compare(a.Album.AlbumName, b.Album.AlbumName) }) + if len(noAlbum) > 0 { + groups = append(groups, ocrGroup{Cands: noAlbum}) + } + return groups, nil +} + +// ocrReview drives the interactive review. All side effects are injected so +// the prompt flow — in particular the album re-confirmation — is testable. +type ocrReview struct { + in *bufio.Scanner + out io.Writer + server string + albumAssets func(openapi_types.UUID) ([]immichapi.AssetResponseDto, error) + setYear func(assets []immichapi.AssetResponseDto, year int, tag string) error + open func(url string) error + + done map[openapi_types.UUID]bool // assets already changed in this run + failures int +} + +func (r *ocrReview) run(groups []ocrGroup) error { + r.done = map[openapi_types.UUID]bool{} + if len(groups) == 0 { + fmt.Fprintln(r.out, "No asset with an OCR year found.") + return nil + } + changed := 0 +groupsLoop: + for _, g := range groups { + if g.Album != nil { + fmt.Fprintf(r.out, "\nAlbum %q (%d asset(s), %d with an OCR year) %s/albums/%s\n", g.Album.AlbumName, g.Album.AssetCount, len(g.Cands), r.server, g.Album.Id) + } else { + fmt.Fprintf(r.out, "\nAssets in no album (%d with an OCR year)\n", len(g.Cands)) + } + for i, cand := range g.Cands { + if r.done[cand.Asset.Id] { + continue + } + n, quit, albumDone := r.reviewOne(g, i, cand) + changed += n + if quit { + break groupsLoop + } + if albumDone { + break + } + } + } + fmt.Fprintf(r.out, "--- %d asset(s) changed ---\n", changed) + if r.failures > 0 { + return fmt.Errorf("%d change(s) failed", r.failures) + } + return nil +} + +// reviewOne prompts for one candidate until it is decided. It returns the +// number of assets changed, whether to quit, and whether the rest of the +// album is done (after an [a]lbum change). +func (r *ocrReview) reviewOne(g ocrGroup, i int, cand workflows.OCRYearCandidate) (int, bool, bool) { + a := cand.Asset + year, haveYear := cand.ProposedYear() + for { + fmt.Fprintf(r.out, " [%d/%d] %s OCR %q now %s", i+1, len(g.Cands), a.OriginalFileName, strings.Join(cand.Texts, " | "), a.LocalDateTime.Format(ocrTimeFmt)) + if haveYear && year != a.LocalDateTime.Year() { + fmt.Fprintf(r.out, " -> %s", workflows.OCRTargetDate(year).Format(ocrTimeFmt)) + } else if haveYear { + fmt.Fprintf(r.out, " (year %d matches)", year) + } else { + fmt.Fprintf(r.out, " (several years %v)", cand.Years) + } + fmt.Fprintf(r.out, "\n %s\n ", assetLink(r.server, a.Id)) + + opts := []string{"[s]kip"} + if haveYear && year != a.LocalDateTime.Year() { + opts = append(opts, fmt.Sprintf("[t]his -> %d", year)) + } + if haveYear && g.Album != nil { + opts = append(opts, fmt.Sprintf("[a]lbum -> %d", year)) + } + opts = append(opts, "[n]ext album (skip rest)", "[y]ear...", "[o]pen", "[q]uit") + fmt.Fprintf(r.out, "%s: ", strings.Join(opts, " ")) + + answer, ok := r.read() + if !ok { + return 0, true, false + } + switch answer { + case "", "s", "skip": + return 0, false, false + case "n", "next": + fmt.Fprintf(r.out, " Skipping the remaining %d hit(s) of this album.\n", len(g.Cands)-i) + return 0, false, true + case "q", "quit": + return 0, true, false + case "o", "open": + if err := r.open(assetLink(r.server, a.Id)); err != nil { + fmt.Fprintf(r.out, "Could not open browser: %v\n", err) + } + case "y", "year": + fmt.Fprintf(r.out, " Year (1800-%d): ", time.Now().Year()) + s, ok := r.read() + if !ok { + return 0, true, false + } + y, err := strconv.Atoi(s) + if err != nil || y < 1800 || y > time.Now().Year() { + fmt.Fprintf(r.out, " Invalid year %q.\n", s) + continue + } + year, haveYear = y, true + case "t", "this": + if !haveYear || year == a.LocalDateTime.Year() { + fmt.Fprintln(r.out, " Nothing to change for this asset.") + continue + } + return r.apply([]immichapi.AssetResponseDto{a}, year, workflows.DateFromOCRTag), false, false + case "a", "album": + if !haveYear || g.Album == nil { + fmt.Fprintln(r.out, " No album change possible here.") + continue + } + if n, applied := r.confirmAlbum(g.Album, a, year); applied { + return n, false, true + } + default: + fmt.Fprintf(r.out, " Unknown choice %q.\n", answer) + } + } +} + +// confirmAlbum lists every asset of the album with its current and new date, +// asks again (default No) and applies on "y". The triggering asset is tagged +// as OCR evidence, the rest as album-propagated. applied=false sends the +// caller back to the options for the current asset. +func (r *ocrReview) confirmAlbum(album *immichapi.AlbumResponseDto, trigger immichapi.AssetResponseDto, year int) (int, bool) { + assets, err := r.albumAssets(album.Id) + if err != nil { + fmt.Fprintf(r.out, " Could not list album assets: %v\n", err) + return 0, false + } + slices.SortFunc(assets, func(a, b immichapi.AssetResponseDto) int { return a.LocalDateTime.Compare(b.LocalDateTime) }) + target := workflows.OCRTargetDate(year).Format(ocrTimeFmt) + + var self, others []immichapi.AssetResponseDto + fmt.Fprintf(r.out, "\n Album %q: setting the year to %d would change:\n", album.AlbumName, year) + for _, a := range assets { + if a.LocalDateTime.Year() == year { + fmt.Fprintf(r.out, " keep %-40s %s (year matches)\n", a.OriginalFileName, a.LocalDateTime.Format(ocrTimeFmt)) + continue + } + fmt.Fprintf(r.out, " change %-40s %s -> %s\n", a.OriginalFileName, a.LocalDateTime.Format(ocrTimeFmt), target) + if a.Id == trigger.Id { + self = append(self, a) + } else { + others = append(others, a) + } + } + total := len(self) + len(others) + if total == 0 { + fmt.Fprintln(r.out, " Nothing to change: every asset is already in that year.") + return 0, false + } + fmt.Fprintf(r.out, " Set %d of %d asset(s) to %s and tag them? [y/N]: ", total, len(assets), target) + answer, ok := r.read() + if !ok || (answer != "y" && answer != "yes") { + fmt.Fprintln(r.out, " Not changed.") + return 0, false + } + n := r.apply(self, year, workflows.DateFromOCRTag) + r.apply(others, year, workflows.DateFromOCRAlbumTag) + for _, a := range assets { + r.done[a.Id] = true + } + return n, true +} + +func (r *ocrReview) apply(assets []immichapi.AssetResponseDto, year int, tag string) int { + if len(assets) == 0 { + return 0 + } + if err := r.setYear(assets, year, tag); err != nil { + fmt.Fprintf(r.out, "Error: %v\n", err) + r.failures++ + return 0 + } + for _, a := range assets { + r.done[a.Id] = true + } + return len(assets) +} + +func (r *ocrReview) read() (string, bool) { + if !r.in.Scan() { + return "", false + } + return strings.ToLower(strings.TrimSpace(r.in.Text())), true +} + +// openBrowser opens url in the default browser. +func openBrowser(url string) error { + var cmd *exec.Cmd + switch runtime.GOOS { + case "windows": + cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url) + case "darwin": + cmd = exec.Command("open", url) + default: + cmd = exec.Command("xdg-open", url) + } + return cmd.Start() +} diff --git a/internal/commands/clientworkflow_datefromocr_test.go b/internal/commands/clientworkflow_datefromocr_test.go new file mode 100644 index 0000000..e8790bc --- /dev/null +++ b/internal/commands/clientworkflow_datefromocr_test.go @@ -0,0 +1,186 @@ +package commands + +import ( + "bufio" + "bytes" + "strings" + "testing" + "time" + + "github.com/google/uuid" + openapi_types "github.com/oapi-codegen/runtime/types" + + "github.com/dhcgn/immich-admin-cli/internal/immichapi" + "github.com/dhcgn/immich-admin-cli/internal/workflows" +) + +func TestParseAssetRef(t *testing.T) { + const want = "ec905585-077a-401f-9c47-00c84944f563" + for _, in := range []string{ + want, + "https://immich.example.com/photos/" + want, + "https://immich.example.com/people/00554a98-5890-4d4c-b648-bba2ff49708a/photos/" + want + "?previousRoute=%2Fpeople", + } { + got, err := parseAssetRef(in) + if err != nil || got.String() != want { + t.Errorf("parseAssetRef(%q) = %v, %v; want %s", in, got, err, want) + } + } + for _, in := range []string{"not-a-uuid", "https://immich.example.com/photos/"} { + if _, err := parseAssetRef(in); err == nil { + t.Errorf("parseAssetRef(%q): expected error", in) + } + } +} + +func testAsset(name string, year int) immichapi.AssetResponseDto { + return immichapi.AssetResponseDto{ + Id: openapi_types.UUID(uuid.New()), + OriginalFileName: name, + LocalDateTime: time.Date(year, 11, 15, 18, 46, 15, 0, time.UTC), + } +} + +type setCall struct { + names []string + year int + tag string +} + +func newTestReview(input string, albumAssets []immichapi.AssetResponseDto) (*ocrReview, *bytes.Buffer, *[]setCall) { + var out bytes.Buffer + var calls []setCall + r := &ocrReview{ + in: bufio.NewScanner(strings.NewReader(input)), out: &out, server: "https://immich.example.com", + albumAssets: func(openapi_types.UUID) ([]immichapi.AssetResponseDto, error) { return albumAssets, nil }, + setYear: func(as []immichapi.AssetResponseDto, year int, tag string) error { + c := setCall{year: year, tag: tag} + for _, a := range as { + c.names = append(c.names, a.OriginalFileName) + } + calls = append(calls, c) + return nil + }, + open: func(string) error { return nil }, + } + return r, &out, &calls +} + +func TestOCRReviewThisAsset(t *testing.T) { + scan := testAsset("440-AngelaDanel-93.jpg", 2009) + g := ocrGroup{Cands: []workflows.OCRYearCandidate{{Asset: scan, Texts: []string{"1986"}, Years: []int{1986}}}} + r, out, calls := newTestReview("t\n", nil) + if err := r.run([]ocrGroup{g}); err != nil { + t.Fatal(err) + } + if len(*calls) != 1 || (*calls)[0].year != 1986 || (*calls)[0].tag != workflows.DateFromOCRTag { + t.Fatalf("calls = %+v, want one 1986 call tagged %s", *calls, workflows.DateFromOCRTag) + } + if !strings.Contains(out.String(), "https://immich.example.com/photos/"+scan.Id.String()) { + t.Errorf("output lacks the asset link:\n%s", out) + } + if strings.Contains(out.String(), "[a]lbum") { + t.Errorf("[a]lbum offered for an asset in no album:\n%s", out) + } +} + +// The album change must list every album asset with its date and only run +// after a second explicit "y"; declining goes back to the options. +func TestOCRReviewAlbumNeedsSecondConfirmation(t *testing.T) { + scan := testAsset("scan-1986.jpg", 2009) + other := testAsset("scan-2.jpg", 2009) + keep := testAsset("already-1986.jpg", 1986) + album := immichapi.AlbumResponseDto{Id: openapi_types.UUID(uuid.New()), AlbumName: "Fotos Angela", AssetCount: 3} + g := ocrGroup{Album: &album, Cands: []workflows.OCRYearCandidate{ + {Asset: scan, Texts: []string{"1986"}, Years: []int{1986}}, + {Asset: other, Texts: []string{"1986"}, Years: []int{1986}}, + }} + albumAssets := []immichapi.AssetResponseDto{scan, other, keep} + + // a → decline (Enter) → back to options → skip; then second asset: skip. + r, out, calls := newTestReview("a\n\ns\ns\n", albumAssets) + if err := r.run([]ocrGroup{g}); err != nil { + t.Fatal(err) + } + if len(*calls) != 0 { + t.Fatalf("declined album change still called setYear: %+v", *calls) + } + for _, want := range []string{"change scan-1986.jpg", "2009-11-15 18:46:15 -> 1986-06-01 00:00:00", "keep already-1986.jpg", "[y/N]", "Not changed."} { + if !strings.Contains(out.String(), want) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } + + // a → y: trigger tagged as OCR evidence, the other as album-propagated, + // the matching asset untouched, and the album's second hit not asked. + r, out, calls = newTestReview("a\ny\n", albumAssets) + if err := r.run([]ocrGroup{g}); err != nil { + t.Fatal(err) + } + if len(*calls) != 2 || + (*calls)[0].tag != workflows.DateFromOCRTag || strings.Join((*calls)[0].names, ",") != "scan-1986.jpg" || + (*calls)[1].tag != workflows.DateFromOCRAlbumTag || strings.Join((*calls)[1].names, ",") != "scan-2.jpg" { + t.Fatalf("calls = %+v", *calls) + } + if strings.Contains(out.String(), "[2/2]") { + t.Errorf("second hit in an already-changed album was prompted:\n%s", out) + } +} + +func TestOCRReviewOtherYearAndEOF(t *testing.T) { + scan := testAsset("amb.jpg", 2009) + g := ocrGroup{Cands: []workflows.OCRYearCandidate{{Asset: scan, Texts: []string{"1986 1993"}, Years: []int{1986, 1993}}}} + r, _, calls := newTestReview("t\ny\n1993\nt\n", nil) + if err := r.run([]ocrGroup{g}); err != nil { + t.Fatal(err) + } + if len(*calls) != 1 || (*calls)[0].year != 1993 { + t.Fatalf("calls = %+v, want one 1993 call", *calls) + } + + r, _, calls = newTestReview("", nil) // closed stdin = quit, nothing changed + if err := r.run([]ocrGroup{g}); err != nil || len(*calls) != 0 { + t.Fatalf("EOF: err %v calls %+v", err, *calls) + } +} + +func TestWithoutMatching(t *testing.T) { + change := workflows.OCRYearCandidate{Asset: testAsset("change.jpg", 2009), Years: []int{1986}} + match := workflows.OCRYearCandidate{Asset: testAsset("match.jpg", 2004), Years: []int{2004}} + amb := workflows.OCRYearCandidate{Asset: testAsset("amb.jpg", 2004), Years: []int{1986, 2004}} + in := []workflows.OCRYearCandidate{change, match, amb} + got := withoutMatching(in) + if len(got) != 2 || got[0].Asset.OriginalFileName != "change.jpg" || got[1].Asset.OriginalFileName != "amb.jpg" { + t.Fatalf("withoutMatching = %v", got) + } + if len(in) != 3 || in[1].Asset.OriginalFileName != "match.jpg" { + t.Fatalf("input modified: %v", in) + } +} + +// [n] skips the remaining hits of the current album; the next album is +// still reviewed. +func TestOCRReviewNextAlbum(t *testing.T) { + hit := func(name string) workflows.OCRYearCandidate { + return workflows.OCRYearCandidate{Asset: testAsset(name, 2009), Texts: []string{"1986"}, Years: []int{1986}} + } + a1 := immichapi.AlbumResponseDto{Id: openapi_types.UUID(uuid.New()), AlbumName: "Familie"} + a2 := immichapi.AlbumResponseDto{Id: openapi_types.UUID(uuid.New()), AlbumName: "Scans"} + groups := []ocrGroup{ + {Album: &a1, Cands: []workflows.OCRYearCandidate{hit("f1.jpg"), hit("f2.jpg"), hit("f3.jpg")}}, + {Album: &a2, Cands: []workflows.OCRYearCandidate{hit("s1.jpg")}}, + } + r, out, calls := newTestReview("n\nt\n", nil) + if err := r.run(groups); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "f2.jpg") || strings.Contains(out.String(), "f3.jpg") { + t.Errorf("skipped album hits were still prompted:\n%s", out) + } + if !strings.Contains(out.String(), "Skipping the remaining 3 hit(s)") { + t.Errorf("no skip notice:\n%s", out) + } + if len(*calls) != 1 || strings.Join((*calls)[0].names, ",") != "s1.jpg" { + t.Fatalf("calls = %+v, want only s1.jpg changed", *calls) + } +} diff --git a/internal/commands/datefromocr_integration_test.go b/internal/commands/datefromocr_integration_test.go new file mode 100644 index 0000000..12442e3 --- /dev/null +++ b/internal/commands/datefromocr_integration_test.go @@ -0,0 +1,85 @@ +//go:build integration + +// Staging roundtrip for `assets ocr` and the date-from-ocr write path +// (workflows.SetAssetsYear): uploads a throwaway PNG, reads its (empty) OCR, +// sets its year, verifies date and tag, and force-deletes it via the +// uploadStagingAsset cleanup. Run with: +// +// go test -tags integration ./internal/commands/ -run DateFromOCR +package commands + +import ( + "context" + "net/http" + "testing" + "time" + + openapi_types "github.com/oapi-codegen/runtime/types" + + "github.com/dhcgn/immich-admin-cli/internal/client" + "github.com/dhcgn/immich-admin-cli/internal/immichapi" + "github.com/dhcgn/immich-admin-cli/internal/workflows" +) + +func TestDateFromOCRRoundtripIntegration(t *testing.T) { + c := stagingTestClient(t) + ctx := context.Background() + id := uploadStagingAsset(t, ctx, c) + + if _, err := workflows.FetchAssetOCR(ctx, c, id); err != nil { + t.Fatalf("FetchAssetOCR: %v", err) + } + + assets, err := workflows.FetchAssets(ctx, c, []openapi_types.UUID{id}) + if err != nil || len(assets) != 1 { + t.Fatalf("FetchAssets: %v (%d)", err, len(assets)) + } + if err := workflows.SetAssetsYear(ctx, c, assets, 1986, workflows.DateFromOCRTag, false); err != nil { + t.Fatalf("SetAssetsYear: %v", err) + } + + // The date may land via a server-side sidecar/metadata job, so poll briefly. + var info *immichapi.AssetResponseDto + deadline := time.Now().Add(30 * time.Second) + for { + resp, err := c.API.GetAssetInfoWithResponse(ctx, id, nil) + if err == nil { + err = client.Check(resp, http.StatusOK) + } + if err != nil { + t.Fatalf("GetAssetInfo: %v", err) + } + info = resp.JSON200 + if info.LocalDateTime.Year() == 1986 || time.Now().After(deadline) { + break + } + time.Sleep(2 * time.Second) + } + // The naive timestamp is shifted by the server/asset time zone (hours + // only; staging is UTC+x, so the date holds); mid-year means the year + // never changes in any zone. + if got := info.LocalDateTime.Format("2006-01-02"); got != "1986-06-01" { + t.Errorf("LocalDateTime date = %s, want 1986-06-01", got) + } + + tagged := false + if info.Tags != nil { + for _, tg := range *info.Tags { + tagged = tagged || tg.Value == workflows.DateFromOCRTag + } + } + if !tagged { + t.Errorf("asset not tagged %q", workflows.DateFromOCRTag) + } +} + +// Read-only: the library-wide pre-filter (one OCR search per year) must run +// through without a server error; staging may simply have no OCR hits. +func TestDateFromOCRFindAllIntegration(t *testing.T) { + c := stagingTestClient(t) + assets, err := workflows.FindAssetsWithOCRYears(context.Background(), c, time.Now().Year()) + if err != nil { + t.Fatalf("FindAssetsWithOCRYears: %v", err) + } + t.Logf("%d candidate asset(s)", len(assets)) +} diff --git a/internal/commands/helpers.go b/internal/commands/helpers.go index 0ff8672..f68d4d6 100644 --- a/internal/commands/helpers.go +++ b/internal/commands/helpers.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "os" + "regexp" "strings" "github.com/google/uuid" @@ -128,7 +129,7 @@ func whitespaceNote(name string) string { func idsFileFlag() cli.Flag { return &cli.StringFlag{ Name: "ids-file", - Usage: "read IDs from `FILE`, one UUID per line ('-' for stdin; '#' or '//' starts a comment)", + Usage: "read IDs from `FILE`, one UUID (or Immich asset link) per line ('-' for stdin; '#' or '//' starts a comment)", } } @@ -151,7 +152,7 @@ func collectIDs(cmd *cli.Command) ([]openapi_types.UUID, error) { ids := make([]openapi_types.UUID, 0, len(raw)) for _, s := range raw { - id, err := uuid.Parse(s) + id, err := parseAssetRef(s) if err != nil { return nil, fmt.Errorf("invalid asset ID %q: %w", s, err) } @@ -160,6 +161,24 @@ func collectIDs(cmd *cli.Command) ([]openapi_types.UUID, error) { return ids, nil } +// uuidInURL matches a UUID anywhere in a string (e.g. an Immich web link). +var uuidInURL = regexp.MustCompile(`[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`) + +// parseAssetRef accepts a bare asset UUID or an Immich web link to an asset +// (e.g. https://immich.example.com/people//photos/?…): +// for a link, the last UUID in the path (query string ignored) is the asset. +func parseAssetRef(s string) (openapi_types.UUID, error) { + if !strings.Contains(s, "/") { + return uuid.Parse(s) + } + path, _, _ := strings.Cut(s, "?") + m := uuidInURL.FindAllString(path, -1) + if len(m) == 0 { + return openapi_types.UUID{}, fmt.Errorf("no asset UUID found in link") + } + return uuid.Parse(m[len(m)-1]) +} + // readIDLines reads one ID per line from path ("-" = stdin). Blank lines and // comment lines (starting with '#' or '//') are skipped. func readIDLines(path string) ([]string, error) { diff --git a/internal/commands/search.go b/internal/commands/search.go index eb3bfc1..1a53e4f 100644 --- a/internal/commands/search.go +++ b/internal/commands/search.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "strconv" + "time" "github.com/urfave/cli/v3" @@ -24,7 +25,7 @@ func Search() *cli.Command { Name: "metadata", Usage: "Search assets by metadata criteria (POST /search/metadata)", Description: "Search for assets using metadata filters such as file name, type, camera, location, and date ranges. " + - "Results are paginated; use --all to fetch every page automatically.", + "Results are paginated; use --all to fetch every page automatically. Trashed assets are excluded.", Flags: []cli.Flag{ // --- file / name --- &cli.StringFlag{ @@ -96,11 +97,11 @@ func Search() *cli.Command { // --- OCR / description --- &cli.StringFlag{ Name: "ocr", - Usage: "filter by OCR text content", + Usage: "filter by OCR text recognized in the image (fuzzy word match, e.g. a year printed on a scan)", }, &cli.StringFlag{ Name: "description", - Usage: "filter by description text", + Usage: "filter by description text (substring match)", }, // --- order --- &cli.StringFlag{ @@ -156,7 +157,7 @@ func searchMetadata(ctx context.Context, cmd *cli.Command) error { for { pager.Apply(body) - resp, err := c.API.SearchAssetsWithResponse(ctx, &immichapi.SearchAssetsParams{}, *body) + resp, err := workflows.SearchExcludingTrash(ctx, c, *body) if err != nil { return fmt.Errorf("calling POST /search/metadata: %w", err) } @@ -200,67 +201,93 @@ func searchMetadata(ctx context.Context, cmd *cli.Command) error { return nil } -// buildMetadataSearchDto maps CLI flags to the API request body. +// buildMetadataSearchDto maps CLI flags to the API request body. It uses only +// the structured shape (filter/orderBy/cursor, v3.2+): the flat fields are +// deprecated and the server rejects mixing the two shapes (400). func buildMetadataSearchDto(cmd *cli.Command) (*immichapi.SearchAssetsJSONRequestBody, error) { - body := &immichapi.MetadataSearchDto{} - - if v := cmd.String("original-file-name"); v != "" { - body.OriginalFileName = &v - } - if v := cmd.String("original-path"); v != "" { - body.OriginalPath = &v - } - if v := cmd.String("type"); v != "" { - t := immichapi.AssetTypeEnum(v) - body.Type = &t - } - if v := cmd.String("city"); v != "" { - body.City = &v - } - if v := cmd.String("country"); v != "" { - body.Country = &v - } - if v := cmd.String("state"); v != "" { - body.State = &v - } - if v := cmd.String("make"); v != "" { - body.Make = &v + f := immichapi.SearchFilter{} + str := func(name string) *string { + if v := cmd.String(name); v != "" { + return &v + } + return nil } - if v := cmd.String("model"); v != "" { - body.Model = &v + // Substring match, same as the legacy flat fields (server: ILIKE '%v%'). + like := func(name string) *immichapi.StringPatternFilter { + if v := str(name); v != nil { + return &immichapi.StringPatternFilter{Like: v} + } + return nil } - if v := cmd.String("lens-model"); v != "" { - body.LensModel = &v + // Exact match, same as the legacy flat fields. + eq := func(name string) *immichapi.StringFilterNullable { + if v := str(name); v != nil { + return &immichapi.StringFilterNullable{Eq: v} + } + return nil } - if v := cmd.String("ocr"); v != "" { - body.Ocr = &v + + f.OriginalFileName = like("original-file-name") + f.OriginalPath = like("original-path") + f.Description = like("description") + f.City, f.Country, f.State = eq("city"), eq("country"), eq("state") + f.Make, f.Model, f.LensModel = eq("make"), eq("model"), eq("lens-model") + if v := str("ocr"); v != nil { + f.Ocr = &immichapi.StringSimilarityFilter{Matches: *v} } - if v := cmd.String("description"); v != "" { - body.Description = &v + if v := str("type"); v != nil { + t := immichapi.AssetTypeEnum(*v) + if !t.Valid() { + return nil, fmt.Errorf("invalid --type %q: must be IMAGE, VIDEO, AUDIO, or OTHER", *v) + } + f.Type = &immichapi.EnumFilterAssetType{Eq: &t} } - if v := cmd.String("order"); v != "" { - // orderBy replaces the deprecated order field (v3.2+); Field stays - // nil so the server keeps its default sort field. - o := immichapi.AssetOrder(v) - body.OrderBy = &immichapi.SearchOrder{Direction: &o} + for _, d := range []struct { + name string + set func(t time.Time) + }{ + {"taken-after", func(t time.Time) { ensureDate(&f.TakenAt).Gte = &t }}, + {"taken-before", func(t time.Time) { ensureDate(&f.TakenAt).Lte = &t }}, + } { + if v := str(d.name); v != nil { + t, err := time.Parse(time.RFC3339, *v) + if err != nil { + return nil, fmt.Errorf("flag --%s: expected RFC3339 (e.g. 2024-01-01T00:00:00Z), got %q", d.name, *v) + } + d.set(t) + } } - if err := setBoolFlag(cmd, "is-favorite", func(b bool) { body.IsFavorite = &b }); err != nil { + boolFilter := func(b bool) *immichapi.BoolFilter { return &immichapi.BoolFilter{Eq: b} } + if err := setBoolFlag(cmd, "is-favorite", func(b bool) { f.IsFavorite = boolFilter(b) }); err != nil { return nil, err } - if err := setBoolFlag(cmd, "is-not-in-album", func(b bool) { body.IsNotInAlbum = &b }); err != nil { + if err := setBoolFlag(cmd, "is-not-in-album", func(b bool) { f.HasAlbums = boolFilter(!b) }); err != nil { return nil, err } - if err := setBoolFlag(cmd, "is-offline", func(b bool) { body.IsOffline = &b }); err != nil { + if err := setBoolFlag(cmd, "is-offline", func(b bool) { f.IsOffline = boolFilter(b) }); err != nil { return nil, err } - if err := setBoolFlag(cmd, "is-motion", func(b bool) { body.IsMotion = &b }); err != nil { + if err := setBoolFlag(cmd, "is-motion", func(b bool) { f.IsMotion = boolFilter(b) }); err != nil { return nil, err } - size := cmd.Int("page-size") - body.Size = &size + o := immichapi.AssetOrder(cmd.String("order")) + if o != immichapi.AssetOrderAsc && o != immichapi.AssetOrderDesc { + return nil, fmt.Errorf("invalid --order %q: must be asc or desc", o) + } + size := int(cmd.Int("page-size")) + return &immichapi.MetadataSearchDto{ + Filter: &f, + OrderBy: &immichapi.SearchOrder{Direction: &o}, // Field nil = server default sort field + Size: &size, + }, nil +} - return body, nil +func ensureDate(p **immichapi.DateFilter) *immichapi.DateFilter { + if *p == nil { + *p = &immichapi.DateFilter{} + } + return *p } // setBoolFlag parses an optional "true"/"false" string flag and calls set if provided. diff --git a/internal/commands/search_test.go b/internal/commands/search_test.go new file mode 100644 index 0000000..d622d08 --- /dev/null +++ b/internal/commands/search_test.go @@ -0,0 +1,98 @@ +package commands + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/urfave/cli/v3" + + "github.com/dhcgn/immich-admin-cli/internal/client" + "github.com/dhcgn/immich-admin-cli/internal/config" + "github.com/dhcgn/immich-admin-cli/internal/immichapi" + "github.com/dhcgn/immich-admin-cli/internal/workflows" +) + +// runSearchFlags parses args with the real `search metadata` flags and +// returns the built request body. +func runSearchFlags(t *testing.T, args ...string) (*immichapi.MetadataSearchDto, error) { + t.Helper() + meta := Search().Commands[0] + var body *immichapi.MetadataSearchDto + var buildErr error + cmd := &cli.Command{ + Name: "metadata", + Flags: meta.Flags, + Action: func(_ context.Context, cmd *cli.Command) error { + body, buildErr = buildMetadataSearchDto(cmd) + return nil + }, + } + if err := cmd.Run(context.Background(), append([]string{"metadata"}, args...)); err != nil { + t.Fatalf("parsing flags: %v", err) + } + return body, buildErr +} + +// No deprecated flat field may be set: the server rejects mixing them with +// filter/orderBy (400 "Deprecated field … cannot be combined with orderBy"). +func TestBuildMetadataSearchDtoUsesOnlyStructuredShape(t *testing.T) { + body, err := runSearchFlags(t, + "--original-file-name", "IMG", "--ocr", "1986", "--type", "IMAGE", "--make", "Canon", + "--is-not-in-album", "true", "--is-favorite", "false", + "--taken-after", "2024-01-01T00:00:00Z", "--taken-before", "2024-12-31T23:59:59Z", "--order", "asc") + if err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(body) + var top map[string]json.RawMessage + _ = json.Unmarshal(raw, &top) + for k := range top { + if k != "filter" && k != "orderBy" && k != "size" { + t.Errorf("unexpected top-level field %q in %s", k, raw) + } + } + for _, want := range []string{ + `"originalFileName":{"like":"IMG"}`, `"ocr":{"matches":"1986"}`, `"type":{"eq":"IMAGE"}`, + `"make":{"eq":"Canon"}`, `"hasAlbums":{"eq":false}`, `"isFavorite":{"eq":false}`, + `"takenAt":{"gte":"2024-01-01T00:00:00Z","lte":"2024-12-31T23:59:59Z"}`, `"orderBy":{"direction":"asc"}`, + } { + if !strings.Contains(string(raw), want) { + t.Errorf("body lacks %s:\n%s", want, raw) + } + } +} + +func TestBuildMetadataSearchDtoRejectsInvalidEnums(t *testing.T) { + for _, args := range [][]string{{"--type", "image"}, {"--order", "up"}, {"--taken-after", "2024-01-01"}} { + if _, err := runSearchFlags(t, args...); err == nil { + t.Errorf("%v: expected error", args) + } + } +} + +func TestSearchExcludingTrashSendsExplicitNull(t *testing.T) { + var got string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + got = string(b) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"albums":{"items":[],"count":0,"total":0,"facets":[]},"assets":{"items":[],"count":0,"total":0,"facets":[]}}`)) + })) + defer srv.Close() + c, err := client.New(&config.Config{Server: srv.URL, APIKey: "test"}) + if err != nil { + t.Fatal(err) + } + ocr := immichapi.SearchFilter{Ocr: &immichapi.StringSimilarityFilter{Matches: "1986"}} + if _, err := workflows.SearchExcludingTrash(context.Background(), c, immichapi.MetadataSearchDto{Filter: &ocr}); err != nil { + t.Fatal(err) + } + if !strings.Contains(got, `"trashedAt":{"eq":null}`) || !strings.Contains(got, `"ocr":{"matches":"1986"}`) { + t.Errorf("request body = %s", got) + } +} diff --git a/internal/commands/skill_best_practices.md b/internal/commands/skill_best_practices.md index 18c431e..6875250 100644 --- a/internal/commands/skill_best_practices.md +++ b/internal/commands/skill_best_practices.md @@ -26,7 +26,8 @@ next command or save it: `search metadata --all -q > ids.txt`. - `--ids-file FILE` reads IDs back (one UUID per line, `#`/`//` comments and blank lines skipped, `-` means stdin). Positional IDs and - `--ids-file` combine. + `--ids-file` combine. Immich web links to an asset (e.g. + `https://immich.example.com/photos/`) are accepted wherever an asset ID is. - Bulk commands continue on per-ID errors and exit non-zero with a `N of M failed` summary — inspect stderr, don't assume all-or-nothing. @@ -94,7 +95,9 @@ albums separate, or rename instead of merging blindly. Always run - **Search → act**: `search metadata` filters by name, type, favorite, album membership, location, camera, dates, OCR (`--all` pages the whole library). Useful sets: `--is-not-in-album true` (orphans), - `--is-offline true`, `--make/--model`, `--city/--taken-after`. + `--is-offline true`, `--make/--model`, `--city/--taken-after`, + `--ocr 1986 -q` (scans with that year printed → pipe into `cw date-from-ocr --ids-file -`). + Name/path/description match substrings; city/camera fields match exactly; trashed assets are excluded. - **Replace**: `client-workflow replace-asset ` uploads, checksum-verifies, copies metadata (albums, favorite, shared links, sidecar, stack), then trashes the original. Aborts on checksum @@ -111,6 +114,19 @@ albums separate, or rename instead of merging blindly. Always run resume); `--size preview` + `--resize`/`--resize-video-preset` for small shareable copies. `fix-album-dates` reconciles date-named albums (report-only for year albums). `add-users-to-album-with-pattern` bulk-shares. +- **Dates from OCR** (scanned prints with a visible year): `assets ocr ID|LINK [--json]` + shows Immich's OCR boxes. `client-workflow date-from-ocr (--album-id|--album-name|ID|LINK...|--ids-file|--all) + [--min-score 0.8]` reports each asset whose OCR contains a 4-digit year, with its web link. + `--all` covers the whole library in seconds (one server-side OCR search per year, then OCR check of the + hits) but finds many non-date numbers ("seit 1938", "2000 qm"), so it is refused with `--yes`: use it + as `--all --json` report (pick IDs → `--ids-file … --yes`) or `--all --interactive`. Statuses: + `change` (one year, differs → would become `YYYY-06-01 00:00`), `matches`, `ambiguous` (several years). + No flags = report only; `--json` for agents. `--yes` applies only unambiguous single-asset changes + (tag `immich-admin-cli/date-from-ocr`), never whole albums. Album-wide changes exist only in + `--interactive` (a human at a terminal; refused without one): `[a]lbum` lists every album asset with + old → new date and asks again; those assets get `immich-admin-cli/date-from-ocr-album`; `[n]` skips the rest + of an album. Agents should + run the report, show it to the user, and leave `--interactive` to them. - **Tags**: `tags upsert`, `tags bulk-tag`, `tags tag` for assignment; `client-workflow tag-delete --include/--exclude` for regex bulk deletion (permanent — dry-run first). diff --git a/internal/workflows/datefromocr.go b/internal/workflows/datefromocr.go new file mode 100644 index 0000000..686e70f --- /dev/null +++ b/internal/workflows/datefromocr.go @@ -0,0 +1,275 @@ +package workflows + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "regexp" + "slices" + "strconv" + "time" + + openapi_types "github.com/oapi-codegen/runtime/types" + + "github.com/dhcgn/immich-admin-cli/internal/client" + "github.com/dhcgn/immich-admin-cli/internal/immichapi" +) + +const ( + // DateFromOCRTag marks an asset whose capture year was set from a year + // OCR found in the asset itself. + DateFromOCRTag = "immich-admin-cli/date-from-ocr" + // DateFromOCRAlbumTag marks an asset whose capture year was set because + // another asset in the same album carried that year (weaker evidence). + DateFromOCRAlbumTag = "immich-admin-cli/date-from-ocr-album" + // DefaultOCRMinScore is the default minimum OCR textScore for a box to + // count as evidence. + DefaultOCRMinScore = 0.8 +) + +// OCR candidate statuses. +const ( + OCRStatusChange = "change" // exactly one OCR year, differs from the capture year + OCRStatusMatches = "matches" // exactly one OCR year, equals the capture year + OCRStatusAmbiguous = "ambiguous" // several distinct OCR years +) + +// OCRYearCandidate is an asset whose OCR text contains at least one year. +type OCRYearCandidate struct { + Asset immichapi.AssetResponseDto + Texts []string // OCR texts that contained a year + Years []int // distinct years, ascending +} + +// ProposedYear returns the OCR year when exactly one distinct year was found. +func (c OCRYearCandidate) ProposedYear() (int, bool) { + if len(c.Years) != 1 { + return 0, false + } + return c.Years[0], true +} + +// Status classifies the candidate (see the OCRStatus* constants). +func (c OCRYearCandidate) Status() string { + y, ok := c.ProposedYear() + switch { + case !ok: + return OCRStatusAmbiguous + case y == c.Asset.LocalDateTime.Year(): + return OCRStatusMatches + default: + return OCRStatusChange + } +} + +// OCRTargetDate is the capture date set for a year-only fix: mid-year +// (June 1st, 00:00), so the uncertainty is at most ±6 months. +func OCRTargetDate(year int) time.Time { + return time.Date(year, time.June, 1, 0, 0, 0, 0, time.UTC) +} + +// yearRe matches a standalone 4-digit year 1800–2099, also inside text like +// "Agypten 2004" or "14.07.1986". +var yearRe = regexp.MustCompile(`\b(?:18|19|20)\d{2}\b`) + +// ExtractOCRYears returns the distinct years (ascending, ≤ maxYear) found in +// boxes with textScore ≥ minScore, plus the texts they came from. Pure. +func ExtractOCRYears(boxes []immichapi.AssetOcrResponseDto, minScore float64, maxYear int) ([]int, []string) { + var years []int + var texts []string + for _, b := range boxes { + if b.TextScore < minScore { + continue + } + found := false + for _, m := range yearRe.FindAllString(b.Text, -1) { + y, _ := strconv.Atoi(m) + if y > maxYear { + continue + } + found = true + if !slices.Contains(years, y) { + years = append(years, y) + } + } + if found && !slices.Contains(texts, b.Text) { + texts = append(texts, b.Text) + } + } + slices.Sort(years) + return years, texts +} + +// FetchAssetOCR returns the OCR text boxes of one asset (GET /assets/{id}/ocr). +func FetchAssetOCR(ctx context.Context, c *client.Client, id openapi_types.UUID) ([]immichapi.AssetOcrResponseDto, error) { + resp, err := c.API.GetAssetOcrWithResponse(ctx, id) + if err == nil { + err = client.Check(resp, http.StatusOK) + } + if err != nil { + return nil, fmt.Errorf("fetching OCR: %w", err) + } + if resp.JSON200 == nil { + return nil, nil + } + return *resp.JSON200, nil +} + +// FetchAssets returns the assets for ids (GET /assets/{id} each), skipping +// and logging per-ID failures; the error summarizes how many failed. +func FetchAssets(ctx context.Context, c *client.Client, ids []openapi_types.UUID) ([]immichapi.AssetResponseDto, error) { + var out []immichapi.AssetResponseDto + failures := 0 + for _, id := range ids { + resp, err := c.API.GetAssetInfoWithResponse(ctx, id, nil) + if err == nil { + err = client.Check(resp, http.StatusOK) + } + if err == nil && resp.JSON200 == nil { + err = fmt.Errorf("response had no body") + } + if err != nil { + fmt.Fprintf(os.Stderr, "Error: asset %s: %v\n", id, err) + failures++ + continue + } + out = append(out, *resp.JSON200) + } + if failures > 0 { + return out, fmt.Errorf("%d of %d asset(s) could not be fetched", failures, len(ids)) + } + return out, nil +} + +// ScanOCRYears fetches the OCR boxes of every asset and returns the ones +// containing at least one year. Per-asset failures are logged and counted; +// the error summarizes them while the found candidates are still returned. +func ScanOCRYears(ctx context.Context, c *client.Client, assets []immichapi.AssetResponseDto, minScore float64) ([]OCRYearCandidate, error) { + maxYear := time.Now().Year() + var out []OCRYearCandidate + failures := 0 + for i, a := range assets { + if (i+1)%50 == 0 { + fmt.Fprintf(os.Stderr, "OCR scanned %d/%d asset(s)...\n", i+1, len(assets)) + } + boxes, err := FetchAssetOCR(ctx, c, a.Id) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %s: %v\n", a.OriginalFileName, err) + failures++ + continue + } + if years, texts := ExtractOCRYears(boxes, minScore, maxYear); len(years) > 0 { + out = append(out, OCRYearCandidate{Asset: a, Texts: texts, Years: years}) + } + } + if failures > 0 { + return out, fmt.Errorf("%d of %d asset(s) failed the OCR fetch", failures, len(assets)) + } + return out, nil +} + +// OCRSearchFromYear is the first year FindAssetsWithOCRYears searches for +// (the same lower bound ExtractOCRYears accepts). +const OCRSearchFromYear = 1800 + +// FindAssetsWithOCRYears finds library-wide candidates without fetching OCR +// for every asset: one server-side OCR search (filter.ocr, a fuzzy word +// match) per year from OCRSearchFromYear to toYear, trash excluded, results +// de-duplicated. The fuzzy hits still go through ScanOCRYears, which keeps +// only assets whose OCR really contains a year. +func FindAssetsWithOCRYears(ctx context.Context, c *client.Client, toYear int) ([]immichapi.AssetResponseDto, error) { + seen := map[openapi_types.UUID]bool{} + var out []immichapi.AssetResponseDto + size := 1000 + for y := OCRSearchFromYear; y <= toYear; y++ { + if y%25 == 0 { + fmt.Fprintf(os.Stderr, "OCR search: year %d of %d..%d, %d candidate(s) so far\n", y, OCRSearchFromYear, toYear, len(out)) + } + var pager SearchPager + for { + body := immichapi.MetadataSearchDto{ + Filter: &immichapi.SearchFilter{Ocr: &immichapi.StringSimilarityFilter{Matches: strconv.Itoa(y)}}, + Size: &size, + } + pager.Apply(&body) + resp, err := SearchExcludingTrash(ctx, c, body) + if err == nil { + err = client.Check(resp, http.StatusOK) + } + if err == nil && resp.JSON200 == nil { + err = fmt.Errorf("response had no body") + } + if err != nil { + return out, fmt.Errorf("OCR search for %d: %w", y, err) + } + for _, a := range resp.JSON200.Assets.Items { + if !seen[a.Id] { + seen[a.Id] = true + out = append(out, a) + } + } + if !pager.Next(resp.JSON200.Assets) { + break + } + } + } + return out, nil +} + +// AlbumsForAsset lists the albums containing an asset (GET /albums?assetId=). +func AlbumsForAsset(ctx context.Context, c *client.Client, id openapi_types.UUID) ([]immichapi.AlbumResponseDto, error) { + resp, err := c.API.GetAllAlbumsWithResponse(ctx, &immichapi.GetAllAlbumsParams{AssetId: &id}) + if err == nil { + err = client.Check(resp, http.StatusOK) + } + if err != nil { + return nil, fmt.Errorf("listing albums of asset %s: %w", id, err) + } + if resp.JSON200 == nil { + return nil, nil + } + return *resp.JSON200, nil +} + +// SetAssetsYear sets every asset's capture date to OCRTargetDate(year) via +// updateAsset (the documented deprecated-endpoint exception, see +// FixAlbumDates), then tags the successfully changed assets with tag. +// Continue-on-error; dry-run only prints. +func SetAssetsYear(ctx context.Context, c *client.Client, assets []immichapi.AssetResponseDto, year int, tag string, dryRun bool) error { + if len(assets) == 0 { + return nil + } + target := OCRTargetDate(year) + var changed []openapi_types.UUID + err := RunBatch(assets, + func(a immichapi.AssetResponseDto) string { return a.OriginalFileName }, + func(a immichapi.AssetResponseDto) error { + steps := []Step{{ + Name: fmt.Sprintf("Set date to %s (was %s)", target.Format("2006-01-02 15:04:05"), a.LocalDateTime.Format("2006-01-02 15:04:05")), + Run: func(ctx context.Context) error { return updateAssetDate(ctx, c, a.Id, target) }, + }} + if err := RunSteps(ctx, RunOptions{DryRun: dryRun}, a.OriginalFileName, steps); err != nil { + return err + } + changed = append(changed, a.Id) + return nil + }, + ) + if dryRun { + fmt.Printf("[dry-run] would tag %d asset(s) with %q\n", len(changed), tag) + return err + } + if len(changed) == 0 { + return err + } + tagID, terr := ResolveOrCreateTag(ctx, c, tag) + if terr == nil { + terr = TagAssets(ctx, c, changed, tagID) + } + if terr == nil { + fmt.Printf("Tagged %d asset(s) with %q\n", len(changed), tag) + } + return errors.Join(err, terr) +} diff --git a/internal/workflows/datefromocr_test.go b/internal/workflows/datefromocr_test.go new file mode 100644 index 0000000..5b26fea --- /dev/null +++ b/internal/workflows/datefromocr_test.go @@ -0,0 +1,63 @@ +package workflows + +import ( + "slices" + "testing" + "time" + + "github.com/dhcgn/immich-admin-cli/internal/immichapi" +) + +func box(text string, score float64) immichapi.AssetOcrResponseDto { + return immichapi.AssetOcrResponseDto{Text: text, TextScore: score} +} + +func TestExtractOCRYears(t *testing.T) { + tests := []struct { + name string + boxes []immichapi.AssetOcrResponseDto + years []int + texts []string + }{ + // The two real prod samples the feature was designed against. + {"year inside text", []immichapi.AssetOcrResponseDto{box("Agypten 2004", 0.94)}, []int{2004}, []string{"Agypten 2004"}}, + {"bare year", []immichapi.AssetOcrResponseDto{box("1986", 1.0)}, []int{1986}, []string{"1986"}}, + {"date format", []immichapi.AssetOcrResponseDto{box("14.07.1986", 0.9)}, []int{1986}, []string{"14.07.1986"}}, + {"low score ignored", []immichapi.AssetOcrResponseDto{box("1986", 0.5)}, nil, nil}, + {"future year ignored", []immichapi.AssetOcrResponseDto{box("2099", 1.0)}, nil, nil}, + {"longer number ignored", []immichapi.AssetOcrResponseDto{box("Tel 019860", 1.0), box("1700", 1.0)}, nil, nil}, + {"distinct sorted", []immichapi.AssetOcrResponseDto{box("2004", 1.0), box("1986 und 2004", 1.0)}, []int{1986, 2004}, []string{"2004", "1986 und 2004"}}, + {"duplicate boxes shown once", []immichapi.AssetOcrResponseDto{box("1986", 1.0), box("1986", 0.9)}, []int{1986}, []string{"1986"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + years, texts := ExtractOCRYears(tt.boxes, DefaultOCRMinScore, 2026) + if !slices.Equal(years, tt.years) || !slices.Equal(texts, tt.texts) { + t.Errorf("got years %v texts %q, want %v %q", years, texts, tt.years, tt.texts) + } + }) + } +} + +func TestOCRYearCandidateStatus(t *testing.T) { + at := func(year int) immichapi.AssetResponseDto { + return immichapi.AssetResponseDto{LocalDateTime: time.Date(year, 11, 15, 18, 46, 15, 0, time.UTC)} + } + tests := []struct { + asset immichapi.AssetResponseDto + years []int + want string + }{ + {at(2009), []int{1986}, OCRStatusChange}, + {at(2004), []int{2004}, OCRStatusMatches}, + {at(2004), []int{1986, 2004}, OCRStatusAmbiguous}, + } + for _, tt := range tests { + if got := (OCRYearCandidate{Asset: tt.asset, Years: tt.years}).Status(); got != tt.want { + t.Errorf("Status(asset %d, years %v) = %q, want %q", tt.asset.LocalDateTime.Year(), tt.years, got, tt.want) + } + } + if got := OCRTargetDate(1986).Format("2006-01-02T15:04:05"); got != "1986-06-01T00:00:00" { + t.Errorf("OCRTargetDate(1986) = %s, want 1986-06-01T00:00:00", got) + } +} diff --git a/internal/workflows/progress.go b/internal/workflows/progress.go index df54575..bbf6263 100644 --- a/internal/workflows/progress.go +++ b/internal/workflows/progress.go @@ -40,7 +40,7 @@ func NewByteProgress(label string, total int64, pos, n int, quiet bool) *BytePro Quiet: quiet, Out: os.Stderr, } - p.tty = isTerminalWriter(p.Out) + p.tty = IsTerminal(p.Out) return p } @@ -155,7 +155,8 @@ func (c *countingReader) Read(b []byte) (int, error) { return n, err } -func isTerminalWriter(w io.Writer) bool { +// IsTerminal reports whether w is a terminal (character device). +func IsTerminal(w io.Writer) bool { f, ok := w.(*os.File) if !ok { return false diff --git a/internal/workflows/searchcursor.go b/internal/workflows/searchcursor.go index 07d82b4..c8efacc 100644 --- a/internal/workflows/searchcursor.go +++ b/internal/workflows/searchcursor.go @@ -32,8 +32,14 @@ func (p *SearchPager) Apply(body *immichapi.MetadataSearchDto) { body.Page = nil return } - body.Page = &p.page body.Cursor = nil + // The deprecated page field cannot be combined with the structured + // shape (filter/orderBy): the server rejects it, so start without it. + if body.Filter != nil || body.OrderBy != nil { + body.Page = nil + return + } + body.Page = &p.page } // Next advances the pager from a response's asset listing, reporting whether diff --git a/internal/workflows/searchcursor_test.go b/internal/workflows/searchcursor_test.go index f76e199..fc90dce 100644 --- a/internal/workflows/searchcursor_test.go +++ b/internal/workflows/searchcursor_test.go @@ -69,3 +69,22 @@ func derefOrNil(s *string) string { } return *s } + +// With the structured shape (filter/orderBy) the deprecated page field must +// never be sent — the server rejects the combination. +func TestSearchPagerStructuredShapeNeverSendsPage(t *testing.T) { + var p SearchPager + body := &immichapi.MetadataSearchDto{Filter: &immichapi.SearchFilter{}} + + p.Apply(body) + if body.Page != nil || body.Cursor != nil { + t.Fatalf("first Apply = page %v cursor %v, want both nil", body.Page, body.Cursor) + } + if !p.Next(immichapi.SearchAssetResponseDto{NextCursor: new("abc")}) { + t.Fatal("Next with NextCursor: got false, want true") + } + p.Apply(body) + if body.Page != nil || body.Cursor == nil || *body.Cursor != "abc" { + t.Fatalf("second Apply = page %v cursor %v, want page nil cursor abc", body.Page, derefOrNil(body.Cursor)) + } +} diff --git a/internal/workflows/searchfilter.go b/internal/workflows/searchfilter.go new file mode 100644 index 0000000..7b80bde --- /dev/null +++ b/internal/workflows/searchfilter.go @@ -0,0 +1,36 @@ +package workflows + +import ( + "bytes" + "context" + "encoding/json" + + "github.com/dhcgn/immich-admin-cli/internal/client" + "github.com/dhcgn/immich-admin-cli/internal/immichapi" +) + +// SearchExcludingTrash posts a structured-shape metadata search (POST +// /search/metadata) with filter.trashedAt = {eq: null} added: unlike the +// legacy flat search, the structured filter includes trashed assets unless +// asked not to, and the generated DateFilterNullable cannot express an +// explicit null (omitempty), so it is patched into the JSON. +func SearchExcludingTrash(ctx context.Context, c *client.Client, body immichapi.MetadataSearchDto) (*immichapi.SearchAssetsResponse, error) { + raw, err := json.Marshal(body) + if err != nil { + return nil, err + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + return nil, err + } + filter, _ := m["filter"].(map[string]any) + if filter == nil { + filter = map[string]any{} + } + filter["trashedAt"] = map[string]any{"eq": nil} + m["filter"] = filter + if raw, err = json.Marshal(m); err != nil { + return nil, err + } + return c.API.SearchAssetsWithBodyWithResponse(ctx, &immichapi.SearchAssetsParams{}, "application/json", bytes.NewReader(raw)) +}