imagent-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. imagent/__init__.py +0 -0
  2. imagent/__main__.py +5 -0
  3. imagent/cli.py +128 -0
  4. imagent/commands/__init__.py +0 -0
  5. imagent/commands/after_add.py +82 -0
  6. imagent/commands/delete.py +200 -0
  7. imagent/commands/failed.py +24 -0
  8. imagent/commands/forget.py +63 -0
  9. imagent/commands/help.py +82 -0
  10. imagent/commands/menu.py +155 -0
  11. imagent/commands/scan.py +1394 -0
  12. imagent/commands/search.py +432 -0
  13. imagent/commands/settings.py +139 -0
  14. imagent/commands/setup.py +1409 -0
  15. imagent/commands/uninstall.py +379 -0
  16. imagent/config.py +331 -0
  17. imagent/db/__init__.py +1 -0
  18. imagent/db/connection.py +237 -0
  19. imagent/db/operations.py +683 -0
  20. imagent/db/schema.sql +454 -0
  21. imagent/image_processing/__init__.py +14 -0
  22. imagent/image_processing/convert.py +48 -0
  23. imagent/image_processing/features.py +88 -0
  24. imagent/image_processing/hashing.py +49 -0
  25. imagent/image_processing/memory.py +101 -0
  26. imagent/image_processing/metadata.py +122 -0
  27. imagent/image_processing/ocr.py +129 -0
  28. imagent/image_processing/preprocess.py +33 -0
  29. imagent/image_processing/problems.py +53 -0
  30. imagent/image_processing/sample_pictures.py +214 -0
  31. imagent/os_specific/__init__.py +15 -0
  32. imagent/os_specific/convert.py +34 -0
  33. imagent/os_specific/files.py +64 -0
  34. imagent/os_specific/locking.py +31 -0
  35. imagent/os_specific/memory.py +153 -0
  36. imagent/os_specific/process.py +19 -0
  37. imagent/os_specific/storage.py +102 -0
  38. imagent/pipeline/__init__.py +1 -0
  39. imagent/pipeline/console.py +111 -0
  40. imagent/pipeline/discovery.py +107 -0
  41. imagent/pipeline/error_logger.py +69 -0
  42. imagent/pipeline/error_messages.py +56 -0
  43. imagent/pipeline/failure.py +51 -0
  44. imagent/pipeline/folder_picker.py +289 -0
  45. imagent/pipeline/locking.py +44 -0
  46. imagent/pipeline/progress.py +243 -0
  47. imagent/pipeline/serialisation.py +20 -0
  48. imagent/pipeline/storage.py +30 -0
  49. imagent/pipeline/validation.py +68 -0
  50. imagent/pipeline/versions.py +56 -0
  51. imagent/prompts/analysis_prompt.txt +8 -0
  52. imagent/prompts/analysis_schema.json +12 -0
  53. imagent/prompts/query_prompt.txt +14 -0
  54. imagent/text_processing/__init__.py +1 -0
  55. imagent/text_processing/cleaners.py +32 -0
  56. imagent/text_processing/formatters.py +79 -0
  57. imagent/vlm/__init__.py +1 -0
  58. imagent/vlm/analyzer.py +348 -0
  59. imagent/vlm/calibration.py +288 -0
  60. imagent/vlm/client.py +302 -0
  61. imagent/vlm/reply_validation.py +72 -0
  62. imagent/vlm/response_format.py +7 -0
  63. imagent_cli-0.1.0.dist-info/METADATA +171 -0
  64. imagent_cli-0.1.0.dist-info/RECORD +68 -0
  65. imagent_cli-0.1.0.dist-info/WHEEL +5 -0
  66. imagent_cli-0.1.0.dist-info/entry_points.txt +2 -0
  67. imagent_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
  68. imagent_cli-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1394 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/scan.py — Imagent: scan folders for images, then index them.
4
+
5
+ Scanning compares a folder with the index and queues the new images and those whose picture changed. A file
6
+ whose EXIF facts changed keeps its analysis and only has them refreshed, an image that moved or was renamed keeps
7
+ its record, and one that disappeared is forgotten. Indexing then takes every file queued
8
+ in the ``backlog`` table, including any left over from an interrupted run, and runs each one through the
9
+ full indexing pipeline:
10
+
11
+ file_scan → metadata_extraction → embedding_generation → database_write
12
+
13
+ Successfully processed files (indexed/updated/skipped) are removed from the backlog; a file that fails stays
14
+ queued and is retried on the next run, up to ``config.BACKLOG_MAX_ATTEMPTS`` times (until it changes).
15
+
16
+ All activity is stored in the user-level database (``config.DB_PATH``).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import shutil
24
+ import sqlite3
25
+ import sys
26
+ import textwrap
27
+ import threading
28
+ import time
29
+ from collections import defaultdict, deque
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+ from typing import Callable
33
+
34
+ import httpx
35
+ import ollama
36
+ from PIL import Image
37
+
38
+ from imagent import config
39
+ from imagent.db.connection import describe_db_error, init_db
40
+ from imagent.db.operations import (
41
+ REUSED_COLUMNS,
42
+ VERSION_COLUMNS,
43
+ StoredImage,
44
+ add_failure_history,
45
+ delete_backlog,
46
+ delete_backlog_paths,
47
+ delete_images,
48
+ find_analysis_by_pixels,
49
+ get_backlog,
50
+ get_backlog_paths_for_root,
51
+ get_exhausted_backlog,
52
+ get_exif_fields,
53
+ get_keep_deleted,
54
+ get_or_add_root,
55
+ images_by_path,
56
+ images_outside_root,
57
+ keep_analyses_of,
58
+ list_roots,
59
+ lookup_by_path,
60
+ mark_root_scanned,
61
+ park_backlog,
62
+ record_backlog_failure,
63
+ refresh_image_file,
64
+ refund_backlog_attempts,
65
+ requeue_changed_parked,
66
+ requeue_parked,
67
+ update_image_location,
68
+ update_image_modified_at,
69
+ upsert_backlog,
70
+ upsert_image_data,
71
+ upsert_text_embedding,
72
+ use_deleted_analysis,
73
+ )
74
+ from imagent.image_processing import ocr
75
+ from imagent.image_processing.hashing import compute_hash, compute_pixel_hash
76
+ from imagent.image_processing.memory import check_image_size
77
+ from imagent.image_processing.metadata import extract_file_metadata, iso_utc
78
+ from imagent.image_processing.problems import BUSY, NO_PERMISSION, NOT_DOWNLOADED, UNREADABLE, UNSUPPORTED, ImageProblem, explain, problem
79
+ from imagent.os_specific.files import is_not_downloaded
80
+ from imagent.pipeline.console import file_link, make_output_safe
81
+ from imagent.pipeline.discovery import discover
82
+ from imagent.pipeline.error_messages import describe
83
+ from imagent.pipeline.error_logger import log_error
84
+ from imagent.pipeline.failure import IndexingFailure, RunStopped
85
+ from imagent.pipeline.folder_picker import ask_for_folder
86
+ from imagent.pipeline.locking import AlreadyRunning, is_running, single_instance
87
+ from imagent.pipeline.progress import Progress
88
+ from imagent.pipeline.serialisation import serialize_embedding
89
+ from imagent.pipeline.versions import collect_versions, model_versions
90
+ from imagent.pipeline.validation import find_overlapping_root, validate_folder
91
+ from imagent.text_processing.formatters import build_description, build_search_text
92
+ from imagent.vlm.analyzer import OUT_OF_MEMORY, SERVER_CRASH, TIMEOUT, analyse_image, embed_search_text
93
+ from imagent.vlm.client import NotReady, check_ready, load_model, make_client, unload_model
94
+
95
+ try:
96
+ import questionary
97
+
98
+ STYLE = questionary.Style(
99
+ [
100
+ ("qmark", "fg:ansidefault bold"),
101
+ ("question", "fg:ansidefault bold"),
102
+ ("pointer", "fg:ansidefault bold"),
103
+ ("highlighted", "underline"),
104
+ ("selected", "underline"),
105
+ ("answer", "fg:ansidefault bold"),
106
+ ("instruction", "fg:ansibrightblack"),
107
+ ]
108
+ )
109
+ except ImportError:
110
+ questionary = None
111
+ STYLE = None
112
+
113
+ # Increment this when the stored metadata schema changes incompatibly.
114
+ METADATA_VERSION = 1
115
+ ALL_INDEXED = "\n ✓ All images are indexed." # said when nothing is pending and no image failed
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # Helpers
120
+ # ---------------------------------------------------------------------------
121
+
122
+ def build_vlm_metadata_json(analysis) -> str:
123
+ """Serialise everything learned about the image: the model's reply exactly as it wrote it, the text read in the image
124
+ and the facts read from the pixels. The summary and the description are also kept in their own columns on ``image_data``."""
125
+ return json.dumps({"vlm": analysis.reply, "ocr_text": analysis.ocr_text, "features": analysis.features})
126
+
127
+
128
+ def is_unchanged(existing: dict | None, file_hash: str, modified_at: str) -> bool:
129
+ """Return True if the stored hash and modification time match the current file.
130
+
131
+ When True the image can be safely skipped — neither content nor metadata
132
+ has changed since the last indexing run.
133
+ """
134
+ if existing is None:
135
+ return False
136
+ return existing["hash"] == file_hash and existing["modified_at"] == modified_at
137
+
138
+
139
+ def _changed_since_scan(image_path: Path, scanned_modified_at: str | None) -> bool:
140
+ """True if the file's modification time is not the one the scan saw: it changed after the scan, so it may still be being written.
141
+
142
+ A damaged-looking file that is still changing is not damaged yet; it is tried again later, and nothing is held against it."""
143
+ if not scanned_modified_at:
144
+ return False
145
+ try:
146
+ return iso_utc(os.stat(image_path).st_mtime) != scanned_modified_at
147
+ except OSError:
148
+ return False
149
+
150
+
151
+ def classify_failure(exc: Exception) -> tuple[bool, bool]:
152
+ """Return ``(counts_as_attempt, ollama_problem)`` for an exception raised while indexing one image.
153
+
154
+ Not being able to reach Ollama, or a model that is no longer installed, is not the file's fault,
155
+ so it does not use up one of the file's attempts. Other trouble talking to Ollama (an error reply,
156
+ a timeout, a connection cut off in the middle, as when Ollama crashes) does count, since a file can
157
+ be what makes the model fail, but it also counts towards stopping the run when Ollama keeps failing.
158
+ """
159
+ if isinstance(exc, ollama.ResponseError) and exc.status_code == 404:
160
+ return False, True
161
+ if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout, ConnectionError)):
162
+ return False, True
163
+ if isinstance(exc, (httpx.TransportError, ollama.ResponseError)):
164
+ return True, True
165
+ return True, False
166
+
167
+
168
+ # ---------------------------------------------------------------------------
169
+ # Per-image pipeline
170
+ # ---------------------------------------------------------------------------
171
+
172
+ def index_image(conn, client: ollama.Client, settings: dict, root_id: int, image_path: Path,
173
+ on_stage: Callable[[str], None] = lambda stage: None,
174
+ on_retry: Callable[[str], None] = lambda kind: None) -> tuple[str, str]:
175
+ """Run the complete indexing pipeline for a single image.
176
+
177
+ Stages (in order):
178
+ 1. file_scan — hash + file metadata
179
+ 2. metadata_extraction — VLM analysis
180
+ 3. embedding_generation — build search doc + embed
181
+ 4. database_write — atomic upsert of image_data + text_embeddings
182
+
183
+ ``on_stage`` is told what is being done, before each step; ``on_retry`` is told when the model's reply
184
+ has to be asked for again, and why.
185
+
186
+ Raises ``AnalysisFailed`` when the model's reply could not be put right.
187
+
188
+ Returns ``(result, short_description)``, where the description is empty for a skipped file and
189
+ ``result`` is one of:
190
+ ``'skipped'`` — file is unchanged since the last run.
191
+ ``'updated'`` — file existed but content or metadata changed.
192
+ ``'indexed'`` — new image, not previously seen.
193
+ """
194
+ path_str = str(image_path)
195
+ versions = settings.get("versions", {})
196
+ on_stage("checking file")
197
+ if is_not_downloaded(os.stat(path_str)): # evicted to cloud storage since the scan: reading it would download it
198
+ raise problem(NOT_DOWNLOADED, "not_downloaded",
199
+ step="checked the file", park=False)
200
+
201
+ # ------------------------------------------------------------------
202
+ # Stage 1: file_scan — gather hash and file-level metadata
203
+ # ------------------------------------------------------------------
204
+ file_hash = compute_hash(path_str)
205
+ file_meta = extract_file_metadata(path_str)
206
+ modified_at: str = file_meta["modified_at"]
207
+
208
+ existing = lookup_by_path(conn, path_str)
209
+
210
+ if is_unchanged(existing, file_hash, modified_at):
211
+ return "skipped", ""
212
+
213
+ is_update = existing is not None
214
+
215
+ # ------------------------------------------------------------------
216
+ # Stage 2: metadata_extraction — VLM analysis
217
+ # ------------------------------------------------------------------
218
+ pipeline_start = time.perf_counter()
219
+ pixel_hash, source = _analysis_of_same_pixels(conn, settings, path_str)
220
+ if source is not None: # the same picture is indexed already, whatever its name and metadata: its analysis is used again
221
+ on_stage("reusing the analysis of the same picture")
222
+ pixel_hash = _pixel_hash_for_record(path_str, modified_at, pixel_hash) # also checks the file did not change meanwhile
223
+ record = {
224
+ "root_id": root_id,
225
+ "file_path": path_str,
226
+ "hash": file_hash,
227
+ "pixel_hash": pixel_hash,
228
+ **{column: source[column] for column in REUSED_COLUMNS},
229
+ **file_meta,
230
+ "indexed_at": datetime.now(timezone.utc).isoformat(),
231
+ "processing_time_ms": int((time.perf_counter() - pipeline_start) * 1000),
232
+ }
233
+ on_stage("saving")
234
+ with conn:
235
+ file_id = upsert_image_data(conn, record)
236
+ upsert_text_embedding(conn, file_id, source["embedding"], settings["embedding_model"], source["embedding_digest"],
237
+ source["embedding_dim"])
238
+ if source["from_deleted"]: # the picture is indexed again: its kept analysis is no longer one of a deleted picture
239
+ use_deleted_analysis(conn, pixel_hash)
240
+ return ("updated" if is_update else "indexed"), source["short_description"]
241
+
242
+ analysis = analyse_image(client, settings["vlm_model"], path_str, on_stage, on_retry)
243
+
244
+ # ------------------------------------------------------------------
245
+ # Stage 3: embedding_generation — search document + embedding vector
246
+ # ------------------------------------------------------------------
247
+ on_stage("embedding description")
248
+ search_text = build_search_text(analysis.reply, analysis.ocr_text, config.SUMMARY_FIELD)
249
+ if config.ONE_MODEL_AT_A_TIME: # setup found the two models do not fit in memory together: the vision model goes before the embedding model comes
250
+ unload_model(client, settings["vlm_model"])
251
+ try:
252
+ embedding = embed_search_text(client, settings["embedding_model"], search_text)
253
+ finally:
254
+ if config.ONE_MODEL_AT_A_TIME: # ... and the embedding model goes before the next image's vision model comes
255
+ unload_model(client, settings["embedding_model"])
256
+ if len(embedding) != settings["embedding_dim"]:
257
+ raise RunStopped(
258
+ f"The embedding model returned {len(embedding)} values, but {settings['embedding_dim']} "
259
+ "were measured at setup. The model has changed, so no image can be indexed with it."
260
+ )
261
+ embedding_bytes = serialize_embedding(embedding)
262
+ elapsed_ms = int((time.perf_counter() - pipeline_start) * 1000)
263
+
264
+ pixel_hash = _pixel_hash_for_record(path_str, modified_at, pixel_hash)
265
+
266
+ vlm_metadata_json = build_vlm_metadata_json(analysis)
267
+ short_description = str(analysis.reply[config.SUMMARY_FIELD]).strip()
268
+
269
+ # ------------------------------------------------------------------
270
+ # Stage 4: database_write — atomic transaction
271
+ # ------------------------------------------------------------------
272
+ record = {
273
+ "root_id": root_id,
274
+ "file_path": path_str,
275
+ "hash": file_hash,
276
+ "pixel_hash": pixel_hash,
277
+ "short_description": short_description,
278
+ "description": build_description(analysis.reply, config.SUMMARY_FIELD),
279
+ "vlm_metadata_json": vlm_metadata_json,
280
+ **file_meta,
281
+ **{column: versions.get(column) for column in VERSION_COLUMNS},
282
+ "indexed_at": datetime.now(timezone.utc).isoformat(),
283
+ "processing_time_ms": elapsed_ms,
284
+ "metadata_version": METADATA_VERSION,
285
+ "vlm_model": settings["vlm_model"],
286
+ }
287
+
288
+ on_stage("saving")
289
+ # ``with conn`` starts a transaction; commits on success, rolls back on error.
290
+ with conn:
291
+ file_id = upsert_image_data(conn, record)
292
+ upsert_text_embedding(conn, file_id, embedding_bytes, settings["embedding_model"], versions.get("embedding_digest"), len(embedding))
293
+ add_failure_history(conn, path_str, analysis.attempts)
294
+ # ↑ Commit point — image is now considered fully indexed in the database.
295
+
296
+ return ("updated" if is_update else "indexed"), short_description
297
+
298
+
299
+ def _analysis_of_same_pixels(conn, settings: dict, path: str) -> tuple[str | None, dict | None]:
300
+ """``(pixel hash, analysis)`` for the picture at ``path``: the analysis is that of another indexed image with the same pixels
301
+ (see ``find_analysis_by_pixels``), None when there is none, or when the picture's pixel hash or what an analysis made now
302
+ would be made with is not known. The pixel hash is None when it could not be told; it is not the last word on the picture:
303
+ ``_pixel_hash_for_record`` makes it final."""
304
+ versions = settings.get("versions", {})
305
+ wanted = {
306
+ "vlm_model": settings["vlm_model"], "vlm_digest": versions.get("vlm_digest"), "prompt_hash": versions.get("prompt_hash"),
307
+ "schema_hash": versions.get("schema_hash"), "search_text_version": versions.get("search_text_version"),
308
+ "ocr_version": versions.get("ocr_version"), "metadata_version": METADATA_VERSION,
309
+ "embedding_model": settings["embedding_model"], "embedding_digest": versions.get("embedding_digest"),
310
+ "embedding_dim": settings["embedding_dim"],
311
+ }
312
+ if any(value is None for value in wanted.values()):
313
+ return None, None
314
+ pixel_hash = _pixel_hash_or_none(path) # a picture that cannot be hashed here is analysed, and its failure (if any) reported, as always
315
+ if pixel_hash is None:
316
+ return None, None
317
+ return pixel_hash, find_analysis_by_pixels(conn, pixel_hash, path, wanted)
318
+
319
+
320
+ def _pixel_hash_for_record(path: str, modified_at: str, known: str | None = None) -> str | None:
321
+ """The pixel hash to store with an image that was just analysed (see ``compute_pixel_hash``; ``known`` is the one already
322
+ worked out, which saves reading the picture again), or None for a picture Pillow cannot read, which was analysed through a
323
+ converted copy: a scan then counts every change of such a file as an edit.
324
+
325
+ Raises ``ImageProblem`` (``BUSY``, nothing held against the file) when the file changed since indexing began: its analysis
326
+ would then belong to other pixels than the ones hashed here, and the next scan would not see that."""
327
+ try:
328
+ pixel_hash = known or compute_pixel_hash(path)
329
+ except Exception as exc:
330
+ found = explain(exc, path)
331
+ if found is None:
332
+ raise
333
+ if found.kind != UNSUPPORTED:
334
+ raise found from exc
335
+ pixel_hash = None
336
+ if iso_utc(os.stat(path).st_mtime) != modified_at:
337
+ raise problem(BUSY, "changed_since_scan", step="checked the file did not change while it was analysed", park=False, report=False)
338
+ return pixel_hash
339
+
340
+
341
+ def _index_with_tries(conn, client: ollama.Client, settings: dict, root_id: int, image_path: Path,
342
+ on_stage: Callable[[str], None], on_retry: Callable[[str], None]) -> tuple[str, str]:
343
+ """``index_image``, tried again right away when the failure is Ollama's or the machine's, up to ``config.SERVICE_TRIES`` times.
344
+
345
+ Each try runs the steps for its kind of trouble (waiting longer, starting Ollama again, freeing memory). What a failed
346
+ try was is shown while the next one runs, and kept in the record of what was tried. The last failure is raised."""
347
+ prefix = ""
348
+ for attempt in range(1, config.SERVICE_TRIES + 1):
349
+ try:
350
+ return index_image(conn, client, settings, root_id, image_path, lambda stage: on_stage(prefix + stage), on_retry)
351
+ except PermissionError as exc: # not the file's content, and not something another try changes: the user has to allow reading it
352
+ raise problem(NO_PERMISSION, "no_permission", detail=f"{type(exc).__name__}: {exc}", retry_when="on_request") from exc
353
+ except IndexingFailure as failure:
354
+ if not failure.service or attempt == config.SERVICE_TRIES:
355
+ raise
356
+ with conn:
357
+ add_failure_history(conn, str(image_path), failure.attempts)
358
+ prefix = f"{failure.kind.replace('_', ' ')}: trying again, {attempt + 1} of {config.SERVICE_TRIES} · "
359
+ on_stage(prefix + "starting")
360
+ raise AssertionError("unreachable") # config.SERVICE_TRIES is at least 1
361
+
362
+
363
+ # ---------------------------------------------------------------------------
364
+ # Trying an image again with lower settings
365
+ # ---------------------------------------------------------------------------
366
+
367
+ LOWER_SETTINGS_KINDS = (OUT_OF_MEMORY, SERVER_CRASH, TIMEOUT) # the troubles that a lighter or a more patient way of asking can put right
368
+
369
+
370
+ def _long_side(image_path: Path) -> int | None:
371
+ """The longer side of the picture in pixels, read from its header; None if it cannot be read."""
372
+ try:
373
+ with Image.open(image_path) as image:
374
+ return max(image.size)
375
+ except Exception:
376
+ return None
377
+
378
+
379
+ def lower_settings_steps(kind: str, long_side: int | None) -> list[dict]:
380
+ """What to change, one step after the other, to try an image again that failed with ``kind``.
381
+
382
+ Each step is the changes to the usual device settings (see ``config.temporary_device_settings``) and builds on the one before:
383
+ * no reply in time: start waiting where the failed tries stopped waiting, then ask for smaller pictures;
384
+ * out of memory, or Ollama stopped (which is often what running out of graphics memory looks like): load the model paged in
385
+ from disk, which needs less memory, if it is not already, then ask for smaller pictures.
386
+ The sizes go down as calibration's do (``config.CALIBRATION_EDGE_STEP``) and stop where it stops (``CALIBRATION_MIN_EDGE``).
387
+ They start below the picture's own long side: a size at or above it would change nothing. The context window stays as it is: it
388
+ holds the largest picture, so a smaller one fits it too."""
389
+ usual = config.device_settings()
390
+ changes: dict = {}
391
+ steps: list[dict] = []
392
+ if kind == TIMEOUT:
393
+ changes["timeout_seconds"] = usual["timeout_seconds"] * config.OLLAMA_TIMEOUT_STEP ** config.OLLAMA_TIMEOUT_RAISES
394
+ steps.append(dict(changes))
395
+ elif not usual["use_mmap"]:
396
+ changes["use_mmap"] = True
397
+ steps.append(dict(changes))
398
+ edge = min(usual["image_long_edge"], long_side or usual["image_long_edge"])
399
+ while True:
400
+ edge = int(edge * config.CALIBRATION_EDGE_STEP)
401
+ if edge < config.CALIBRATION_MIN_EDGE:
402
+ return steps
403
+ changes = {**changes, "image_long_edge": edge}
404
+ steps.append(dict(changes))
405
+
406
+
407
+ def _describe_changes(changes: dict) -> str:
408
+ parts = []
409
+ if "timeout_seconds" in changes:
410
+ parts.append(f"waiting up to {changes['timeout_seconds']} s")
411
+ if "use_mmap" in changes:
412
+ parts.append("model paged in from disk")
413
+ if "image_long_edge" in changes:
414
+ parts.append(f"pictures up to {changes['image_long_edge']} px")
415
+ return ", ".join(parts)
416
+
417
+
418
+ def _index_with_lower_settings(conn, client: ollama.Client, settings: dict, row, kind: str,
419
+ on_stage: Callable[[str], None], on_retry: Callable[[str], None]) -> tuple[str, str, dict] | None:
420
+ """``index_image`` for an image that failed with ``kind``, tried again with lower settings: each step of ``lower_settings_steps``
421
+ in turn, until one works. The settings are lower only while that one try runs, so no other image and no later run sees them.
422
+
423
+ Returns ``(result, short_description, what_was_changed)``, or None when no step worked (or there was none). A failure that is
424
+ not the computer's (the model's reply, the picture) is raised: lower settings do not put it right."""
425
+ path = Path(row["file_path"])
426
+ for changes in lower_settings_steps(kind, _long_side(path)):
427
+ label = f"lower settings ({_describe_changes(changes)}) · "
428
+ with config.temporary_device_settings(**changes):
429
+ if kind != TIMEOUT:
430
+ for name in (settings["vlm_model"], settings["embedding_model"]):
431
+ unload_model(client, name) # the memory is free again, and the models load with the settings of this try
432
+ step_client = make_client(timeout=changes["timeout_seconds"]) if "timeout_seconds" in changes else client
433
+ try:
434
+ result, description = index_image(conn, step_client, settings, row["root_id"], path,
435
+ lambda stage: on_stage(label + stage), on_retry)
436
+ except IndexingFailure as failure:
437
+ if not failure.service:
438
+ raise
439
+ with conn:
440
+ add_failure_history(conn, row["file_path"], failure.attempts)
441
+ continue
442
+ return result, description, changes
443
+ return None
444
+
445
+
446
+ def _offer_lower_settings(conn, client: ollama.Client, settings: dict, failures: list, parked_versions: dict | None) -> None:
447
+ """Tell the user which images were not indexed because of the computer (its memory or its speed, not the images) and why, and
448
+ ask whether to try them again with lower settings. The settings are lower for these images only, and for each one by what went
449
+ wrong with it: the usual settings stay as they are, and every other image is indexed as before.
450
+
451
+ ``failures`` holds ``(backlog row, kind of trouble, message)`` for each of them."""
452
+ width = max(shutil.get_terminal_size((80, 24)).columns - 1, 40)
453
+ print(f"\n{len(failures)} image(s) were not indexed, and the trouble was the computer's, not the images':")
454
+ for row, _, message in failures[:10]:
455
+ print(f"\n {file_link(row['file_path'], row['file_path'])}")
456
+ print(textwrap.fill(message, width, initial_indent=" ", subsequent_indent=" "))
457
+ if len(failures) > 10:
458
+ print(f"\n … and {len(failures) - 10} more.")
459
+ if questionary is None or not sys.stdin.isatty():
460
+ print("\nThey stay queued. To try them again with lower settings, scan again in a terminal.")
461
+ return
462
+ print("\nImagent can try each of them again with lower settings, chosen for what went wrong with that image: a longer wait, "
463
+ "the model paged in from disk, a smaller picture. Your usual settings do not change and no other image is affected. "
464
+ "A picture read at a smaller size is described in less detail.")
465
+ if not questionary.confirm("Try these images again with lower settings?", default=False, style=STYLE).ask():
466
+ print("They stay queued, and the next scan tries them with your usual settings.")
467
+ return
468
+ indexed = 0
469
+ progress = Progress(len(failures))
470
+ try:
471
+ for i, (row, kind, _) in enumerate(failures, start=1):
472
+ progress.start(i, row["file_path"])
473
+ try:
474
+ found = _index_with_lower_settings(conn, client, settings, row, kind, progress.stage, lambda kind: None)
475
+ except IndexingFailure as exc: # not the computer's: set aside or left queued, as in the run itself
476
+ with conn:
477
+ add_failure_history(conn, row["file_path"], exc.attempts)
478
+ if exc.park:
479
+ park_backlog(conn, row["file_path"], exc.kind, exc.error_id, exc.retry_when, parked_versions, exc.params)
480
+ else:
481
+ record_backlog_failure(conn, row["file_path"], exc.error_id, count_attempt=False, kind=exc.kind if exc.report else None,
482
+ params=exc.params)
483
+ progress.done("FAILED", str(exc))
484
+ continue
485
+ except sqlite3.Error as exc:
486
+ progress.done("FAILED", describe_db_error(exc))
487
+ break
488
+ except Exception as exc:
489
+ progress.done("FAILED", f"{type(exc).__name__}: {exc}")
490
+ continue
491
+ if found is None:
492
+ progress.done("FAILED", "Still not indexed, even with lower settings. It stays queued.")
493
+ continue
494
+ result, description, changes = found
495
+ with conn:
496
+ delete_backlog(conn, row["file_path"])
497
+ indexed += 1
498
+ progress.done(result, f"({_describe_changes(changes)}) {description}")
499
+ except KeyboardInterrupt:
500
+ progress.close()
501
+ print(" interrupted")
502
+ finally:
503
+ progress.close()
504
+ print(f"\n{indexed} of {len(failures)} image(s) indexed with lower settings; {len(failures) - indexed} stay queued.")
505
+
506
+
507
+ # ---------------------------------------------------------------------------
508
+ # Pipeline runner
509
+ # ---------------------------------------------------------------------------
510
+
511
+ def run(root_ids: set[int] | None = None) -> None:
512
+ """Index the backlog (only the files of the folders ``root_ids`` when given); only one indexing run can be active at a time (a second one says so and stops)."""
513
+ make_output_safe()
514
+ try:
515
+ with single_instance("indexing", "Indexing"):
516
+ _index_backlog(root_ids)
517
+ except AlreadyRunning as exc:
518
+ sys.exit(f"{exc}")
519
+
520
+
521
+ def _index_backlog(root_ids: set[int] | None = None) -> None:
522
+ """Initialise the database, pull pending files from the backlog (only those of the folders ``root_ids`` when given), and index them.
523
+
524
+ Progress is printed for each image. Failures are logged to ``error_logs``
525
+ and their backlog row is kept (with the reason) so the file is retried on the
526
+ next run; every other outcome (indexed/updated/skipped) removes the row from the
527
+ backlog. The run stops early if Ollama keeps failing, if the database cannot be
528
+ written (disk full, for example; the files stay queued, none of their attempts used),
529
+ or on Ctrl+C.
530
+ """
531
+ db_path = str(config.DB_PATH)
532
+ conn = init_db(db_path)
533
+
534
+ try:
535
+ client, settings = check_ready(conn, ("vlm", "embedding"))
536
+ except NotReady as exc:
537
+ conn.close()
538
+ sys.exit(f"{exc}")
539
+
540
+ settings = {**settings, "versions": collect_versions(client, settings)}
541
+ parked_versions = model_versions(settings["versions"])
542
+ if parked_versions:
543
+ with conn:
544
+ queued_again = requeue_changed_parked(conn, parked_versions)
545
+ if queued_again:
546
+ print(f"{queued_again} file(s) set aside because of the model's replies are queued again: the model or the prompt changed.")
547
+
548
+ with conn:
549
+ requeue_parked(conn, kind=NO_PERMISSION) # allowing the file to be read does not change it, so every run tries those files once more
550
+ backlog_rows = get_backlog(conn, config.BACKLOG_MAX_ATTEMPTS)
551
+ if root_ids is not None:
552
+ backlog_rows = [row for row in backlog_rows if row["root_id"] in root_ids]
553
+ total = len(backlog_rows)
554
+
555
+ if total == 0:
556
+ if get_exhausted_backlog(conn, config.BACKLOG_MAX_ATTEMPTS):
557
+ print("Nothing to index.")
558
+ else:
559
+ print(ALL_INDEXED)
560
+ print_failed(conn)
561
+ conn.close()
562
+ return
563
+
564
+ # Text in images is read by OCR. Without its models an image would be stored without its text and never
565
+ # read again, so this is settled before the first image, not found out image by image.
566
+ print()
567
+ print("Loading the text-reading (OCR) engine…")
568
+ try:
569
+ ocr.check_available()
570
+ except Exception as exc:
571
+ conn.close()
572
+ sys.exit(f"The text-reading (OCR) engine could not be loaded ({type(exc).__name__}: {exc}). "
573
+ f"Run: {config.SETUP_COMMAND}. Nothing was indexed; the backlog is kept.")
574
+ # The models load here, so the time of the first image is not the time of loading them. When setup found that the two do not
575
+ # fit in memory together, only the vision model is loaded: the embedding model comes after it, for each image (index_image).
576
+ print("Loading the vision and embedding models…")
577
+ load_model(client, settings["vlm_model"])
578
+ if not config.ONE_MODEL_AT_A_TIME:
579
+ load_model(client, settings["embedding_model"], embedding=True)
580
+ print()
581
+
582
+ in_a_row = 0 # consecutive images that failed for a reason that is not theirs (Ollama, the machine)
583
+ last_service_error = ""
584
+ lower_settings_offer: list[tuple] = [] # (backlog row, kind, message) of images that failed for the computer's trouble: the user may try them again with lower settings
585
+ can_offer = True # not after Ctrl+C, a database that could not be written, or a model that changed
586
+ io_failures: list[str] = [] # files that failed one after another with an error of the file system: a drive that went away, perhaps
587
+ stopped = ""
588
+ recent_retries: deque[bool] = deque(maxlen=config.RETRY_RATE_WINDOW) # for the latest analysed images: did the model's reply need asking for again?
589
+ progress = Progress(total)
590
+ root_paths = {root["root_id"]: root["path"] for root in list_roots(conn)}
591
+
592
+ try:
593
+ for i, row in enumerate(backlog_rows, start=1):
594
+ image_path = Path(row["file_path"])
595
+ progress.start(i, image_path)
596
+
597
+ retried: list[str] = []
598
+ try:
599
+ try:
600
+ result, short_description = _index_with_tries(conn, client, settings, row["root_id"], image_path, progress.stage,
601
+ retried.append)
602
+ with conn:
603
+ delete_backlog(conn, row["file_path"])
604
+ progress.done(result, short_description)
605
+ in_a_row = 0
606
+ io_failures.clear()
607
+ if result != "skipped":
608
+ recent_retries.append(bool(retried))
609
+ except sqlite3.Error:
610
+ raise # the database is the problem, not this image: handled below
611
+ except IndexingFailure as exc:
612
+ if exc.kind == UNREADABLE and _changed_since_scan(image_path, row["modified_at"]):
613
+ exc = ImageProblem(BUSY, "changed_since_scan", exc.attempts, park=False, report=False)
614
+ # Every step for this kind of trouble was tried, so trying again would only repeat them. The file is set
615
+ # aside with the whole record of what was tried (it is queued again when the file changes), or, when the
616
+ # fault is not the file's, left queued with its attempts untouched.
617
+ params = dict(exc.params)
618
+ if exc.service: # the machine's trouble: it was tried several times, and the user is told what to do about it
619
+ params["tries"] = config.SERVICE_TRIES
620
+ message = describe(exc.error_id, params)
621
+ log_error(conn, stage="pipeline", exc=exc, file_path=str(image_path),
622
+ metadata={"root_id": row["root_id"], "kind": exc.kind})
623
+ with conn:
624
+ add_failure_history(conn, row["file_path"], exc.attempts)
625
+ if exc.park:
626
+ park_backlog(conn, row["file_path"], exc.kind, exc.error_id, exc.retry_when, parked_versions, params)
627
+ else:
628
+ record_backlog_failure(conn, row["file_path"], exc.error_id, count_attempt=False,
629
+ kind=exc.kind if exc.report else None, params=params)
630
+ progress.done("FAILED", message)
631
+ io_failures.clear()
632
+ if exc.service:
633
+ in_a_row += 1
634
+ last_service_error = str(exc)
635
+ if exc.kind in LOWER_SETTINGS_KINDS:
636
+ lower_settings_offer.append((row, exc.kind, message))
637
+ else:
638
+ in_a_row = 0
639
+ if exc.model_trouble:
640
+ recent_retries.append(True)
641
+ except RunStopped as exc:
642
+ progress.done("FAILED", str(exc))
643
+ stopped = f"Indexing stopped. {exc} Nothing was held against the files; the rest stays queued."
644
+ can_offer = False
645
+ break
646
+ except Exception as exc:
647
+ if isinstance(exc, FileNotFoundError) and _is_gone(image_path, root_paths.get(row["root_id"])):
648
+ # Deleted since the scan, while its folder is still there: nothing to index. The next scan removes any stale record.
649
+ with conn:
650
+ delete_backlog(conn, row["file_path"])
651
+ progress.done("gone")
652
+ continue
653
+ counts_as_attempt, ollama_problem = classify_failure(exc)
654
+ log_error(
655
+ conn,
656
+ stage="pipeline",
657
+ exc=exc,
658
+ file_path=str(image_path),
659
+ metadata={"root_id": row["root_id"]},
660
+ )
661
+ with conn:
662
+ record_backlog_failure(conn, row["file_path"], "unexpected", counts_as_attempt,
663
+ params={"type": type(exc).__name__, "text": str(exc)})
664
+ progress.done("FAILED", f"{type(exc).__name__}: {exc}")
665
+ if ollama_problem:
666
+ in_a_row += 1
667
+ last_service_error = f"{type(exc).__name__}: {exc}"
668
+ else:
669
+ in_a_row = 0
670
+ if isinstance(exc, OSError) and not ollama_problem:
671
+ io_failures.append(row["file_path"])
672
+ else:
673
+ io_failures.clear()
674
+ if len(io_failures) >= config.MAX_CONSECUTIVE_SERVICE_FAILURES:
675
+ with conn:
676
+ refund_backlog_attempts(conn, io_failures) # a drive that went away is not these files' fault
677
+ stopped = (f"Reading the images failed {len(io_failures)} times in a row (last error: {type(exc).__name__}: {exc}), "
678
+ "so indexing stopped. Is the drive still connected and readable? "
679
+ "The files keep all their attempts; the rest stays queued.")
680
+ break
681
+ if in_a_row >= config.MAX_CONSECUTIVE_SERVICE_FAILURES:
682
+ stopped = (f"{in_a_row} images in a row failed for a reason that is not theirs, so indexing stopped "
683
+ f"(last error: {last_service_error}). Check that Ollama is running and has enough memory "
684
+ "and that the text-reading models are intact, then run it again; the rest stays queued.")
685
+ break
686
+ if len(recent_retries) == recent_retries.maxlen and sum(recent_retries) / len(recent_retries) >= config.RETRY_RATE_STOP:
687
+ stopped = (f"The model's reply had to be asked for again for {sum(recent_retries)} of the last {len(recent_retries)} images, "
688
+ "so indexing stopped: this points at the model or the prompt, not at the images. "
689
+ "Nothing was held against the images. Close other apps that use a lot of memory, then scan again; "
690
+ "the rest stays queued.")
691
+ break
692
+ except sqlite3.Error as exc:
693
+ message = describe_db_error(exc)
694
+ progress.done("FAILED", message)
695
+ stopped = f"Indexing stopped. {message} Finished images are saved and the rest stays queued."
696
+ can_offer = False
697
+ break
698
+ except KeyboardInterrupt:
699
+ progress.close()
700
+ print(" interrupted")
701
+ can_offer = False
702
+ stopped = "Interrupted. Finished images are saved; the rest stays queued."
703
+ finally:
704
+ progress.close()
705
+
706
+ if settings["vlm_model"] != settings["judge_model"]:
707
+ unload_model(client, settings["vlm_model"]) # searching does not need the VLM; free its memory for the judge model
708
+
709
+ if stopped:
710
+ print(f"\n{stopped}")
711
+ try:
712
+ print_failed(conn)
713
+ except sqlite3.Error:
714
+ pass # the database is what stopped the run; its message is above
715
+ if lower_settings_offer and can_offer:
716
+ _offer_lower_settings(conn, client, settings, lower_settings_offer, parked_versions)
717
+ print()
718
+
719
+ conn.close()
720
+ if stopped:
721
+ sys.exit(1)
722
+
723
+
724
+ def _is_gone(image_path: Path, root_path: str | None) -> bool:
725
+ """True if the file was deleted while the folder it was found in is still there.
726
+
727
+ A missing file whose folder is missing too points at a drive that went away, or at a missing program file, and is
728
+ not the file's doing: it is handled as a failure to read, which stops the run after a few in a row."""
729
+ return root_path is not None and Path(root_path).is_dir() and not image_path.exists()
730
+
731
+
732
+ def print_failed(conn, limit: int | None = 10) -> int:
733
+ """Tell the user which images could not be indexed, each with the reason and what can be done about it. Returns how many there are.
734
+
735
+ Only images whose every try is over are listed; one that is indexed later (or whose file is gone) drops out of the list by itself.
736
+ ``limit`` is how many to show; None shows them all."""
737
+ failed = get_exhausted_backlog(conn, config.BACKLOG_MAX_ATTEMPTS)
738
+ if not failed:
739
+ return 0
740
+ print(f"\n{len(failed)} image(s) could not be indexed:")
741
+ width = max(shutil.get_terminal_size((80, 24)).columns - 1, 40)
742
+ by_folder = defaultdict(list)
743
+ for item in sorted(failed, key=lambda item: (os.path.dirname(item["file_path"]), os.path.basename(item["file_path"])))[:limit]:
744
+ by_folder[os.path.dirname(item["file_path"])].append(item)
745
+ bold = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and "NO_COLOR" not in os.environ
746
+ for folder, items in by_folder.items():
747
+ heading = f"\033[1m{folder}\033[0m" if bold else folder
748
+ print(f"\n {heading}")
749
+ for item in items:
750
+ print(f" {file_link(os.path.basename(item['file_path']), item['file_path'])}")
751
+ print(textwrap.fill(describe(item["error_id"], item["error_params"]) or "No reason was recorded.", width, initial_indent=" ", subsequent_indent=" "))
752
+ if limit is not None and len(failed) > limit:
753
+ print(f"\n … and {len(failed) - limit} more. Choose \"Show the images that could not be indexed\" in the menu to see them all.")
754
+ return len(failed)
755
+
756
+
757
+ # ---------------------------------------------------------------------------
758
+ # Scanning
759
+ # ---------------------------------------------------------------------------
760
+
761
+ class RootOverlapError(ValueError):
762
+ """The folder contains, or lies inside, a folder that was scanned before."""
763
+
764
+
765
+ def _inside(path: str, folders: list[str]) -> bool:
766
+ return any(path.startswith(folder + os.sep) for folder in folders)
767
+
768
+
769
+ def _warn_about(items: list, problem: str, consequence: str, shown: int = 3) -> None:
770
+ """Tell the user about folders or files the scan had trouble with: the first few by name, then how many more."""
771
+ if not items:
772
+ return
773
+ print(f"{len(items)} {problem}; {consequence}")
774
+ for item in items[:shown]:
775
+ print(f" {item}")
776
+ if len(items) > shown:
777
+ print(f" … and {len(items) - shown} more")
778
+
779
+
780
+ def _pixel_hash_or_none(path: str) -> str | None:
781
+ """The pixel hash of the picture at ``path`` (see ``compute_pixel_hash``), or None when it cannot be told: the picture is too
782
+ large for the memory free, damaged, or in a format Pillow does not read. A scan never guesses from None: a file whose pixel
783
+ hash is unknown counts as edited, and one that cannot be compared is not taken for a moved file."""
784
+ try:
785
+ check_image_size(path)
786
+ return compute_pixel_hash(path)
787
+ except Exception:
788
+ return None
789
+
790
+
791
+ def _picture_size(path: str) -> tuple[int, int] | None:
792
+ """The sides of the picture, the shorter first (a picture turned by its orientation keeps them), read from the file's header."""
793
+ try:
794
+ with Image.open(path) as image:
795
+ return tuple(sorted(image.size))
796
+ except Exception:
797
+ return None
798
+
799
+
800
+ def _is_missing(path: str) -> bool:
801
+ """True if nothing is at ``path``. A path that cannot be looked at (a folder without permission) is not missing, only unknown."""
802
+ try:
803
+ os.stat(path)
804
+ except (FileNotFoundError, NotADirectoryError):
805
+ return True
806
+ except OSError:
807
+ return False
808
+ return False
809
+
810
+
811
+ def _pair_moves(new_by_key: dict[str, list[str]], gone_by_key: dict[str, list[str]], gone: dict[str, StoredImage],
812
+ on_disk: dict[str, str]) -> dict[str, str]:
813
+ """Pair each new path with the path it was moved from: ``new_by_key`` and ``gone_by_key`` list the new and the vanished paths
814
+ by the hash of what they hold, and each new path is paired with a vanished one of the same hash (``{new path: old path}``).
815
+
816
+ Of identical copies, the pair that looks most like a move is made first: the same modified time and name, then the same time
817
+ (a move keeps it), then the same name, then any. So when two copies of a picture exist and one was renamed, the one that was
818
+ renamed is the one the report says moved."""
819
+ ways = (lambda path, modified: (modified, os.path.basename(path)), lambda path, modified: modified,
820
+ lambda path, modified: os.path.basename(path), lambda path, modified: None)
821
+ pairs: dict[str, str] = {}
822
+ for key, new_paths in new_by_key.items():
823
+ old_paths, new_paths = list(gone_by_key.get(key, ())), list(new_paths)
824
+ for way in ways:
825
+ if not old_paths or not new_paths:
826
+ break
827
+ candidates = defaultdict(deque)
828
+ for old in old_paths:
829
+ candidates[way(old, gone[old].modified_at)].append(old)
830
+ unpaired = []
831
+ for new in new_paths:
832
+ if candidates.get(way(new, on_disk[new])):
833
+ pairs[new] = candidates[way(new, on_disk[new])].popleft()
834
+ else:
835
+ unpaired.append(new)
836
+ used = set(pairs.values())
837
+ old_paths = [old for old in old_paths if old not in used]
838
+ new_paths = unpaired
839
+ return pairs
840
+
841
+
842
+ def _find_moves(conn, new_paths: list[str], gone: dict[str, StoredImage], on_disk: dict[str, str], sizes: dict[str, int],
843
+ file_hashes: dict[str, str | None], counts: dict[str, int]) -> dict[str, str]:
844
+ """Which of ``new_paths`` are pictures of ``gone`` (indexed, but no longer at their path) at another path: ``{new path: old path}``.
845
+
846
+ First by the bytes of the file (the hash of the whole file), then, for what is left, by the picture (the pixel hash), which also
847
+ finds a file whose EXIF or other embedded data was edited as it was moved. A file is only read when something that could be its
848
+ old self exists: by its size for the first, by the sides of the picture for the second, so a folder of new pictures is not read.
849
+ ``file_hashes`` keeps the hash of each new file read (None when it could not be), for the caller to use."""
850
+ if not gone or not new_paths:
851
+ return {}
852
+
853
+ def hash_of(path: str) -> str | None:
854
+ if path not in file_hashes:
855
+ try:
856
+ file_hashes[path] = compute_hash(path)
857
+ except OSError as exc:
858
+ counts["unreadable"] += 1
859
+ log_error(conn, stage="scan", exc=exc, file_path=path)
860
+ file_hashes[path] = None
861
+ return file_hashes[path]
862
+
863
+ gone_by_hash: dict[str, list[str]] = defaultdict(list)
864
+ for path, image in gone.items():
865
+ gone_by_hash[image.hash].append(path)
866
+ sizes_gone = {image.file_size for image in gone.values()}
867
+ new_by_hash: dict[str, list[str]] = defaultdict(list)
868
+ for path in new_paths:
869
+ if None in sizes_gone or sizes[path] in sizes_gone:
870
+ digest = hash_of(path)
871
+ if digest is not None:
872
+ new_by_hash[digest].append(path)
873
+ moved = _pair_moves(new_by_hash, gone_by_hash, gone, on_disk)
874
+
875
+ taken = set(moved.values())
876
+ left_gone = {path: image for path, image in gone.items() if path not in taken and image.pixel_hash}
877
+ left_new = [path for path in new_paths if path not in moved and file_hashes.get(path, "") is not None]
878
+ if left_gone and left_new:
879
+ gone_by_pixels: dict[str, list[str]] = defaultdict(list)
880
+ for path, image in left_gone.items():
881
+ gone_by_pixels[image.pixel_hash].append(path)
882
+ sides_gone = {tuple(sorted((image.width, image.height))) if image.width and image.height else None
883
+ for image in left_gone.values()}
884
+ new_by_pixels: dict[str, list[str]] = defaultdict(list)
885
+ for path in left_new:
886
+ if None not in sides_gone and _picture_size(path) not in sides_gone:
887
+ continue
888
+ pixel_hash = _pixel_hash_or_none(path)
889
+ if pixel_hash is not None and hash_of(path) is not None:
890
+ new_by_pixels[pixel_hash].append(path)
891
+ moved.update(_pair_moves(new_by_pixels, gone_by_pixels, left_gone, on_disk))
892
+ return moved
893
+
894
+
895
+ def _gone_from_other_folders(conn, root_id: int) -> dict[str, StoredImage]:
896
+ """The indexed images of the other scanned folders whose file is not there any more, while their folder is: pictures that may
897
+ have been moved into the folder being scanned. A folder that cannot be read now (a drive that is not connected) gives none:
898
+ its images are unknown, not gone."""
899
+ folders = {root["root_id"]: Path(root["path"]).is_dir() for root in list_roots(conn)}
900
+ return {path: image for other, path, image in images_outside_root(conn, root_id)
901
+ if folders.get(other) and _is_missing(path)}
902
+
903
+
904
+ def _find_moves_out(conn, root_id: int, gone: dict[str, StoredImage], counts: dict[str, int]) -> set[str]:
905
+ """Which of ``gone`` (indexed images that are not at their path any more) are in another added folder now: their records are
906
+ pointed at their new path and folder (as ``_apply_moves`` does), and the old paths are returned.
907
+
908
+ A scan of one folder cannot tell a deleted picture from one moved into a folder that has not been scanned yet, so the other folders
909
+ are looked at, for files they do not have in the index. A folder that cannot be read now (a drive that is not connected) is skipped."""
910
+ found: set[str] = set()
911
+ if not gone:
912
+ return found
913
+ for other in list_roots(conn):
914
+ folder = Path(other["path"])
915
+ if other["root_id"] == root_id or len(found) == len(gone) or not folder.is_dir() or not os.access(folder, os.R_OK):
916
+ continue
917
+ known = images_by_path(conn, other["root_id"])
918
+ on_disk: dict[str, str] = {}
919
+ sizes: dict[str, int] = {}
920
+ for file_path in discover(folder).images:
921
+ path = str(file_path)
922
+ try:
923
+ status = os.stat(path)
924
+ except OSError:
925
+ continue
926
+ if path in known or status.st_size == 0 or is_not_downloaded(status):
927
+ continue
928
+ on_disk[path] = iso_utc(status.st_mtime)
929
+ sizes[path] = status.st_size
930
+ left = {path: image for path, image in gone.items() if path not in found}
931
+ file_hashes: dict[str, str | None] = {}
932
+ moved = _find_moves(conn, list(on_disk), left, on_disk, sizes, file_hashes, counts)
933
+ _apply_moves(conn, moved, left, other["root_id"], on_disk, file_hashes, counts)
934
+ found.update(moved.values())
935
+ return found
936
+
937
+
938
+ def _apply_moves(conn, moved: dict[str, str], gone: dict[str, StoredImage], root_id: int, on_disk: dict[str, str],
939
+ file_hashes: dict[str, str | None], counts: dict[str, int]) -> None:
940
+ """Point the record of each moved picture at its new path (and folder). When the file's bytes differ from before (the same
941
+ picture with other embedded data) the facts stored about the file are refreshed too; the analysis is left as it is."""
942
+ for new_path, old_path in moved.items():
943
+ image = gone[old_path]
944
+ details = None
945
+ if file_hashes.get(new_path) != image.hash:
946
+ try:
947
+ details = {**extract_file_metadata(new_path), "modified_at": on_disk[new_path]}
948
+ except OSError as exc:
949
+ counts["unreadable"] += 1
950
+ log_error(conn, stage="scan", exc=exc, file_path=new_path)
951
+ with conn:
952
+ update_image_location(conn, image.file_id, root_id, new_path, on_disk[new_path])
953
+ if details is not None:
954
+ refresh_image_file(conn, image.file_id, file_hashes[new_path], details)
955
+
956
+
957
+ def _register_root(conn, root: Path) -> int:
958
+ """Add ``root`` to the scanned folders (nothing happens if it was added before) and return its id; raises ``RootOverlapError`` if
959
+ it contains, or lies inside, another added folder."""
960
+ conflict = find_overlapping_root(root, [r["path"] for r in list_roots(conn)])
961
+ if conflict:
962
+ raise RootOverlapError(f"{root} overlaps the folder already scanned: {conflict}")
963
+ with conn:
964
+ return get_or_add_root(conn, str(root))
965
+
966
+
967
+ def scan(root: Path, allow_mass_delete: bool = False) -> dict[str, int]:
968
+ """Reconcile the index with the files under ``root``; the other folders' images are never deleted.
969
+
970
+ Every file is in exactly one of these states (the counts of the result). A file whose path is in the index is:
971
+ * up to date (``up_to_date``): nothing about its picture or its EXIF facts changed, even if its timestamp or other data in
972
+ the file did (what is stored about the file is brought up to date);
973
+ * details updated (``details_updated``): the picture is the same but its EXIF facts changed; they are refreshed in the
974
+ index, nothing is analysed or embedded again (the embedded text holds no EXIF);
975
+ * changed (``queued_modified``): its picture is not the one that was analysed, the pixels after the EXIF orientation
976
+ (queued; the old record stays until the new one is ready).
977
+ A file whose path is not in the index is:
978
+ * moved (``moved``): a picture indexed under another path, in another folder (a subfolder of this one, or another scanned
979
+ folder), that is gone from there. Its record follows it and nothing is analysed again. Found by the file's bytes, then by
980
+ its pixels;
981
+ * renamed (``renamed``): the same, but the old path is in the same folder as the new one (only the name changed). The
982
+ report shows it with the details updated;
983
+ * new (``queued_new``): anything else (queued).
984
+ A changed or new file that failed to be indexed on every try (it is still in the backlog, with its reason) is counted as
985
+ ``failed`` instead, not as queued.
986
+ An indexed file that is gone from its path and was not moved here is looked for in the other added folders, among the files they
987
+ have not indexed yet; one found there is moved to that folder (``moved_out``), whichever folder is scanned first.
988
+ An indexed file that is gone from its path and was not moved is removed (``deleted``).
989
+ Three things protect the index from a scan that
990
+ cannot see what is really there:
991
+ * what lies in a subfolder that could not be read is neither deleted nor treated as moved;
992
+ * if the folder shows no images at all while some are indexed (a drive that is not
993
+ mounted, for example), or at least ``config.SCAN_GUARD_MIN_FILES`` indexed images are gone
994
+ and they are more than ``config.SCAN_GUARD_MAX_SHARE`` of the folder's indexed images,
995
+ nothing is deleted unless ``allow_mass_delete`` is True; ``delete_blocked`` in the
996
+ result tells the caller.
997
+ Files that cannot be indexed are counted and left out: empty files and files whose name
998
+ is not valid text (``empty``, ``bad_names``).
999
+ """
1000
+ conn = init_db(str(config.DB_PATH))
1001
+ counts = {
1002
+ "scanned": 0,
1003
+ "queued_new": 0,
1004
+ "queued_modified": 0,
1005
+ "failed": 0,
1006
+ "details_updated": 0,
1007
+ "moved": 0,
1008
+ "moved_out": 0,
1009
+ "renamed": 0,
1010
+ "up_to_date": 0,
1011
+ "deleted": 0,
1012
+ "delete_blocked": 0,
1013
+ "unreadable": 0,
1014
+ "unreadable_dirs": 0,
1015
+ "empty": 0,
1016
+ "bad_names": 0,
1017
+ "not_downloaded": 0,
1018
+ }
1019
+
1020
+ try:
1021
+ root_id = _register_root(conn, root)
1022
+
1023
+ # path -> modification time, for every image on disk right now.
1024
+ found = discover(root)
1025
+ counts["unreadable_dirs"] = len(found.unreadable_dirs)
1026
+ counts["bad_names"] = len(found.bad_names)
1027
+ _warn_about(found.unreadable_dirs, "folder(s) could not be read", "their images were left in the index as they are:")
1028
+ _warn_about(found.bad_names, "file(s) have a name that is not valid text", "rename them to have them indexed:")
1029
+ unseen = [str(folder) for folder in found.unreadable_dirs]
1030
+ on_disk: dict[str, str] = {}
1031
+ sizes: dict[str, int] = {} # path -> size in bytes, for telling which new files could be an indexed one that moved
1032
+ not_downloaded: list[Path] = [] # in cloud storage, not on this computer: neither read (it would be downloaded) nor forgotten
1033
+ for file_path in found.images:
1034
+ try:
1035
+ status = os.stat(file_path)
1036
+ except OSError as exc: # removed or locked while scanning
1037
+ counts["unreadable"] += 1
1038
+ log_error(conn, stage="scan", exc=exc, file_path=str(file_path))
1039
+ continue
1040
+ if is_not_downloaded(status):
1041
+ not_downloaded.append(file_path)
1042
+ continue
1043
+ if status.st_size == 0:
1044
+ counts["empty"] += 1
1045
+ continue
1046
+ on_disk[str(file_path)] = iso_utc(status.st_mtime)
1047
+ sizes[str(file_path)] = status.st_size
1048
+ counts["scanned"] = len(on_disk)
1049
+ counts["not_downloaded"] = len(not_downloaded)
1050
+ _warn_about(not_downloaded, "image(s) are in cloud storage and not downloaded to this computer",
1051
+ "they were not read, and what is indexed of them was kept:")
1052
+ away = {str(path) for path in not_downloaded}
1053
+
1054
+ stored = images_by_path(conn, root_id)
1055
+ # Whatever lies in a folder that could not be read is unknown, not gone; so is a file that is in the cloud only.
1056
+ vanished = [path for path in stored if path not in on_disk and path not in away and not _inside(path, unseen)]
1057
+ new_paths = [path for path in on_disk if path not in stored]
1058
+
1059
+ # A new path holding a picture that is gone from its own path is that picture, moved or renamed: from this folder, or
1060
+ # from another scanned one. Files are only read when something that could be their old self is gone (see _find_moves).
1061
+ file_hashes: dict[str, str | None] = {}
1062
+ gone_here = {path: stored[path] for path in vanished}
1063
+ moved = _find_moves(conn, new_paths, gone_here, on_disk, sizes, file_hashes, counts)
1064
+ _apply_moves(conn, moved, gone_here, root_id, on_disk, file_hashes, counts)
1065
+ left = [path for path in new_paths if path not in moved]
1066
+ gone_elsewhere = _gone_from_other_folders(conn, root_id) if left else {}
1067
+ moved_in = _find_moves(conn, left, gone_elsewhere, on_disk, sizes, file_hashes, counts)
1068
+ _apply_moves(conn, moved_in, gone_elsewhere, root_id, on_disk, file_hashes, counts)
1069
+ for new_path, old_path in {**moved, **moved_in}.items(): # same folder, other name: renamed; another folder: moved
1070
+ counts["renamed" if os.path.dirname(new_path) == os.path.dirname(old_path) else "moved"] += 1
1071
+
1072
+ queued: list[tuple[str, str]] = [] # (path, "queued_new" or "queued_modified") of the files put in the backlog by this scan
1073
+
1074
+ # Files present before and now: up to date, or changed in some way. Only a file whose timestamp changed is looked at.
1075
+ for path, modified_at in on_disk.items():
1076
+ row = stored.get(path)
1077
+ if row is None:
1078
+ continue
1079
+ if row.modified_at == modified_at:
1080
+ counts["up_to_date"] += 1
1081
+ continue
1082
+ try:
1083
+ file_hash = compute_hash(path)
1084
+ except OSError as exc:
1085
+ counts["unreadable"] += 1
1086
+ log_error(conn, stage="scan", exc=exc, file_path=path)
1087
+ continue
1088
+ if file_hash == row.hash: # a touch or a sync changed the timestamp, not the file
1089
+ with conn:
1090
+ update_image_modified_at(conn, row.file_id, modified_at)
1091
+ counts["up_to_date"] += 1
1092
+ continue
1093
+ pixel_hash = _pixel_hash_or_none(path)
1094
+ if pixel_hash is None or pixel_hash != row.pixel_hash: # not the picture that was analysed (or not known to be)
1095
+ with conn:
1096
+ upsert_backlog(conn, path, root_id, modified_at)
1097
+ queued.append((path, "queued_modified"))
1098
+ continue
1099
+ try: # the same picture in other bytes: the EXIF facts may differ, nothing else needs to be done about it
1100
+ details = {**extract_file_metadata(path), "modified_at": modified_at}
1101
+ except OSError as exc:
1102
+ counts["unreadable"] += 1
1103
+ log_error(conn, stage="scan", exc=exc, file_path=path)
1104
+ continue
1105
+ with conn:
1106
+ stored_exif = get_exif_fields(conn, row.file_id)
1107
+ exif_changed = any(value != details[field] for field, value in stored_exif.items())
1108
+ refresh_image_file(conn, row.file_id, file_hash, details)
1109
+ counts["details_updated" if exif_changed else "up_to_date"] += 1
1110
+
1111
+ moved_paths = set(moved) | set(moved_in)
1112
+ with conn:
1113
+ for path in new_paths:
1114
+ if path not in moved_paths:
1115
+ upsert_backlog(conn, path, root_id, on_disk[path])
1116
+ queued.append((path, "queued_new"))
1117
+ # A file whose every try is over stays in the backlog as it is: it is failed (listed with its reason), not waiting to be indexed.
1118
+ failed = {row["file_path"] for row in get_exhausted_backlog(conn, config.BACKLOG_MAX_ATTEMPTS)}
1119
+ for path, state in queued:
1120
+ counts["failed" if path in failed else state] += 1
1121
+
1122
+ # Forget what is gone: stored images, and queued files that vanished before they were indexed.
1123
+ moved_from = set(moved.values())
1124
+ # Pictures gone from here may be in another added folder, not scanned yet: found there now, before anything is deleted, whichever folder is scanned first.
1125
+ moved_out = _find_moves_out(conn, root_id, {path: stored[path] for path in vanished if path not in moved_from}, counts)
1126
+ counts["moved_out"] = len(moved_out)
1127
+ gone = [path for path in vanished if path not in moved_from and path not in moved_out]
1128
+ mass_delete = gone and (
1129
+ not on_disk
1130
+ or (len(gone) >= config.SCAN_GUARD_MIN_FILES and len(gone) > len(stored) * config.SCAN_GUARD_MAX_SHARE)
1131
+ )
1132
+ if mass_delete and not allow_mass_delete:
1133
+ counts["delete_blocked"] = len(gone)
1134
+ gone = []
1135
+ stale_queue = [path for path in get_backlog_paths_for_root(conn, root_id)
1136
+ if path not in on_disk and path not in away and not _inside(path, unseen)]
1137
+ gone_ids = [stored[path].file_id for path in gone]
1138
+ with conn:
1139
+ keep_analyses_of(conn, gone_ids, get_keep_deleted(conn)) # what the user chose at setup: the analysis may be used again if the picture comes back
1140
+ counts["deleted"] = delete_images(conn, gone_ids)
1141
+ delete_backlog_paths(conn, stale_queue)
1142
+
1143
+ with conn:
1144
+ mark_root_scanned(conn, root_id)
1145
+ return counts
1146
+ finally:
1147
+ conn.close()
1148
+
1149
+
1150
+ def _ask_yes_no(question: str) -> bool:
1151
+ try:
1152
+ return input(question).strip().lower() in ("y", "yes")
1153
+ except EOFError: # no terminal attached: the safe answer is no
1154
+ return False
1155
+
1156
+
1157
+ def _scannable(saved: list[str]) -> list[Path]:
1158
+ """The folders added before that can be read now; each of the others is skipped, with a warning."""
1159
+ folders = []
1160
+ for path in saved:
1161
+ folder = Path(path)
1162
+ if folder.is_dir() and os.access(folder, os.R_OK):
1163
+ folders.append(folder)
1164
+ else:
1165
+ print(f"Skipping {path}: the folder is missing or cannot be read. Its indexed images are kept.")
1166
+ return folders
1167
+
1168
+
1169
+ def _scan_and_report(root: Path) -> None:
1170
+ """Scan ``root`` and print what changed."""
1171
+ try:
1172
+ counts = scan(root)
1173
+ except RootOverlapError as exc:
1174
+ sys.exit(f"Error: {exc}")
1175
+
1176
+ if counts["delete_blocked"] and _ask_yes_no(
1177
+ f"{counts['delete_blocked']} indexed image(s) from this folder cannot be found any more, "
1178
+ "which is all or most of them (is a drive disconnected or a folder unmounted?). "
1179
+ "Remove them from the index? [y/N]: "
1180
+ ):
1181
+ counts = scan(root, allow_mass_delete=True)
1182
+
1183
+ skip_reasons = (("empty", counts["empty"]), ("not downloaded", counts["not_downloaded"]),
1184
+ ("unreadable", counts["unreadable"] + counts["bad_names"]))
1185
+ skipped = sum(number for _, number in skip_reasons)
1186
+ why = ", ".join(f"{number} {reason}" for reason, number in skip_reasons if number)
1187
+ states = ( # what the scan found, every state always shown: the files that are fine first, then what changed, then the problems
1188
+ ("Already indexed", counts["up_to_date"] + counts["moved"] + counts["details_updated"] + counts["renamed"]),
1189
+ ("To index", counts["queued_new"] + counts["queued_modified"]),
1190
+ ("Failed", counts["failed"]),
1191
+ ("Moved elsewhere", counts["moved_out"]),
1192
+ ("Deleted files", counts["deleted"]),
1193
+ ("Skipped", f"{skipped} ({why})" if why else skipped),
1194
+ ) # images kept after a declined mass deletion have no row: the note below explains them
1195
+ bold = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and "NO_COLOR" not in os.environ # as in Progress
1196
+ if bold:
1197
+ os.system("") # makes the Windows console understand ANSI escape codes
1198
+ print(f"\n\033[1m{root}\033[0m" if bold else f"\n{root}")
1199
+ for label, value in states:
1200
+ print(f" {label:<15} : {value}")
1201
+ if counts["delete_blocked"]:
1202
+ print(f"\nNote: {counts['delete_blocked']} image(s) are no longer in this folder. Their index was kept in case they come back.\n"
1203
+ f" Moved them? Scan their new folder ({config.ADD_COMMAND} \"folder path\"). They are recognised\n"
1204
+ f" and not analysed again, which can save hours.\n"
1205
+ f" Drive unplugged? Reconnect it and run {config.SCAN_COMMAND}.\n"
1206
+ f" Deleted them? Run {config.SCAN_COMMAND} and answer y to delete their index.")
1207
+
1208
+
1209
+ def _scan_folders(roots: list[Path]) -> None:
1210
+ """Scan each folder and print what changed in it, then offer to index what is pending."""
1211
+ bold = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and "NO_COLOR" not in os.environ # as in _scan_and_report
1212
+ title = "List of folders added for scan:"
1213
+ print(f"\n\033[1m{title}\033[0m" if bold else f"\n{title}")
1214
+ for root in roots:
1215
+ _scan_and_report(root)
1216
+ print()
1217
+
1218
+ backlog_size = _pending_count()
1219
+ if backlog_size == 0:
1220
+ _say_if_all_indexed()
1221
+ return
1222
+ if is_running("indexing"): # said now, not after the question: the lock is checked again when it is taken, in case one starts meanwhile
1223
+ print(f"{backlog_size} file(s) are pending indexing, but indexing is already running in another window. "
1224
+ f"Wait for it to finish, then run {config.SCAN_COMMAND} again.")
1225
+ return
1226
+ if _ask_yes_no(
1227
+ f"{backlog_size} file(s) in the backlog are pending indexing. "
1228
+ "Run indexing now? [y/N]: "
1229
+ ):
1230
+ _index_until_nothing_is_pending(lambda: _rescan(roots))
1231
+ else:
1232
+ print(f"\nSkipping indexing. Run {config.SCAN_COMMAND} later to process the backlog.")
1233
+
1234
+
1235
+ def _pending_count(root_ids: set[int] | None = None) -> int:
1236
+ """How many files wait to be indexed (only those of the folders ``root_ids`` when given)."""
1237
+ conn = init_db(str(config.DB_PATH))
1238
+ try:
1239
+ backlog = get_backlog(conn, config.BACKLOG_MAX_ATTEMPTS)
1240
+ failed = {row["file_path"] for row in get_exhausted_backlog(conn, config.BACKLOG_MAX_ATTEMPTS)}
1241
+ finally:
1242
+ conn.close()
1243
+ # a file left queued after its tries is failed, not pending
1244
+ return len([row for row in backlog if row["file_path"] not in failed and (root_ids is None or row["root_id"] in root_ids)])
1245
+
1246
+
1247
+ def _say_if_all_indexed() -> None:
1248
+ """Say that all images are indexed, unless some image could not be indexed (it is listed as failed, so the claim would be untrue)."""
1249
+ conn = init_db(str(config.DB_PATH))
1250
+ try:
1251
+ failed = get_exhausted_backlog(conn, config.BACKLOG_MAX_ATTEMPTS)
1252
+ finally:
1253
+ conn.close()
1254
+ if not failed:
1255
+ print(ALL_INDEXED)
1256
+
1257
+
1258
+ def _rescan(roots: list[Path]) -> None:
1259
+ for root in roots:
1260
+ _scan_and_report(root)
1261
+
1262
+
1263
+ def _run_again_or_exit() -> bool:
1264
+ """Ask in a menu whether to index the backlog again; True to run it (chosen, or nobody answered within ``config.RESCAN_WAIT_SECONDS``), False to exit.
1265
+
1266
+ Ctrl+C ends the program."""
1267
+ run_again, leave = "run again", "exit"
1268
+ question = questionary.select(
1269
+ f"Run the backlog again now, or exit? (it runs again by itself in {config.RESCAN_WAIT_SECONDS} seconds)",
1270
+ choices=[questionary.Choice("Run the backlog again", value=run_again), questionary.Choice("Exit", value=leave)],
1271
+ qmark="▌", pointer="»", instruction=" ", style=STYLE)
1272
+ app = question.application
1273
+
1274
+ def time_is_up() -> None: # runs in the timer's thread: the menu is closed from the thread that shows it
1275
+ loop = app.loop
1276
+ if loop is not None and app.is_running:
1277
+ loop.call_soon_threadsafe(lambda: app.exit(result=run_again) if app.is_running else None)
1278
+
1279
+ timer = threading.Timer(config.RESCAN_WAIT_SECONDS, time_is_up)
1280
+ timer.daemon = True
1281
+ timer.start()
1282
+ try:
1283
+ choice = question.ask()
1284
+ finally:
1285
+ timer.cancel()
1286
+ if choice is None: # Ctrl+C; questionary already said so
1287
+ sys.exit(1)
1288
+ return choice != leave
1289
+
1290
+
1291
+ def _index_until_nothing_is_pending(rescan, root_ids: set[int] | None = None) -> None:
1292
+ """Index the backlog (only the files of the folders ``root_ids`` when given), then ``rescan`` the folders: pictures that changed or were added
1293
+ meanwhile are indexed in another round, after a menu that waits ``config.RESCAN_WAIT_SECONDS`` for the user's choice. This repeats until
1294
+ nothing is pending or the user exits. With no terminal to answer in, there is one round."""
1295
+ run(root_ids)
1296
+ if questionary is None or not sys.stdin.isatty():
1297
+ return
1298
+ while True:
1299
+ print("\nScanning again to find what changed while indexing…")
1300
+ rescan()
1301
+ pending = _pending_count(root_ids)
1302
+ if pending == 0:
1303
+ _say_if_all_indexed()
1304
+ return
1305
+ print(f"\n{pending} file(s) are pending indexing again: they changed during the earlier scan, or failed for a reason that may pass.")
1306
+ if not _run_again_or_exit():
1307
+ print(f"\nExiting. Run {config.SCAN_COMMAND} later to process the backlog.")
1308
+ return
1309
+ print("\nRunning the scan and index again for the backlog images…")
1310
+ run(root_ids)
1311
+
1312
+
1313
+ # ---------------------------------------------------------------------------
1314
+ # Entry points
1315
+ # ---------------------------------------------------------------------------
1316
+
1317
+ def added_folders() -> list[str]:
1318
+ """The folders that were added, the most recently scanned first."""
1319
+ conn = init_db(str(config.DB_PATH))
1320
+ try:
1321
+ return [row["path"] for row in list_roots(conn)]
1322
+ finally:
1323
+ conn.close()
1324
+
1325
+
1326
+ def _ask_for_folder(added: list[str]) -> str:
1327
+ """The folder to add, asked for in a terminal with suggestions; ends the program if there is no terminal or nothing was entered."""
1328
+ if questionary is None or not sys.stdin.isatty(): # nobody to ask
1329
+ sys.exit(f'No folder was given. Run: {config.ADD_COMMAND} "folder path"')
1330
+ folder = ask_for_folder(added, STYLE)
1331
+ if folder is None: # Ctrl+C; already said so
1332
+ sys.exit(1)
1333
+ if not folder.strip():
1334
+ sys.exit("No folder entered.")
1335
+ return folder.strip()
1336
+
1337
+
1338
+ def main() -> None:
1339
+ """Scan every folder that was added, then offer to index what was found."""
1340
+ make_output_safe()
1341
+ saved = added_folders()
1342
+ if not saved:
1343
+ if questionary is None or not sys.stdin.isatty(): # nobody to ask
1344
+ sys.exit(f'No folders have been added yet. Run: {config.ADD_COMMAND} "folder path"')
1345
+ print()
1346
+ print("No folders have been added yet, so there is nothing to scan. Add one now and it is scanned and indexed.")
1347
+ add()
1348
+ return
1349
+ roots = _scannable(saved)
1350
+ if not roots:
1351
+ sys.exit("Error: none of the folders added before can be read.")
1352
+ _scan_folders(roots)
1353
+
1354
+
1355
+ def add_folder(folder: str | None = None) -> Path:
1356
+ """Add ``folder`` (asked for, with suggestions, when not given) to the folders that are scanned, without scanning it; returns the folder.
1357
+
1358
+ Ends the program with a message if the folder cannot be used or overlaps one added before."""
1359
+ if folder is None:
1360
+ folder = _ask_for_folder(added_folders())
1361
+ root = validate_folder(folder)
1362
+ conn = init_db(str(config.DB_PATH))
1363
+ try:
1364
+ _register_root(conn, root)
1365
+ except RootOverlapError as exc:
1366
+ sys.exit(f"Error: {exc}")
1367
+ finally:
1368
+ conn.close()
1369
+ return root
1370
+
1371
+
1372
+ def scan_and_index(root: Path) -> None:
1373
+ """Scan the added folder ``root``, print what changed in it, then index the pictures it has pending."""
1374
+ _scan_and_report(root)
1375
+ print()
1376
+ conn = init_db(str(config.DB_PATH))
1377
+ try:
1378
+ with conn:
1379
+ root_id = get_or_add_root(conn, str(root))
1380
+ finally:
1381
+ conn.close()
1382
+ _index_until_nothing_is_pending(lambda: _scan_and_report(root), {root_id})
1383
+
1384
+
1385
+ def add(folder: str | None = None) -> None:
1386
+ """Add ``folder`` (asked for, with suggestions, when not given) to the folders that are scanned, then offer what to do next (see after_add.py).
1387
+
1388
+ With no terminal to answer, nothing is offered: the folder is scanned and, as a script expects, the pictures found are indexed only if asked."""
1389
+ make_output_safe()
1390
+ if questionary is None or not sys.stdin.isatty():
1391
+ _scan_folders([validate_folder(_ask_for_folder([]) if folder is None else folder)])
1392
+ return
1393
+ from imagent.commands import after_add # after_add uses this module's functions
1394
+ after_add.run(add_folder(folder))