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,432 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/search.py — Imagent natural-language image search.
4
+
5
+ Given a natural language query, returns the three indexed images whose descriptions are
6
+ closest to it, best first.
7
+
8
+ Pipeline:
9
+ 1. Embed the query as typed.
10
+ 2. understand_query — an LLM drafts a hypothetical description of the image the query
11
+ asks for (HyDE), and that description is embedded too. If this fails, the search
12
+ continues with the query embedding alone.
13
+ 3. Cosine similarity of each embedding to every stored image embedding, read a batch at a
14
+ time (so memory does not grow with the number of images); an image's score is the mean of
15
+ the similarities it has.
16
+ 4. The top ``config.UNCERTAIN_TOP_K`` images by score whose file still exists are returned.
17
+ There is no cut-off: the closest images are returned however weak the match.
18
+
19
+ All activity reads from the user-level database (``config.DB_PATH``).
20
+
21
+ ``main`` is what ``imagent search`` runs. Given a query it answers it and ends. Without one it starts Ollama and loads
22
+ the models once, then keeps asking for queries until the user types ``exit`` (or presses Ctrl+C), so later searches start at once.
23
+
24
+ Each result shows its one-line summary, then its date, camera and size, then the full path of the file. With ``--full`` it shows
25
+ the full description instead of the summary, and ``--short`` the summary; with neither, what was chosen in settings (the summary until then). On a terminal, a line that is too long continues under its own indent.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ import shutil
32
+ import sys
33
+ import textwrap
34
+ import time
35
+ from datetime import datetime
36
+
37
+ import numpy as np
38
+ import questionary
39
+
40
+ from imagent import config
41
+ from imagent.db.connection import init_db
42
+ from imagent.db.operations import (
43
+ count_embeddings,
44
+ get_image_summary,
45
+ get_search_detail,
46
+ iter_embedding_batches,
47
+ )
48
+ from imagent.pipeline.console import file_link, make_output_safe
49
+ from imagent.pipeline.error_logger import log_error
50
+ from imagent.pipeline.locking import is_running
51
+ from imagent.pipeline.progress import SearchProgress, format_duration
52
+ from imagent.vlm.analyzer import embed_search_text, understand_query
53
+ from imagent.vlm.client import NotReady, check_ready, load_model, other_models_running, short_error
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # Ranking
58
+ # ---------------------------------------------------------------------------
59
+
60
+ def _unit(embedding: list[float]) -> np.ndarray:
61
+ """An embedding as a unit-length float32 vector: cosine similarity is then a plain dot product."""
62
+ vector = np.array(embedding, dtype=np.float32)
63
+ vector /= np.linalg.norm(vector) + 1e-10
64
+ return vector
65
+
66
+
67
+ def _best_matches(conn, dim: int, query_embeddings: list[list[float]], keep: int) -> tuple[list[int], np.ndarray, int]:
68
+ """The ``keep`` stored images closest to the queries: ``(file_ids, similarities, skipped)``, best first.
69
+
70
+ ``similarities`` has a row per image and a column per query (the cosine similarity of that query's embedding to the image's);
71
+ the closest is the one with the highest mean over the columns. The embeddings are read ``config.DB_BATCH_ROWS`` at a time and
72
+ only the best ``keep`` so far are held, so memory use is about ``DB_BATCH_ROWS * dim * 4`` bytes whatever the number of
73
+ images. Rows whose size is not ``dim`` floats are skipped and counted (a defensive check: the models are locked, so none
74
+ are expected).
75
+ """
76
+ queries = np.stack([_unit(embedding) for embedding in query_embeddings])
77
+ best_ids = np.empty(0, dtype=np.int64)
78
+ best_scores = np.empty((0, len(queries)), dtype=np.float32)
79
+ skipped = 0
80
+ for rows in iter_embedding_batches(conn, config.DB_BATCH_ROWS):
81
+ batch = np.empty((len(rows), dim), dtype=np.float32)
82
+ ids = []
83
+ for row in rows:
84
+ blob = row["embedding"]
85
+ if len(blob) != dim * 4:
86
+ skipped += 1
87
+ continue
88
+ batch[len(ids)] = np.frombuffer(blob, dtype="<f4") # stored little-endian on every platform
89
+ ids.append(row["file_id"])
90
+ if not ids:
91
+ continue
92
+ batch = batch[: len(ids)]
93
+ batch /= np.sqrt(np.einsum("ij,ij->i", batch, batch))[:, None] + 1e-10 # no full-size temporary, as np.linalg.norm would make
94
+ ids_all = np.concatenate([best_ids, np.array(ids, dtype=np.int64)])
95
+ scores_all = np.concatenate([best_scores, batch @ queries.T])
96
+ if len(ids_all) > keep:
97
+ closest = np.argpartition(-scores_all.mean(axis=1), keep - 1)[:keep]
98
+ ids_all, scores_all = ids_all[closest], scores_all[closest]
99
+ best_ids, best_scores = ids_all, scores_all
100
+ order = np.argsort(-best_scores.mean(axis=1), kind="stable")
101
+ return [int(file_id) for file_id in best_ids[order]], best_scores[order], skipped
102
+
103
+
104
+ # ---------------------------------------------------------------------------
105
+ # Public entrypoint
106
+ # ---------------------------------------------------------------------------
107
+
108
+ def _another_model_is_running(client, settings: dict, progress: SearchProgress) -> bool:
109
+ """True if Ollama is running a model the search does not use; the user is warned (and told if indexing is the cause) and the search should close."""
110
+ others = other_models_running(client, [settings["judge_model"], settings["embedding_model"]])
111
+ if not others:
112
+ return False
113
+ progress.fail()
114
+ progress.say(f"Ollama is running another model ({', '.join(others)}), so loading the search models now would throttle the device. "
115
+ + ("Indexing is running in the background; wait for it to finish, then search again."
116
+ if is_running("indexing") else "Close it or wait for it to finish, then search again."))
117
+ return True
118
+
119
+
120
+ def _offer_scan() -> None:
121
+ """With a terminal to answer in, offer to scan and index images now (or, when no folder has been added, to add one), or to exit; the search
122
+ itself ends either way."""
123
+ if not sys.stdin.isatty():
124
+ return
125
+ from imagent.commands import scan # after_add (which scan uses) imports this module
126
+ from imagent.commands.menu import ADD_FOLDER, STYLE, has_folders
127
+ title, command = ("Scan and index images", "scan") if has_folders() else ADD_FOLDER # with no folder there is nothing to scan: adding one scans and indexes it
128
+ choice = questionary.select("What would you like to do?", choices=[questionary.Separator(" "), questionary.Choice(title, value=command),
129
+ questionary.Choice("Exit", value="exit")], qmark="▌", pointer="»", instruction=" ", style=STYLE).ask()
130
+ if choice is None: # Ctrl+C; questionary already said so
131
+ sys.exit(1)
132
+ if choice == "scan":
133
+ scan.main()
134
+ elif choice == "add":
135
+ scan.add()
136
+
137
+
138
+ def start_session(exit_on_failure: bool = False) -> tuple | None:
139
+ """Start Ollama and load the judge and embedding models, shown as one step.
140
+
141
+ Returns the client and the locked model settings to pass to ``search``, or None
142
+ (after saying why) if the search cannot run. With ``exit_on_failure`` the program also ends with exit code 1 when the reason is a
143
+ failure (the models are not ready, or another one is running), not when there is simply nothing indexed to search.
144
+ """
145
+ make_output_safe()
146
+ conn = init_db(str(config.DB_PATH))
147
+ print() # a gap above the live line
148
+ progress = SearchProgress()
149
+ progress.step("Loading the model and starting the server")
150
+ try:
151
+ if count_embeddings(conn) == 0: # said before Ollama is started and the models are loaded: with nothing to search they are not needed
152
+ progress.fail()
153
+ progress.say("\nNo indexed images found.\n") # a blank line above and below
154
+ progress.close()
155
+ conn.close()
156
+ _offer_scan()
157
+ return None
158
+
159
+ try:
160
+ client, settings = check_ready(conn, ("judge", "embedding"))
161
+ except NotReady as exc:
162
+ progress.fail()
163
+ progress.say(str(exc))
164
+ if exit_on_failure:
165
+ sys.exit(1)
166
+ return None
167
+
168
+ if _another_model_is_running(client, settings, progress):
169
+ if exit_on_failure:
170
+ sys.exit(1)
171
+ return None
172
+ load_model(client, settings["judge_model"])
173
+ load_model(client, settings["embedding_model"], embedding=True)
174
+ return client, settings
175
+ finally:
176
+ progress.close()
177
+ conn.close()
178
+
179
+
180
+ def search(query: str, session: tuple | None = None) -> list[dict]:
181
+ """Return the ``config.UNCERTAIN_TOP_K`` images closest to ``query``, best first.
182
+
183
+ Identical copies of a picture (the same pixel hash) are one result, in the place of the closest copy, with the paths of the
184
+ others in ``other_paths``; so the results are different pictures.
185
+
186
+ Each result dict has: file_id, file_path, short_description, description, the file's properties
187
+ (width, height, file_size, mime_type, modified_at, root_path) and EXIF facts (taken_at, camera_make, camera_model,
188
+ gps_lat, gps_lon; None when absent), score (the mean of the similarities below), query_score (similarity to the
189
+ query as typed) and hyde_score (similarity to the HyDE description, None if that step failed).
190
+
191
+ ``session`` is what ``start_session`` returned; without it the session is started here.
192
+ """
193
+ make_output_safe()
194
+ if session is None:
195
+ session = start_session()
196
+ if session is None:
197
+ return []
198
+ client, settings = session
199
+ conn = init_db(str(config.DB_PATH))
200
+ progress = SearchProgress()
201
+ try:
202
+ judge_model, embedding_model = settings["judge_model"], settings["embedding_model"]
203
+ progress.step("Searching")
204
+ try:
205
+ query_embedding = embed_search_text(client, embedding_model, query)
206
+ except Exception as exc:
207
+ log_error(conn, stage="search", exc=exc, metadata={"query": query})
208
+ progress.fail()
209
+ progress.say(f"Could not reach the embedding model ({short_error(exc)}).")
210
+ return []
211
+ if len(query_embedding) != settings["embedding_dim"]:
212
+ progress.fail()
213
+ progress.say(f"The embedding model returned {len(query_embedding)} values, but "
214
+ f"{settings['embedding_dim']} were measured at setup. The model has changed.")
215
+ return []
216
+
217
+ hyde_embedding = None
218
+ progress.step("Analyzing")
219
+ try:
220
+ understanding = understand_query(client, judge_model, query)
221
+ embedded = embed_search_text(client, embedding_model, understanding.hypothetical_description)
222
+ if len(embedded) != settings["embedding_dim"]:
223
+ raise ValueError(f"the embedding model returned {len(embedded)} values, "
224
+ f"but {settings['embedding_dim']} were measured at setup")
225
+ hyde_embedding = embedded
226
+ except Exception as exc:
227
+ log_error(conn, stage="query_understanding", exc=exc, metadata={"query": query})
228
+ progress.fail("Could not analyze the query, so the search uses your words as typed.")
229
+ # Query understanding is an enhancement, not a hard dependency —
230
+ # fall back to the query embedding alone.
231
+
232
+ progress.step("Matching images")
233
+ queries = [query_embedding] if hyde_embedding is None else [query_embedding, hyde_embedding]
234
+ # Enough of the closest to still find UNCERTAIN_TOP_K whose file exists after skipping up to SEARCH_MAX_MISSING_SKIPPED that do not.
235
+ file_ids, similarities, skipped_dim = _best_matches(conn, settings["embedding_dim"], queries,
236
+ config.UNCERTAIN_TOP_K + config.SEARCH_MAX_MISSING_SKIPPED)
237
+ if skipped_dim:
238
+ progress.say(f"Skipped {skipped_dim} embedding(s) with an unexpected size.")
239
+ if not file_ids:
240
+ return []
241
+ scores = similarities.mean(axis=1)
242
+
243
+ results: list[dict] = []
244
+ by_picture: dict[str, dict] = {} # pixel hash -> its result: copies of a picture are one result, listing every path
245
+ missing = 0
246
+ for row, file_id in enumerate(file_ids):
247
+ if missing >= config.SEARCH_MAX_MISSING_SKIPPED:
248
+ break
249
+ summary = get_image_summary(conn, file_id)
250
+ if summary is None:
251
+ continue
252
+ if not os.path.exists(summary["file_path"]): # moved or deleted since the last scan, or on a drive that is not connected
253
+ missing += len(results) < config.UNCERTAIN_TOP_K # only one that is closer than the last result is worth a word
254
+ continue
255
+ shown = by_picture.get(summary["pixel_hash"]) if summary["pixel_hash"] else None
256
+ if shown is not None: # a copy of a picture already in the results: no place of its own
257
+ shown["other_paths"].append(summary["file_path"])
258
+ continue
259
+ if len(results) >= config.UNCERTAIN_TOP_K: # full: the rest are only looked at for copies of what is shown
260
+ continue
261
+ result = {
262
+ "file_id": file_id,
263
+ "file_path": summary["file_path"],
264
+ "short_description": summary["short_description"],
265
+ "description": summary["description"],
266
+ **{key: summary[key] for key in _DETAIL_COLUMNS},
267
+ "score": float(scores[row]),
268
+ "query_score": float(similarities[row, 0]),
269
+ "hyde_score": None if hyde_embedding is None else float(similarities[row, 1]),
270
+ "other_paths": [], # where identical copies of this picture are
271
+ }
272
+ results.append(result)
273
+ if summary["pixel_hash"]:
274
+ by_picture[summary["pixel_hash"]] = result
275
+ if missing:
276
+ progress.say(f"Skipped {missing} closer match(es) whose file is missing "
277
+ f"(is a drive disconnected?). Run {config.SCAN_COMMAND} to bring the index up to date.")
278
+ return results
279
+ finally:
280
+ progress.close()
281
+ conn.close()
282
+
283
+
284
+ _DETAIL_COLUMNS = ("width", "height", "file_size", "mime_type", "taken_at", "modified_at",
285
+ "camera_make", "camera_model", "gps_lat", "gps_lon", "root_path")
286
+
287
+
288
+ def _file_size(size: int) -> str:
289
+ amount = float(size)
290
+ for unit in ("B", "KB", "MB", "GB"):
291
+ if amount < 1024 or unit == "GB":
292
+ return f"{amount:.0f} {unit}" if unit == "B" else f"{amount:.1f} {unit}"
293
+ amount /= 1024
294
+
295
+
296
+ def _day(moment: datetime) -> str:
297
+ """A date as people say it, e.g. ``9 May, 2024`` (the day is not padded, which strftime cannot do on every system)."""
298
+ return f"{moment.day} {moment:%b}, {moment.year}"
299
+
300
+
301
+ def _when(result: dict) -> str | None:
302
+ """When the picture was taken (its EXIF time), or else when the file was last changed."""
303
+ if result["taken_at"]:
304
+ try:
305
+ taken = datetime.fromisoformat(result["taken_at"])
306
+ return f"{taken:%I:%M %p} {_day(taken)}"
307
+ except ValueError:
308
+ return result["taken_at"]
309
+ if result["modified_at"]:
310
+ try:
311
+ return f"modified {_day(datetime.fromisoformat(result['modified_at'][:10]))}"
312
+ except ValueError:
313
+ return f"modified {result['modified_at'][:10]}"
314
+ return None
315
+
316
+
317
+ def _facts(result: dict) -> str:
318
+ """The date, camera, size in pixels and size on disk of an image on one line, leaving out what is not known."""
319
+ make, model = result["camera_make"], result["camera_model"]
320
+ if make and model and model.lower().startswith(make.lower()): # many cameras already put the make in the model ("iQOO", "iQOO Neo9 Pro")
321
+ make = None
322
+ camera = " ".join(part for part in (make, model) if part)
323
+ pixels = f"{result['width']}\u00d7{result['height']}" if result["width"] and result["height"] else None
324
+ size = _file_size(result["file_size"]) if result["file_size"] is not None else None
325
+ return " \u00b7 ".join(part for part in (_when(result), camera, pixels, size) if part)
326
+
327
+
328
+ def _indented(text: str, break_long_words: bool = False) -> str:
329
+ """``text`` under the file name (three spaces in). On a terminal a line that is too long continues with the same indent,
330
+ instead of starting again at the left edge; piped output is not wrapped. A word longer than the line (a path) is
331
+ only cut when ``break_long_words``."""
332
+ lines = text.splitlines()
333
+ if not sys.stdout.isatty():
334
+ return "\n".join(f" {line}".rstrip() for line in lines)
335
+ width = max(shutil.get_terminal_size().columns - 1, 20) # the last column is left empty so a line never wraps by itself
336
+ return "\n".join(textwrap.fill(line, width, initial_indent=" ", subsequent_indent=" ", break_long_words=break_long_words,
337
+ break_on_hyphens=False) if line.strip() else "" for line in lines)
338
+
339
+
340
+ def _description(result: dict, full: bool) -> str:
341
+ """The one-line summary, or with ``full`` the whole description; empty when there is none."""
342
+ return _indented((result["description"] if full else result["short_description"]) or "")
343
+
344
+
345
+ QUERY_SHOWN_CHARS = 120 # a longer query is cut in the heading of its results (it is searched in full)
346
+
347
+
348
+ def _shortened(query: str) -> str:
349
+ """``query`` as it is named in the heading of the results: cut, with … , when it is very long."""
350
+ return query if len(query) <= QUERY_SHOWN_CHARS else query[:QUERY_SHOWN_CHARS].rstrip() + "…"
351
+
352
+
353
+ def _show(query: str, results: list[dict], full: bool = False, seconds: float | None = None) -> None:
354
+ """Print the results; ``seconds`` is how long the search took, shown in the heading when given."""
355
+ took = f" in {format_duration(seconds, decimals=1)}" if seconds is not None else ""
356
+ if not results:
357
+ print(f"\nNo results for: {_shortened(query)!r}{took}\n")
358
+ return
359
+
360
+ bold = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and "NO_COLOR" not in os.environ
361
+ shown = _shortened(query)
362
+ print(f"\nTop {len(results)} result(s) for: " + (f"\033[1m{shown!r}\033[0m" if bold else f"{shown!r}") + f"{took}\n")
363
+ for position, result in enumerate(results, start=1):
364
+ name = file_link(os.path.basename(result["file_path"]), result["file_path"])
365
+ name = f"\033[1m{name}\033[0m" if bold else name
366
+ copies = [_indented(f"Same picture also at: {path}", break_long_words=True) for path in result.get("other_paths", ())]
367
+ lines = [f"{position}. {name}", _description(result, full), _indented(_facts(result)),
368
+ _indented(result["file_path"], break_long_words=True), *copies]
369
+ print("\n\n".join(line for line in lines if line)) # a blank line between the lines of a result, two between results
370
+ print("\n")
371
+
372
+
373
+ def _answer(query: str, session: tuple, full: bool) -> None:
374
+ started = time.monotonic()
375
+ results = search(query, session)
376
+ _show(query, results, full, time.monotonic() - started)
377
+
378
+
379
+ def _saved_detail_is_full() -> bool:
380
+ """True when settings (or, before any choice, ``config.SEARCH_DETAIL_DEFAULT``) say a search shows the full description."""
381
+ conn = init_db(str(config.DB_PATH))
382
+ try:
383
+ return (get_search_detail(conn) or config.SEARCH_DETAIL_DEFAULT) == "full"
384
+ finally:
385
+ conn.close()
386
+
387
+
388
+ DETAIL_HINT = "Tip: add --full or --short to change how much each result shows. You can also change it in Settings."
389
+
390
+
391
+ def _show_detail_hint() -> None:
392
+ """The first thing a search says, in grey, on a terminal only (it is not part of the results): how to change what each result shows."""
393
+ if not sys.stdout.isatty():
394
+ return
395
+ grey = os.environ.get("TERM") != "dumb" and "NO_COLOR" not in os.environ
396
+ print("\n" + (f"\033[38;5;244m{DETAIL_HINT}\033[0m" if grey else DETAIL_HINT)) # a gap above, so it never touches the command typed
397
+
398
+
399
+ def main(query: str = "", full: bool | None = None) -> None:
400
+ """Answer ``query`` and end; with no query, keep asking for queries until the user types ``exit``.
401
+
402
+ ``full`` True shows every result's full description, False its summary; None (the default) uses what was chosen in settings. A flag
403
+ given on the command line always wins over the setting."""
404
+ make_output_safe()
405
+ _show_detail_hint()
406
+ if full is None:
407
+ full = _saved_detail_is_full()
408
+ query = query.strip()
409
+ session = start_session(exit_on_failure=True)
410
+ if session is None:
411
+ return
412
+ if query:
413
+ _answer(query, session, full)
414
+ return
415
+ colour = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and "NO_COLOR" not in os.environ
416
+ title = "▌Enter your search query (type exit to quit):"
417
+ title = f"\033[1m{title}\033[0m" if colour else title
418
+ above = "" # the live line that loaded the models left the gap above the first step
419
+ while True:
420
+ print(f"{above}{title}\n") # a step: a gap above and below it
421
+ above = "\n"
422
+ try:
423
+ query = input().strip()
424
+ except EOFError: # Ctrl+D, or no terminal to type in
425
+ return
426
+ if query.lower() in ("exit", "quit"):
427
+ return
428
+ if not query:
429
+ print('Type what you are looking for, for example: red car at night')
430
+ continue
431
+ print() # a gap between the query and the step shown while it is answered
432
+ _answer(query, session, full)
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/settings.py — Imagent: the settings menu, run by ``imagent settings`` and offered by the main menu.
4
+
5
+ Every setting is picked from a list of values; nothing is typed. The settings are kept in the database (``index_preferences``) and a
6
+ setting never chosen uses its default from ``config.py``:
7
+ - how many deleted pictures Imagent remembers (asked at the end of setup too). Choosing fewer than are remembered now forgets the
8
+ oldest ones, so it asks first;
9
+ - whether a search shows the one-line summary or the full description of each picture (``imagent search --full`` / ``--short`` change it
10
+ for one search).
11
+ "Uninstall Imagent" is here too. It is offered even when the database cannot be read, as the damage may be why the user is uninstalling.
12
+ The models and the measurements of this computer are not settings: they are locked at setup.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+
19
+ import questionary
20
+
21
+ from imagent import config
22
+ from imagent.commands.menu import STYLE
23
+ from imagent.commands.setup import KEEP_DELETED_CHOICES, KEEP_DELETED_DEFAULT, keep_deleted_label
24
+ from imagent.db.connection import init_db
25
+ from imagent.db.operations import count_deleted_analyses, get_keep_deleted, get_search_detail, set_keep_deleted, set_search_detail
26
+ from imagent.pipeline.console import make_output_safe, run_cli
27
+
28
+ CANCELLED = "Settings closed."
29
+ KEEP_DELETED = "keep_deleted"
30
+ SEARCH_DETAIL = "search_detail"
31
+ UNINSTALL = "uninstall"
32
+ EXIT = "exit"
33
+
34
+ NOTE_STYLE = questionary.Style([*STYLE.style_rules, ("separator", "fg:#808080")]) # a fixed mid grey, as the terminal's "bright black" can look like normal text
35
+ SEARCH_DETAIL_SHOWS = {"short": "the one-line summary", "full": "the whole description"}
36
+
37
+
38
+ def read_settings() -> dict | None:
39
+ """The settings as they are now (the defaults where none was chosen) and how many deleted pictures are remembered, or None if the
40
+ database cannot be read."""
41
+ try:
42
+ conn = init_db(str(config.DB_PATH))
43
+ try:
44
+ return {KEEP_DELETED: get_keep_deleted(conn), # None: not chosen yet, nothing is remembered
45
+ SEARCH_DETAIL: get_search_detail(conn) or config.SEARCH_DETAIL_DEFAULT,
46
+ "remembered": count_deleted_analyses(conn)}
47
+ finally:
48
+ conn.close()
49
+ except Exception:
50
+ return None
51
+
52
+
53
+ def choices(values: dict | None) -> list:
54
+ """The entries of the settings menu. With no readable database only Exit and Uninstall are offered."""
55
+ rows = []
56
+ if values is not None:
57
+ keep = values[KEEP_DELETED]
58
+ rows = [(f"Deleted pictures Imagent remembers: {'not chosen yet (none)' if keep is None else keep}", KEEP_DELETED),
59
+ (f"Search result detail: {values[SEARCH_DETAIL].capitalize()} ({SEARCH_DETAIL_SHOWS[values[SEARCH_DETAIL]]})", SEARCH_DETAIL)]
60
+ return [questionary.Choice(title, value=value) for title, value in rows + [("Exit", EXIT)]] + [
61
+ questionary.Choice([("fg:ansired", "Uninstall Imagent")], value=UNINSTALL)]
62
+
63
+
64
+ def _select(question: str, entries: list, default=None, note: str | None = None):
65
+ """The value of the entry picked from ``entries``; Ctrl+C ends the program. ``note`` is a small grey description under the question, one line per ``\n``."""
66
+ questionary.print("") # a gap above every question, so it never touches the command typed or the line before it
67
+ top = [questionary.Separator(line) for line in note.split("\n")] if note else [] # separators are skipped by the arrow keys
68
+ prompt = questionary.select(question, choices=[*top, questionary.Separator(" ")] + entries, default=default, qmark="▌", pointer="»",
69
+ instruction=" ", style=NOTE_STYLE)
70
+ # questionary also marks the default as "selected", which it colours. Keep only the pointer on it, as in the main menu.
71
+ control = next(w.content for w in prompt.application.layout.find_all_windows() if hasattr(w.content, "selected_options"))
72
+ control.selected_options.clear()
73
+ answer = prompt.ask()
74
+ if answer is None: # Ctrl+C; questionary already said so
75
+ sys.exit(1)
76
+ return answer
77
+
78
+
79
+ def _save(setter, value) -> None:
80
+ conn = init_db(str(config.DB_PATH))
81
+ try:
82
+ with conn:
83
+ setter(conn, value)
84
+ finally:
85
+ conn.close()
86
+
87
+
88
+ def _done(text: str) -> None:
89
+ questionary.print(f"\n✓ {text}", style="fg:green")
90
+
91
+
92
+ def change_keep_deleted(values: dict) -> None:
93
+ current = values[KEEP_DELETED]
94
+ numbers = sorted({*KEEP_DELETED_CHOICES, *([] if current is None else [current])}) # a number chosen before stays in the list
95
+ new = _select("How many deleted pictures should Imagent remember?",
96
+ [questionary.Choice(keep_deleted_label(number), value=number) for number in numbers] + [questionary.Choice("Exit", value=EXIT)],
97
+ default=KEEP_DELETED_DEFAULT if current is None else current, note="After you delete a picture, Imagent can remember what it learned about it.\nIf the picture comes back, it does not need to be analysed again.\nOnce the limit is reached, the oldest are forgotten first.")
98
+ if new == EXIT: # nothing is changed (setup asks the same question without this entry)
99
+ return
100
+ forgotten = max(values["remembered"] - new, 0)
101
+ if forgotten:
102
+ keep = _select(f"Imagent remembers {values['remembered']} deleted pictures. Forget the {forgotten} oldest?",
103
+ [questionary.Choice("No, leave it as it is", value=False), questionary.Choice(f"Yes, forget {forgotten}", value=True)])
104
+ if not keep:
105
+ return
106
+ _save(set_keep_deleted, new)
107
+ _done(f"Imagent will remember the last {new} deleted pictures." if new else "Imagent will not remember deleted pictures.")
108
+
109
+
110
+ def change_search_detail(values: dict) -> None:
111
+ new = _select("What should a search show for each picture?",
112
+ [questionary.Choice(f"{detail.capitalize()}: {SEARCH_DETAIL_SHOWS[detail]}", value=detail) for detail in config.SEARCH_DETAILS]
113
+ + [questionary.Choice("Exit", value=EXIT)], default=values[SEARCH_DETAIL])
114
+ if new == EXIT: # nothing is changed
115
+ return
116
+ _save(set_search_detail, new)
117
+ _done(f"A search shows {SEARCH_DETAIL_SHOWS[new]} of each picture.")
118
+
119
+
120
+ CHANGES = {KEEP_DELETED: change_keep_deleted, SEARCH_DETAIL: change_search_detail}
121
+
122
+
123
+ def main() -> None:
124
+ make_output_safe()
125
+ if not sys.stdin.isatty():
126
+ sys.exit("Settings need an interactive terminal. Run: imagent settings")
127
+ chosen = None
128
+ while True:
129
+ values = read_settings()
130
+ if values is None:
131
+ questionary.print("Imagent's database cannot be read, so no setting can be shown or changed.")
132
+ chosen = _select("Settings", choices(values), default=chosen if values is not None else None)
133
+ if chosen == EXIT:
134
+ return
135
+ if chosen == UNINSTALL:
136
+ from imagent.commands import uninstall
137
+ run_cli(uninstall.main, cancelled=uninstall.CANCELLED)
138
+ return # uninstalled, or it said why not: either way there is nothing more to set
139
+ CHANGES[chosen](values)