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,1409 @@
1
+ """
2
+ imagent/commands/setup.py — First-run setup (``imagent setup``): show system details, load the text-reading engine, check
3
+ Ollama, collect and verify the model names, save a fixed copy of each model, then lock them in the Imagent database.
4
+ Ollama is only fixed after you agree. The models cannot be changed afterwards; running this again only shows their status and
5
+ reinstalls a missing one. Starts Ollama only temporarily, to download the models.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import errno
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import platform
15
+ import re
16
+ import shutil
17
+ import sqlite3
18
+ import subprocess
19
+ import sys
20
+ import tarfile
21
+ import time
22
+ import urllib.error
23
+ import urllib.request
24
+ import zipfile
25
+ from contextlib import contextmanager
26
+ from pathlib import Path
27
+
28
+ import questionary
29
+
30
+ from imagent import config as app_config
31
+ from imagent.db.connection import init_db
32
+ from imagent.db.operations import (get_device_settings, get_keep_deleted, get_model_settings, set_device_settings, set_keep_deleted,
33
+ set_model_settings)
34
+ from imagent.pipeline.console import make_output_safe
35
+ from imagent.pipeline.progress import SearchProgress
36
+
37
+ DEFAULT_HOST = "http://localhost:11434"
38
+ CANCELLED = "Setup cancelled. Run it again any time."
39
+ MODEL_NAME_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/-]*(:[A-Za-z0-9._-]+)?$")
40
+ REGISTRY = "https://registry.ollama.ai/v2"
41
+ MANIFEST_ACCEPT = "application/vnd.docker.distribution.manifest.v2+json"
42
+ KEEP_DELETED_CHOICES = (0, 100, 500, 1000, 2000, 5000) # how many deleted pictures to remember (0: none), offered at the end of setup and in settings
43
+ KEEP_DELETED_DEFAULT = 500
44
+ RED = "fg:ansibrightred"
45
+ INDENT = " " # left padding for everything under a step heading
46
+ QMARK = INDENT + "?"
47
+ POINTER = INDENT + "»"
48
+
49
+ ASK_AI = "Not sure? Ask AI. Copy the prompt and give it to your favorite LLM."
50
+ COPIED = "✓ Prompt copied to clipboard. Paste it into your favorite LLM. (Select again to copy once more)"
51
+ PASTE_SET = "Paste the AI's answer: one set of three models (vision, text, embedding)."
52
+
53
+ STYLE = questionary.Style([
54
+ ("qmark", "fg:ansidefault bold"),
55
+ ("question", "fg:ansidefault bold"),
56
+ ("pointer", "fg:ansidefault bold"),
57
+ ("highlighted", "fg:ansidefault bold underline"),
58
+ ("selected", "noreverse fg:ansidefault bold underline"),
59
+ ("answer", "fg:ansidefault bold"),
60
+ ("instruction", "fg:ansibrightblack"),
61
+ ("disabled", "fg:ansibrightblack italic"),
62
+ ])
63
+
64
+
65
+ # --- Output helpers -----------------------------------------------------------
66
+
67
+ def say(message: str = "", style: str = "") -> None:
68
+ message = "\n".join(INDENT + line if line else line for line in message.split("\n"))
69
+ questionary.print(message, style=style)
70
+
71
+
72
+ def step(title: str) -> None:
73
+ os.system("") # enables ANSI colours in terminals
74
+ print(f"\n\033[1m▌{title}\033[0m\n")
75
+
76
+
77
+ def clear_screen() -> None:
78
+ os.system("") # enables ANSI escape codes in the Windows console
79
+ print("\033[2J\033[H", end="", flush=True) # erase the screen and move the cursor to the top
80
+
81
+
82
+ def fail(message: str) -> None:
83
+ sys.exit(f"\n{INDENT}✗ {message}")
84
+
85
+
86
+ def ask(question):
87
+ answer = question.ask()
88
+ if answer is None:
89
+ sys.exit("\nSetup cancelled. Run it again any time.")
90
+ return answer
91
+
92
+
93
+ # --- System details -----------------------------------------------------------
94
+
95
+ def _run(cmd: list[str]) -> str:
96
+ try:
97
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=15).stdout.strip()
98
+ except (OSError, subprocess.SubprocessError):
99
+ return ""
100
+
101
+
102
+ def _ram_gb() -> str:
103
+ system = platform.system()
104
+ try:
105
+ if system == "Darwin":
106
+ return f"{int(_run(['sysctl', '-n', 'hw.memsize'])) / 2**30:.0f} GB"
107
+ if system == "Linux":
108
+ for line in Path("/proc/meminfo").read_text().splitlines():
109
+ if line.startswith("MemTotal:"):
110
+ return f"{int(line.split()[1]) / 2**20:.0f} GB"
111
+ if system == "Windows":
112
+ out = _run(["powershell", "-NoProfile", "-Command",
113
+ "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory"])
114
+ return f"{int(out) / 2**30:.0f} GB"
115
+ except (ValueError, OSError):
116
+ pass
117
+ return "unknown"
118
+
119
+
120
+ def _cpu() -> str:
121
+ system = platform.system()
122
+ if system == "Darwin":
123
+ return _run(["sysctl", "-n", "machdep.cpu.brand_string"]) or platform.processor()
124
+ if system == "Linux":
125
+ try:
126
+ for line in Path("/proc/cpuinfo").read_text().splitlines():
127
+ if line.startswith("model name"):
128
+ return line.split(":", 1)[1].strip()
129
+ except OSError:
130
+ pass
131
+ if system == "Windows":
132
+ out = _run(["powershell", "-NoProfile", "-Command",
133
+ "(Get-CimInstance Win32_Processor).Name"])
134
+ if out:
135
+ return out
136
+ return platform.processor() or platform.machine()
137
+
138
+
139
+ def _gpu() -> str:
140
+ if shutil.which("nvidia-smi"):
141
+ out = _run(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader"])
142
+ if out:
143
+ return out.replace("\n", "; ")
144
+ system = platform.system()
145
+ if system == "Darwin":
146
+ out = _run(["system_profiler", "SPDisplaysDataType"])
147
+ names = [l.split(":", 1)[1].strip() for l in out.splitlines() if "Chipset Model" in l]
148
+ if names:
149
+ return f"{', '.join(names)} (unified memory shared with RAM)"
150
+ if system == "Windows":
151
+ out = _run(["powershell", "-NoProfile", "-Command",
152
+ "(Get-CimInstance Win32_VideoController).Name"])
153
+ if out:
154
+ return out.replace("\n", "; ")
155
+ if system == "Linux" and shutil.which("lspci"):
156
+ lines = [l for l in _run(["lspci"]).splitlines() if "VGA" in l or "3D" in l]
157
+ if lines:
158
+ return "; ".join(l.split(": ", 1)[-1] for l in lines)
159
+ return "none detected"
160
+
161
+
162
+ def _metal_gpu_memory_gb():
163
+ """Memory the macOS GPU may use in GB, as Metal reports it (recommendedMaxWorkingSetSize); None if Metal cannot be asked."""
164
+ if platform.system() != "Darwin":
165
+ return None
166
+ try:
167
+ import ctypes
168
+ import ctypes.util
169
+ metal = ctypes.CDLL("/System/Library/Frameworks/Metal.framework/Metal")
170
+ objc = ctypes.CDLL(ctypes.util.find_library("objc"))
171
+ metal.MTLCreateSystemDefaultDevice.restype = ctypes.c_void_p
172
+ objc.sel_registerName.restype = ctypes.c_void_p
173
+ objc.sel_registerName.argtypes = [ctypes.c_char_p]
174
+ objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
175
+ objc.objc_msgSend.restype = ctypes.c_uint64
176
+ device = metal.MTLCreateSystemDefaultDevice()
177
+ if not device:
178
+ return None
179
+ size = objc.objc_msgSend(device, objc.sel_registerName(b"recommendedMaxWorkingSetSize"))
180
+ return size / 2**30 if size else None
181
+ except (OSError, AttributeError, TypeError):
182
+ return None
183
+
184
+
185
+ def system_details() -> str:
186
+ free_disk = shutil.disk_usage(Path.home()).free / 2**30
187
+ lines = [
188
+ f"- OS: {platform.system()} {platform.release()} ({platform.machine()})",
189
+ f"- CPU: {_cpu()}",
190
+ f"- RAM: {_ram_gb()}",
191
+ f"- GPU: {_gpu()}",
192
+ ]
193
+ metal_gb = _metal_gpu_memory_gb()
194
+ if metal_gb is not None:
195
+ lines.append(f"- GPU memory usable (reported by Metal for this computer): {metal_gb:.1f} GB")
196
+ lines.append(f"- Free disk space: {free_disk:.0f} GB")
197
+ return "\n".join(lines)
198
+
199
+
200
+ # --- AI prompt ----------------------------------------------------------------
201
+
202
+ def failed_models_section(failed: dict | None) -> str:
203
+ """The part of the AI prompt about models that were downloaded and tried on this computer and did not work: each with the reason."""
204
+ if not failed:
205
+ return ""
206
+ lines = "\n".join(f"- {name} {' '.join(reason.split())}" for name, reason in failed.items())
207
+ return f"""
208
+ ## Models that already failed on this computer
209
+ They were downloaded and tried here. Do not suggest any of them, and do not suggest a larger model of the same family: choose smaller ones, or another family. A model may have failed for lack of memory, for being too slow, or because it could not answer in the required JSON form.
210
+ {lines}
211
+ """
212
+
213
+
214
+ def build_ai_prompt(failed: dict | None = None) -> str:
215
+ """The prompt to paste into an AI chat. ``failed`` maps each model that was tried on this computer and did not work to the reason."""
216
+ return f"""I need to choose AI models for a local image search tool that runs on my computer through Ollama. Choose the smallest and fastest models that are accurate enough for the tasks below, not the largest that fit: more memory is a limit, never a goal, and a computer with a lot of memory does not need big models for these tasks.
217
+
218
+ ## My computer
219
+ {system_details()}
220
+ {failed_models_section(failed)}
221
+ ## The three models
222
+ - Vision model: looks at each image once and writes a JSON description (scene, objects, people, colors and mood, tags). A separate OCR step reads text in images. The descriptions must be accurate, and I may index thousands of images, so speed matters too.
223
+ - Text model: fixes typos in my search query and writes a short description of the image I am looking for. It never sees images. One request per search. This is an easy task that a small model does well, and it can be the vision model itself.
224
+ - Embedding model: turns the stored descriptions (about 500 tokens each) and my search queries (possibly in several languages) into vectors. Used when indexing and when searching.
225
+
226
+ ## Rules
227
+ 1. Search the web now. Do not rely on your memory.
228
+ 2. Only models from https://ollama.com/library, each with an exact tag that you confirmed on its page so that `ollama pull <name>:<tag>` works. Never guess or invent a tag.
229
+ 3. Capabilities: the vision model needs "vision", the text model needs "completion", the embedding model needs "embedding" (context of at least 1024 tokens, strong multilingual retrieval). The vision and text models must follow a JSON schema reliably and must not be thinking-only (reasoning) models. By default the text model is the same model as the vision model: one download fewer, and it is already loaded after indexing. Give a separate text model only when it is clearly faster for a search (about twice as fast) and just as good at fixing typos and at not inventing details I did not ask for; do not give a larger text model than the vision model.
230
+ 4. Quantization of 4-bit or better, never lower.
231
+ 5. Speed: a vision reply within a few seconds per image (never more than about 30 seconds) and a text reply within about 10 seconds. Indexing thousands of images must take hours, not days, on my computer. If two models are within about 30% of each other in speed, choose the more accurate one. Choose the faster one only when it is clearly faster (about twice as fast) and only slightly less accurate. Judge by published benchmarks and the model's own page, not by size, popularity or release date; an older maintained model is fine if the balance is better.
232
+ Enough is enough: a bigger model is worth choosing only when it is clearly more accurate at these tasks (describing images in the JSON format above, and fixing typos in short queries), not merely higher on general benchmarks. When a smaller model of the same family is within a few percent on the tasks, choose the smaller one. Do not choose a model because it is the largest that fits.
233
+ 6. Memory: this is only an upper limit, not a target; a set that uses much less memory is better, not worse. Model weights are fully loaded (no memory-mapping). Every set must fit entirely on the GPU, with no CPU offload and no swapping, in about 85% of my VRAM (or RAM if there is no dedicated GPU). With shared (unified) memory the GPU cannot use all of the RAM: if "GPU memory usable" is listed above, it is the figure to use, so take 85% of that and do not look it up. Check both cases; the vision and text models are never loaded together:
234
+ - indexing: the vision model AND the embedding model are loaded at the same time, so both must fit together. Count the vision model's weights, its KV cache at a context of {app_config.OLLAMA_NUM_CTX} tokens and its image-encoder working memory for images up to {app_config.IMAGE_MAX_LONG_EDGE} px on the long edge (reserved for a worst-case image), plus the embedding model's weights and its own KV cache and compute buffers at the context Ollama gives it by default; those buffers can make an embedding model several times larger in memory than its weight file. Ollama does not publish buffer sizes, so estimate them and leave a safety margin instead of declining a set for lack of an exact figure;
235
+ - searching: the text model AND the embedding model are loaded at the same time. Count the text model's weights and its KV cache at a context of {app_config.OLLAMA_NUM_CTX} tokens, plus the embedding model in memory as above.
236
+ 7. Do the memory sums yourself and do not show the working.
237
+
238
+ ## Answer
239
+ Give three sets. A set is one complete choice: a vision model, a text model and an embedding model that work together. Set 1 is the smallest set that is accurate enough and the one you recommend; set 2 is a faster or lighter alternative; set 3 is a more accurate one that still fits, and the table must show how much accuracy it adds, so that I can judge whether it is worth the extra size and time. Only give a set if you verified the tag and capabilities of all three of its models (memory is estimated, rule 6); if there are fewer than three, give fewer and say so.
240
+
241
+ Reply with exactly these three parts, in this order, and nothing else:
242
+ 1. A table with one row per set and the columns: Set, Vision model, Text model, Embedding model, Memory (indexing / searching), Speed, Accuracy (the scores you used).
243
+ 2. One or two sentences per set on the trade-offs against the other two sets: what I gain and what I give up.
244
+ 3. The heading "Copy one set", then one code block per set (plain, no language name). Each code block holds one line and nothing else: the three model names, in the order vision, text, embedding, separated by commas.
245
+ - Exact shape: visionname:7b,textname:8b,embeddingname:335m (when the text model is the vision model, write its name twice: visionname:7b,visionname:7b,embeddingname:335m)
246
+ - Forbidden in that line: spaces, labels, numbering, bullets, quotes, brackets, JSON and line breaks.
247
+ - Before you reply, check that every such line has exactly two commas and three `name:tag` values.
248
+ """
249
+
250
+
251
+ def copy_to_clipboard(text: str) -> bool:
252
+ system = platform.system()
253
+ if system == "Darwin":
254
+ candidates = [["pbcopy"]]
255
+ elif system == "Windows":
256
+ candidates = [["powershell", "-NoProfile", "-Command", "Set-Clipboard -Value ([Console]::In.ReadToEnd())"]]
257
+ else:
258
+ candidates = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]]
259
+ for cmd in candidates:
260
+ if shutil.which(cmd[0]):
261
+ try:
262
+ subprocess.run(cmd, input=text, text=True, encoding="utf-8", check=True, timeout=10)
263
+ return True
264
+ except (OSError, subprocess.SubprocessError):
265
+ continue
266
+ return False
267
+
268
+
269
+ def offer_prompt_copy(failed: dict | None = None) -> bool:
270
+ """Copy the AI prompt to the clipboard. If that fails, print it for manual copying."""
271
+ prompt = build_ai_prompt(failed)
272
+ if copy_to_clipboard(prompt):
273
+ return True
274
+ say("Could not reach your clipboard. Select and copy the text below by hand,", "fg:ansimagenta")
275
+ say("then paste it into any AI chat:\n", "fg:ansimagenta")
276
+ print(prompt)
277
+ return False
278
+
279
+
280
+ # --- Helpers ------------------------------------------------------------------
281
+
282
+ def prepare_ocr() -> None:
283
+ """Load the OCR engine now. Its models come with the package, so nothing is downloaded, and Imagent never needs the internet once set up."""
284
+ say("Loading the text-reading (OCR) engine…")
285
+ try:
286
+ from imagent.image_processing.ocr import check_available
287
+ check_available()
288
+ except Exception as exc:
289
+ fail(f"The text-reading (OCR) engine could not be loaded ({type(exc).__name__}: {exc}). "
290
+ f"Run {app_config.SETUP_COMMAND} again; if it keeps failing, reinstall Imagent (pipx reinstall imagent).")
291
+ say("✓ Text reading is ready.", "fg:green")
292
+
293
+
294
+ # --- Step 2: Ollama -----------------------------------------------------------
295
+
296
+ class OllamaInstallError(Exception):
297
+ """Installing Ollama failed; the message says why."""
298
+
299
+
300
+ OLLAMA_DESCRIPTION = "Runs the AI models on your computer. Imagent installed its own copy, which only Imagent uses."
301
+
302
+
303
+ def _ollama_command_version(command: str = "ollama"):
304
+ """Version of the `ollama` program at ``command`` as numbers, e.g. (0, 6, 4); None if it cannot be told."""
305
+ try:
306
+ out = subprocess.run([command, "--version"], capture_output=True, text=True, timeout=15)
307
+ except (OSError, subprocess.SubprocessError):
308
+ return None
309
+ text = out.stdout + out.stderr
310
+ match = re.search(r"client version is (\d+)\.(\d+)\.(\d+)", text) or re.search(r"version is (\d+)\.(\d+)\.(\d+)", text)
311
+ version = tuple(int(part) for part in match.groups()) if match else None
312
+ return version if version and any(version) else None # a development build reports 0.0.0
313
+
314
+
315
+ def _remove(path: Path) -> None:
316
+ """Delete a file or folder if it exists."""
317
+ if path.is_dir() and not path.is_symlink():
318
+ shutil.rmtree(path, ignore_errors=True)
319
+ else:
320
+ path.unlink(missing_ok=True)
321
+
322
+
323
+ def _download_file(url: str, target: Path) -> str:
324
+ """Download ``url`` into ``target``, showing a spinner and the progress. Returns the SHA-256 of what arrived."""
325
+ digest = hashlib.sha256()
326
+ request = urllib.request.Request(url, headers={"User-Agent": "imagent"})
327
+ loader = SearchProgress() # keeps spinning while the server is slow to answer
328
+ loader.step(f"{INDENT}Downloading Ollama")
329
+ try:
330
+ with urllib.request.urlopen(request, timeout=60) as response, open(target, "wb") as out:
331
+ total = int(response.headers.get("Content-Length") or 0)
332
+ free = shutil.disk_usage(target.parent).free
333
+ if total and free < total:
334
+ raise OllamaInstallError(f"There is not enough free disk space: the download is {_fmt_bytes(total)} and {_fmt_bytes(free)} is free.")
335
+ done, shown = 0, 0.0
336
+ while chunk := response.read(1 << 20):
337
+ out.write(chunk)
338
+ digest.update(chunk)
339
+ done += len(chunk)
340
+ if time.monotonic() - shown >= 0.25:
341
+ shown = time.monotonic()
342
+ share = f" {done * 100 // total}% ({_fmt_bytes(done)} of {_fmt_bytes(total)})" if total else f" {_fmt_bytes(done)}"
343
+ loader.step(f"{INDENT}Downloading Ollama{share}")
344
+ finally:
345
+ loader.close()
346
+ return digest.hexdigest()
347
+
348
+
349
+ def _check_tar_member(destination: Path, member: tarfile.TarInfo) -> None:
350
+ """Refuse an archive entry that would be written outside ``destination`` or is not a plain file, folder or link."""
351
+ root = destination.resolve()
352
+
353
+ def inside(path: Path) -> bool:
354
+ try:
355
+ path.resolve().relative_to(root)
356
+ return True
357
+ except ValueError:
358
+ return False
359
+
360
+ target = destination / member.name
361
+ ok = (member.isreg() or member.isdir() or member.issym() or member.islnk()) and inside(target)
362
+ if ok and member.issym():
363
+ ok = inside(target.parent / member.linkname)
364
+ if ok and member.islnk():
365
+ ok = inside(destination / member.linkname)
366
+ if not ok:
367
+ raise OllamaInstallError(f"The download holds an unsafe entry ({member.name}), so it was not unpacked.")
368
+
369
+
370
+ def _unpack(archive: Path, destination: Path) -> None:
371
+ """Unpack Ollama's .zip, .tgz or .tar.zst into the folder ``destination``, over what an earlier archive put there."""
372
+ destination.mkdir(parents=True, exist_ok=True)
373
+ if archive.name.endswith(".zip"):
374
+ with zipfile.ZipFile(archive) as bundle:
375
+ bundle.extractall(destination) # removes any ../ or absolute path from the names itself
376
+ return
377
+ options = {"filter": "data"} if hasattr(tarfile, "data_filter") else {}
378
+ if archive.name.endswith(".tar.zst"):
379
+ import zstandard
380
+ try:
381
+ with open(archive, "rb") as raw, zstandard.ZstdDecompressor().stream_reader(raw) as reader, \
382
+ tarfile.open(fileobj=reader, mode="r|") as bundle:
383
+ for member in bundle:
384
+ _check_tar_member(destination, member)
385
+ bundle.extract(member, destination, **options)
386
+ except zstandard.ZstdError as exc:
387
+ raise OllamaInstallError(f"The download is damaged ({exc}).") from exc
388
+ return
389
+ with tarfile.open(archive, "r:gz") as bundle:
390
+ for member in bundle:
391
+ _check_tar_member(destination, member)
392
+ bundle.extract(member, destination, **options)
393
+
394
+
395
+ TEGRA_RELEASE = Path("/etc/nv_tegra_release") # exists on NVIDIA Jetson boards; names the JetPack generation (R35, R36)
396
+ DRM_DIR = Path("/sys/class/drm") # the graphics cards on Linux, each with the vendor id of its maker
397
+ AMD_VENDOR_ID = "0x1002"
398
+
399
+
400
+ def _nvidia_gpu_present() -> bool:
401
+ return bool(shutil.which("nvidia-smi")) and "GPU" in _run(["nvidia-smi", "-L"])
402
+
403
+
404
+ def _amd_gpu_present() -> bool:
405
+ if platform.system() == "Windows":
406
+ names = _run(["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_VideoController).Name"]).lower()
407
+ return "amd" in names or "radeon" in names
408
+ try:
409
+ return any(card.read_text().strip().lower() == AMD_VENDOR_ID for card in DRM_DIR.glob("card*/device/vendor"))
410
+ except OSError:
411
+ return False
412
+
413
+
414
+ def _ollama_extras() -> dict:
415
+ """The extra Ollama files this computer's GPU needs on top of the main build, as {name in the release's file names: what it is for}.
416
+ Ollama's own installer does the same: AMD GPUs and NVIDIA Jetson boards need an extra file, an NVIDIA GPU needs none (its driver
417
+ is what must be installed), and a Mac needs none."""
418
+ system = platform.system()
419
+ if system == "Linux" and TEGRA_RELEASE.is_file():
420
+ text = TEGRA_RELEASE.read_text(errors="replace")
421
+ for generation, extra in (("R36", "jetpack6"), ("R35", "jetpack5")):
422
+ if generation in text:
423
+ return {extra: "an NVIDIA Jetson board"}
424
+ return {}
425
+ if system in ("Linux", "Windows") and not _nvidia_gpu_present() and _amd_gpu_present(): # with both, the NVIDIA one is used
426
+ return {"rocm": "an AMD GPU"}
427
+ return {}
428
+
429
+
430
+ def install_ollama() -> None:
431
+ """Download Ollama's own build for this computer into Imagent's tools folder, plus the extra file its GPU needs (AMD, Jetson).
432
+ It needs no administrator rights and no change to PATH, and uninstalling removes it by deleting the folder. Stops setup, with the
433
+ reason, when it cannot be done."""
434
+ manual = f"Install Ollama from https://ollama.com/download, then run {app_config.SETUP_COMMAND} again."
435
+ if app_config.ollama_build_prefix() is None:
436
+ fail(f"Imagent has no Ollama build for this computer ({platform.system()} on {platform.machine()}). {manual}")
437
+ root = app_config.OLLAMA_DIR
438
+ program, partial, manifest = root / "program", root / "program.partial", root / app_config.OLLAMA_MANIFEST
439
+ archive = None
440
+ loader = SearchProgress() # the spinner for the steps that show no download percentage
441
+ swapped = False
442
+ try:
443
+ root.mkdir(parents=True, exist_ok=True)
444
+ _remove(partial)
445
+ _remove(manifest)
446
+ # The release's list of files and their sums is trusted only when it is the one pinned in config.py; the sums in it are
447
+ # then what each file is checked against.
448
+ if _download_file(app_config.ollama_release_url(app_config.OLLAMA_MANIFEST), manifest) != app_config.OLLAMA_MANIFEST_SHA256:
449
+ raise OllamaInstallError("The list of Ollama's files is not the one Imagent was made for (its checksum is different).")
450
+ extras = _ollama_extras()
451
+ downloads = app_config.ollama_downloads(manifest.read_text(encoding="utf-8", errors="replace"), tuple(extras))
452
+ if not downloads:
453
+ raise OllamaInstallError(f"Ollama {app_config.OLLAMA_VERSION} has no build for this computer ({platform.system()} on {platform.machine()}).")
454
+ files = {file_name for _, file_name, _ in downloads}
455
+ for extra, purpose in extras.items():
456
+ stem = f"{app_config.ollama_build_prefix()}-{extra}"
457
+ if any(stem + ending in files for ending in app_config.OLLAMA_ARCHIVE_ENDINGS):
458
+ say(f"This computer has {purpose}, so the extra files for it are installed too.")
459
+ else:
460
+ say(f"This computer has {purpose}, but Ollama {app_config.OLLAMA_VERSION} has no extra files for it, so it may not be used.",
461
+ "fg:ansimagenta")
462
+ for url, file_name, expected in downloads:
463
+ archive = root / file_name
464
+ _remove(archive)
465
+ if _download_file(url, archive) != expected:
466
+ raise OllamaInstallError("The download is not the file Ollama published (its checksum is different).")
467
+ loader.step(f"{INDENT}Unpacking Ollama")
468
+ _unpack(archive, partial) # the extra files go over the build, into the same folder
469
+ _remove(archive)
470
+ loader.close()
471
+ _remove(program)
472
+ os.replace(partial, program) # a half-unpacked folder never looks installed
473
+ swapped = True
474
+ binary = app_config.private_ollama_binary()
475
+ if binary is None:
476
+ raise OllamaInstallError("The download does not contain the `ollama` program.")
477
+ loader.step(f"{INDENT}Checking that Ollama runs")
478
+ if subprocess.run([binary, "--version"], capture_output=True, timeout=60).returncode != 0:
479
+ raise OllamaInstallError("The downloaded Ollama does not run on this computer.")
480
+ loader.close()
481
+ (root / "models").mkdir(exist_ok=True)
482
+ app_config.save_tool_info(root, "Ollama", OLLAMA_DESCRIPTION, app_config.OLLAMA_VERSION)
483
+ except OllamaInstallError as exc:
484
+ reason = str(exc)
485
+ except OSError as exc:
486
+ reason = "There is not enough free disk space." if exc.errno == errno.ENOSPC else f"{type(exc).__name__}: {exc}"
487
+ except (tarfile.TarError, zipfile.BadZipFile, subprocess.SubprocessError) as exc:
488
+ reason = f"{type(exc).__name__}: {exc}"
489
+ else:
490
+ reason = None
491
+ finally:
492
+ loader.close() # a failed step must not leave the spinner running
493
+ if archive is not None:
494
+ _remove(archive)
495
+ _remove(manifest)
496
+ _remove(partial)
497
+ if reason is not None:
498
+ if swapped:
499
+ _remove(program)
500
+ fail(f"The Ollama install did not finish. {reason} {manual}")
501
+ say("✓ Ollama installed.", "fg:green")
502
+
503
+
504
+ def ensure_ollama_installed() -> None:
505
+ """Use the Ollama that is here: Imagent's own copy, or the one on PATH if it is new enough. Otherwise install Imagent's own copy,
506
+ and leave an older Ollama of the user's as it is."""
507
+ from imagent.vlm.client import MIN_OLLAMA_VERSION # needs the packages that ensure_packages installed
508
+ if app_config.private_ollama_binary():
509
+ say("✓ Ollama is installed (the copy Imagent installed).", "fg:green")
510
+ return
511
+ system_copy = shutil.which("ollama")
512
+ if system_copy:
513
+ version = _ollama_command_version(system_copy)
514
+ if version is None or version >= MIN_OLLAMA_VERSION:
515
+ say("✓ Ollama is installed.", "fg:green")
516
+ return
517
+ say("Installing Ollama for this project.")
518
+ say(f"Your Ollama is version {'.'.join(map(str, version))}, but Imagent needs {'.'.join(map(str, MIN_OLLAMA_VERSION))} or newer. "
519
+ "Imagent installs its own copy and leaves yours as it is.", "fg:ansimagenta")
520
+ else:
521
+ say("Installing Ollama for this project.")
522
+ say("Ollama is the program that runs the AI models on your computer. It is not installed yet.", "fg:ansimagenta")
523
+ install_ollama()
524
+
525
+
526
+ # --- Step 3: models -----------------------------------------------------------
527
+
528
+ def _clean_model_name(raw: str) -> str:
529
+ """Accept pasted 'VLM_1=name:tag' lines as well as plain names; drop markdown decoration."""
530
+ return raw.strip().split("=", 1)[-1].strip().strip("`'\"*").strip()
531
+
532
+
533
+ def _validate_model(value: str):
534
+ name = _clean_model_name(value)
535
+ if not name:
536
+ return "Please paste a model name, for example: name:tag"
537
+ if name.upper() == "NONE":
538
+ return "NONE means that option does not exist. Paste one of the other options."
539
+ if not MODEL_NAME_PATTERN.match(name):
540
+ return "That does not look like a model name. Paste only the name, for example: name:tag"
541
+ return True
542
+
543
+
544
+ def parse_model_set(raw: str):
545
+ """(vlm, embedding, text_model) from one pasted set, or None unless it holds exactly three model names.
546
+
547
+ The AI is asked for ``vision-name:tag,text-name:tag,embedding-name:tag`` on one line, in that order. Commas, semicolons,
548
+ spaces and line breaks all separate the names, and backticks, quotes and brackets around them are ignored."""
549
+ names = [name for name in re.split(r"[,;|\s]+", re.sub(r"[`'\"*()\[\]]", "", raw)) if name]
550
+ if len(names) != 3 or any(_validate_model(name) is not True for name in names):
551
+ return None
552
+ vlm, text_model, embedding = names
553
+ return vlm, embedding, text_model
554
+
555
+
556
+ def _erase_last_line() -> None:
557
+ """Remove the answered prompt line so the next menu redraws in the same place."""
558
+ print("\033[1A\033[2K", end="", flush=True)
559
+
560
+
561
+ def ask_models(vlm: str = "", embedding: str = "", text_model: str = "", failed: dict | None = None):
562
+ """One screen of editable rows: type or paste each model name where it is shown, copy the AI prompt (which adds a row to
563
+ paste its answer into; a good paste continues at once), and choose Continue once all three names are set. Nothing is cleared while you type.
564
+
565
+ ``failed`` maps the models that were tried on this computer and did not work to the reason; the prompt tells the AI about them.
566
+
567
+ Returns (vlm, embedding, text_model)."""
568
+ from prompt_toolkit import Application
569
+ from prompt_toolkit.application import get_app
570
+ from prompt_toolkit.buffer import Buffer
571
+ from prompt_toolkit.document import Document
572
+ from prompt_toolkit.filters import Condition, has_focus, is_done
573
+ from prompt_toolkit.key_binding import KeyBindings
574
+ from prompt_toolkit.layout import BufferControl, ConditionalContainer, FormattedTextControl, HSplit, Layout, VSplit, Window
575
+ from prompt_toolkit.layout.processors import AfterInput, ConditionalProcessor
576
+
577
+ say("Fill in all three model names, then choose Continue.\n")
578
+ state = {"copied": False, "asked": False, "message": ""}
579
+
580
+ def one_line(buffer): # a pasted line break would show as ^J
581
+ if "\n" in buffer.text or "\r" in buffer.text:
582
+ buffer.document = Document(" ".join(buffer.text.split()))
583
+
584
+ def make_buffer(text=""):
585
+ return Buffer(document=Document(text, len(text)), multiline=False, on_text_changed=one_line)
586
+
587
+ fields = {"vlm": make_buffer(vlm), "embedding": make_buffer(embedding), "text": make_buffer(text_model)}
588
+ paste = make_buffer()
589
+ pointer = lambda window: POINTER + " " if not is_done() and get_app().layout.has_focus(window) else " " * (len(POINTER) + 1)
590
+
591
+ def ready():
592
+ return all(buffer.text.strip() for buffer in fields.values())
593
+
594
+ show_paste = Condition(lambda: state["asked"]) & ~is_done
595
+ show_message = Condition(lambda: bool(state["message"])) & ~is_done
596
+
597
+ def blank(visible=~is_done):
598
+ return ConditionalContainer(Window(height=1), filter=visible)
599
+
600
+ def text_row(label, buffer, filled_green=True):
601
+ # wrap_lines: a name or set longer than the row continues on the next line; without it the row scrolls sideways and
602
+ # hides the start of what was typed or pasted. dont_extend_height: the row grows only as far as the text needs.
603
+ window = Window(
604
+ BufferControl(buffer, input_processors=[ConditionalProcessor(
605
+ AfterInput("not set", style="fg:ansibrightred"), Condition(lambda: filled_green and not buffer.text))]),
606
+ wrap_lines=True, dont_extend_height=True, style=lambda: "fg:ansigreen" if filled_green and buffer.text else "")
607
+ style = lambda: "fg:ansigreen" if buffer.text or not filled_green else "fg:ansibrightred"
608
+ title = Window(FormattedTextControl(lambda: [(style(), f"{pointer(window)}○ {label} ")]), height=1, dont_extend_width=True)
609
+ return window, VSplit([title, window])
610
+
611
+ rows = {}
612
+ field_rows = []
613
+ for key, label in (("vlm", "VLM model: "), ("embedding", "Embedding model:"), ("text", "Text model: ")):
614
+ rows[key], container = text_row(label, fields[key])
615
+ field_rows.append(container)
616
+ rows["paste"], paste_row = text_row("Paste one set:", paste, filled_green=False)
617
+
618
+ def button(text, style):
619
+ # dont_extend_height: without it the row stretches to fill the free height below the cursor, leaving a gap of blank lines
620
+ window = Window(FormattedTextControl(lambda: [(style(), f"{pointer(window)}○ {text()}")], focusable=True), wrap_lines=True,
621
+ dont_extend_height=True)
622
+ return window
623
+
624
+ rows["ask"] = button(lambda: COPIED if state["copied"] else ASK_AI, lambda: "fg:ansigreen" if state["copied"] else "")
625
+ rows["continue"] = button(lambda: "Continue" if ready() else "Continue (enter all three model names first)",
626
+ lambda: "" if ready() else "fg:ansibrightblack italic")
627
+ visible = {"vlm": Condition(lambda: True), "embedding": Condition(lambda: True), "text": Condition(lambda: True),
628
+ "paste": show_paste, "ask": ~is_done, "continue": ~is_done}
629
+
630
+ def initial_focus():
631
+ if ready():
632
+ return "vlm" # all three prefilled: start on the first row, not on Continue
633
+ if state["asked"]:
634
+ return "paste"
635
+ return next(key for key, buffer in fields.items() if not buffer.text.strip())
636
+
637
+ def order():
638
+ return [rows[key] for key in ("vlm", "embedding", "text", "paste", "ask", "continue") if visible[key]()]
639
+
640
+ def commit(app):
641
+ """Tidy the name in the row being left; False (and say why) when it is not a model name."""
642
+ for key, buffer in fields.items():
643
+ if app.layout.has_focus(rows[key]):
644
+ name = _clean_model_name(buffer.text)
645
+ problem = _validate_model(name) if name else True
646
+ if problem is not True:
647
+ state["message"] = "✗ " + problem
648
+ return False
649
+ buffer.document = Document(name)
650
+ state["message"] = ""
651
+ return True
652
+
653
+ def move(app, step):
654
+ if not commit(app):
655
+ return
656
+ windows = order()
657
+ current = app.layout.current_window
658
+ index = windows.index(current) if current in windows else 0
659
+ app.layout.focus(windows[(index + step) % len(windows)])
660
+
661
+ bindings = KeyBindings()
662
+ for key, step in (("up", -1), ("s-tab", -1), ("down", 1), ("tab", 1)):
663
+ bindings.add(key)(lambda event, step=step: move(event.app, step))
664
+ for key in fields:
665
+ bindings.add("enter", filter=has_focus(rows[key]))(lambda event: move(event.app, 1))
666
+
667
+ @bindings.add("enter", filter=has_focus(rows["paste"]))
668
+ def _(event):
669
+ names = parse_model_set(paste.text)
670
+ if names is None:
671
+ state["message"] = "✗ Parsing failed. Please try again, or write the model names manually." if paste.text.strip() else ""
672
+ paste.document = Document()
673
+ return
674
+ for key, name in zip(("vlm", "embedding", "text"), names):
675
+ fields[key].document = Document(name)
676
+ event.app.exit(result="continue") # a good paste is the answer: no second Continue
677
+
678
+ @bindings.add("enter", filter=has_focus(rows["ask"]))
679
+ def _(event):
680
+ state["asked"], state["message"] = True, ""
681
+ if copy_to_clipboard(build_ai_prompt(failed)):
682
+ state["copied"] = True
683
+ event.app.layout.focus(rows["paste"])
684
+ else: # nowhere to copy it to: leave the screen, print the prompt for copying by hand, and come back
685
+ event.app.erase_when_done = True
686
+ event.app.exit(result="print")
687
+
688
+ @bindings.add("enter", filter=has_focus(rows["continue"]))
689
+ def _(event):
690
+ if ready():
691
+ event.app.exit(result="continue")
692
+ else:
693
+ state["message"] = "✗ Enter all three model names first."
694
+
695
+ @bindings.add("c-c")
696
+ def _(event):
697
+ event.app.exit(exception=KeyboardInterrupt)
698
+
699
+ while True:
700
+ layout = HSplit([
701
+ ConditionalContainer(HSplit([paste_row, Window(height=1, content=FormattedTextControl([("fg:ansibrightblack", INDENT + " " + PASTE_SET)])), blank()]),
702
+ filter=show_paste),
703
+ *field_rows, blank(),
704
+ ConditionalContainer(HSplit([rows["ask"], blank(), rows["continue"]]), filter=~is_done),
705
+ ConditionalContainer(Window(FormattedTextControl(lambda: [(RED, INDENT + state["message"])]), height=1), filter=show_message),
706
+ ])
707
+ app = Application(layout=Layout(layout, focused_element=rows[initial_focus()]), key_bindings=bindings, erase_when_done=False)
708
+ try:
709
+ result = app.run()
710
+ except (KeyboardInterrupt, EOFError):
711
+ sys.exit("\nSetup cancelled. Run it again any time.")
712
+ if result == "continue":
713
+ return tuple(fields[key].text.strip() for key in ("vlm", "embedding", "text"))
714
+ state["copied"] = offer_prompt_copy(failed) # "print": offer_prompt_copy tries the clipboard once more, then prints the prompt
715
+
716
+
717
+ # --- Model lookup (ollama.com registry, no Ollama server needed) ---------------
718
+
719
+ class ModelNotFound(Exception):
720
+ pass
721
+
722
+
723
+ class RegistryUnreachable(Exception):
724
+ pass
725
+
726
+
727
+ def _fmt_bytes(n: float) -> str:
728
+ return f"{n / 1e9:.1f} GB" if n >= 1e8 else f"{n / 1e6:.0f} MB"
729
+
730
+
731
+ def _split_model(name: str):
732
+ """'name[:tag]' or 'user/name[:tag]' -> (repository, tag). None for external registries (e.g. hf.co/...)."""
733
+ repo, _, tag = name.partition(":")
734
+ if "/" in repo and "." in repo.split("/")[0]:
735
+ return None
736
+ return (repo if "/" in repo else f"library/{repo}"), tag or "latest"
737
+
738
+
739
+ def _registry_get(path: str, accept: str = "application/json") -> dict:
740
+ request = urllib.request.Request(f"{REGISTRY}/{path}", headers={"Accept": accept, "User-Agent": "imagent-setup"})
741
+ try:
742
+ with urllib.request.urlopen(request, timeout=20) as response:
743
+ return json.load(response)
744
+ except urllib.error.HTTPError as exc:
745
+ if exc.code == 404:
746
+ raise ModelNotFound() from exc
747
+ raise RegistryUnreachable(f"HTTP {exc.code}") from exc
748
+ except (urllib.error.URLError, OSError, ValueError) as exc:
749
+ raise RegistryUnreachable(str(exc)) from exc
750
+
751
+
752
+ def fetch_model_specs(name: str) -> dict:
753
+ """Look the model up on ollama.com. Raises ModelNotFound / RegistryUnreachable."""
754
+ parsed = _split_model(name)
755
+ if parsed is None:
756
+ return {"rows": [("Details", "not checked (model from another registry)")], "bytes": 0}
757
+ repo, tag = parsed
758
+ manifest = _registry_get(f"{repo}/manifests/{tag}", MANIFEST_ACCEPT)
759
+ try:
760
+ size = manifest["config"]["size"] + sum(layer["size"] for layer in manifest["layers"])
761
+ digest = manifest["config"]["digest"]
762
+ except (KeyError, TypeError) as exc:
763
+ raise RegistryUnreachable("unexpected response") from exc
764
+ rows = [("Download size", _fmt_bytes(size))]
765
+ try:
766
+ config = _registry_get(f"{repo}/blobs/{digest}")
767
+ for label, key in (("Parameters", "model_type"), ("Quantization", "file_type"), ("Family", "model_family")):
768
+ if config.get(key):
769
+ rows.append((label, str(config[key])))
770
+ except RegistryUnreachable:
771
+ pass # size alone is enough to continue
772
+ return {"rows": rows, "bytes": size}
773
+
774
+
775
+ def review_models(vlm: str, embedding: str, text_model: str, local: bool):
776
+ """Verify both models exist, show their specs, then ask Continue / Go back.
777
+
778
+ ``local`` is whether Ollama runs on this computer; the disk-space check only makes sense then.
779
+ Returns (proceed, names_not_found)."""
780
+ say("\nChecking the models on ollama.com…")
781
+ specs, problems, missing = {}, [], set()
782
+ for name in dict.fromkeys([vlm, embedding, text_model]):
783
+ try:
784
+ specs[name] = fetch_model_specs(name)
785
+ except ModelNotFound:
786
+ missing.add(name)
787
+ problems.append(f"✗ '{name}' was not found on ollama.com. Check the name and try again.")
788
+ except RegistryUnreachable:
789
+ problems.append("✗ Could not reach ollama.com. Check your internet connection and try again.")
790
+ break
791
+ if problems:
792
+ say("")
793
+ for problem in problems:
794
+ say(problem, RED)
795
+ say("")
796
+ return False, missing
797
+
798
+ say("")
799
+ for label, name in (("VLM model", vlm), ("Embedding model", embedding), ("Text model", text_model)):
800
+ say(f"{label}: {name}", "bold")
801
+ for key, value in specs[name]["rows"]:
802
+ say(f" {key + ':':<15}{value}")
803
+ say("")
804
+ total = sum(specs[name]["bytes"] for name in dict.fromkeys([vlm, embedding, text_model]))
805
+ enough_space = True
806
+ if local:
807
+ # Ollama keeps its models in its own folder, usually on the home drive; this is an estimate.
808
+ free = shutil.disk_usage(Path.home()).free
809
+ say(f"Total download: {_fmt_bytes(total)} Free disk space (home drive, estimate): {_fmt_bytes(free)}\n", "bold")
810
+ enough_space = total * 1.1 <= free
811
+ if not enough_space:
812
+ say("✗ Not enough free disk space for these models. Free up space or go back and choose smaller models.\n", RED)
813
+ else:
814
+ say(f"Total download: {_fmt_bytes(total)} (disk space on the Ollama computer is not checked)\n", "bold")
815
+ say("Once Imagent is set up, these models cannot be changed.\n", "fg:ansimagenta")
816
+
817
+ choice = ask(questionary.select(
818
+ "Ready to download?",
819
+ choices=[
820
+ questionary.Choice("○ ✓ Continue: download the models" if enough_space else "Continue: download the models", value="go",
821
+ disabled=None if enough_space else "not enough disk space"),
822
+ questionary.Choice("○ ← Go back and change the models", value="back"),
823
+ ],
824
+ qmark=QMARK, pointer=POINTER, style=STYLE,
825
+ ))
826
+ return choice == "go", missing
827
+
828
+
829
+ # --- Step 4: download ---------------------------------------------------------
830
+
831
+ @contextmanager
832
+ def ollama_client(host: str):
833
+ """Yield a connected Ollama client, starting `ollama serve` only if needed and stopping it afterwards.
834
+
835
+ Yields None (after printing the reason) when Ollama cannot be reached or started."""
836
+ # needs the packages that ensure_packages installed
837
+ from imagent.vlm.client import MIN_OLLAMA_VERSION, is_local, is_reachable, make_client, server_version, start_server, stop_server
838
+ client = make_client(host)
839
+
840
+ started = None
841
+ try:
842
+ if not is_reachable(client):
843
+ if not is_local(host):
844
+ say(f"✗ Cannot reach Ollama at {host}.", RED)
845
+ yield None
846
+ return
847
+ if not app_config.ollama_binary():
848
+ say(f"✗ The `ollama` program was not found. Run {app_config.SETUP_COMMAND} again to install it.", RED)
849
+ yield None
850
+ return
851
+ say("Starting Ollama in the background…")
852
+ started = start_server(client, host)
853
+ if started is None:
854
+ say("✗ Ollama did not start. Open the Ollama app (or run `ollama serve`) and try again.", RED)
855
+ yield None
856
+ return
857
+ version = server_version(host)
858
+ if version is not None and version < MIN_OLLAMA_VERSION:
859
+ say(f"✗ The Ollama at {host} is version {'.'.join(map(str, version))}, but Imagent needs "
860
+ f"{'.'.join(map(str, MIN_OLLAMA_VERSION))} or newer. Update it (on that computer, if it is another one), "
861
+ f"then run {app_config.SETUP_COMMAND} again.", RED)
862
+ yield None
863
+ return
864
+ yield client
865
+ finally:
866
+ if started is not None:
867
+ stop_server(started)
868
+ say("Stopped the temporary Ollama server.")
869
+
870
+
871
+ def _normalize(name: str) -> str:
872
+ return name if ":" in name else f"{name}:latest"
873
+
874
+
875
+ def _pull_with_progress(client, name: str) -> None:
876
+ last = ""
877
+ for progress in client.pull(name, stream=True):
878
+ line = progress.status or ""
879
+ if progress.total and progress.completed is not None:
880
+ line = f"{line} {progress.completed * 100 // progress.total}% ({_fmt_bytes(progress.completed)} of {_fmt_bytes(progress.total)})"
881
+ if line != last:
882
+ print(f"\r\033[K{INDENT}{line}", end="", flush=True)
883
+ last = line
884
+ print("\r\033[K", end="", flush=True)
885
+
886
+
887
+ def _remember_pulled(name: str) -> None:
888
+ """Note in install_record.json that Imagent downloaded this model, so uninstalling removes it (and only such models)."""
889
+ record = app_config.load_install_record()
890
+ models = [m for m in record.get("ollama_models", []) if isinstance(m, str)]
891
+ if _normalize(name) not in models:
892
+ models.append(_normalize(name))
893
+ app_config.save_install_record({**record, "ollama_models": models})
894
+
895
+
896
+ def _pull_models(client, models: list) -> None:
897
+ """Pull each model that is not installed yet, showing progress."""
898
+ installed = {_normalize(m.model) for m in client.list().models}
899
+ for name in dict.fromkeys(models):
900
+ if _normalize(name) in installed:
901
+ say(f"✓ {name} is already downloaded.", "fg:ansigreen")
902
+ continue
903
+ say(f"Downloading {name}…")
904
+ _pull_with_progress(client, name)
905
+ _remember_pulled(name)
906
+ say(f"✓ {name} downloaded.", "fg:ansigreen")
907
+
908
+
909
+ def verify_models(client, vlm: str, embedding: str, text_model: str):
910
+ """Check that the downloaded models can do their job, before they are locked in.
911
+
912
+ Returns (settings, problems). ``problems`` maps a model name to what is wrong with it."""
913
+ problems = {}
914
+ for name, needed, what in ((vlm, "vision", "a vision model"), (embedding, "embedding", "an embedding model"),
915
+ (text_model, "completion", "a text chat model")):
916
+ try:
917
+ capabilities = client.show(name).capabilities
918
+ except Exception as exc:
919
+ problems[name] = f"could not be inspected ({type(exc).__name__}: {exc})."
920
+ continue
921
+ if capabilities is None:
922
+ problems[name] = f"cannot be checked because your Ollama is too old. Update Ollama, then run {app_config.SETUP_COMMAND} again."
923
+ elif needed not in capabilities:
924
+ problems[name] = f"is not {what}. Ollama lists its abilities as: {', '.join(capabilities) or 'none'}."
925
+ if problems:
926
+ return None, problems
927
+ try:
928
+ dimension = len(client.embed(model=embedding, input=["Imagent setup check"],
929
+ options=app_config.EMBED_OPTIONS).embeddings[0])
930
+ except Exception as exc:
931
+ return None, {embedding: f"did not produce an embedding ({type(exc).__name__}: {exc})."}
932
+ if dimension == 0:
933
+ return None, {embedding: "returned an empty embedding."}
934
+ digests = {m.model: m.digest for m in client.list().models}
935
+ return {
936
+ "vlm_model": _normalize(vlm), "embedding_model": _normalize(embedding), "judge_model": _normalize(text_model),
937
+ "vlm_digest": digests.get(_normalize(vlm)), "embedding_digest": digests.get(_normalize(embedding)),
938
+ "judge_digest": digests.get(_normalize(text_model)),
939
+ "embedding_dim": dimension,
940
+ }, {}
941
+
942
+
943
+ def _ask_about_memory(edge: int, model_bytes: int | None, free_bytes: int | None) -> bool:
944
+ """The vision model ran out of memory at this picture size. Shows the memory that is free and the programs using the most, since
945
+ closing some may be all it takes, and asks what to do. Returns True to try again from the largest size, False to go on with
946
+ smaller pictures; stops setup when asked to."""
947
+ from imagent.os_specific.memory import top_memory_users
948
+ say(f"⚠ The model ran out of memory with pictures up to {edge} pixels. This may only be because other programs are using the "
949
+ "memory right now.", "fg:ansimagenta")
950
+ if free_bytes is not None:
951
+ say(f"Free memory now: {_fmt_bytes(free_bytes)}" + (f" The model: {_fmt_bytes(model_bytes)}" if model_bytes else ""))
952
+ users = top_memory_users(app_config.CALIBRATION_TOP_APPS)
953
+ if users:
954
+ say("Using the most memory right now:\n" + "\n".join(f" {_fmt_bytes(used):>9} {name}" for name, used in users))
955
+ say()
956
+ choice = ask(questionary.select(
957
+ "What would you like to do?",
958
+ choices=[
959
+ questionary.Choice("○ Try again (close some programs first)", value="again"),
960
+ questionary.Choice("○ Continue with smaller pictures", value="smaller"),
961
+ questionary.Choice("○ Stop setup", value="stop"),
962
+ ],
963
+ qmark=QMARK, pointer=POINTER, style=STYLE,
964
+ ))
965
+ if choice == "stop":
966
+ sys.exit(f"\n{INDENT}Setup stopped. Close programs you do not need, then run {app_config.SETUP_COMMAND} again.")
967
+ return choice == "again"
968
+
969
+
970
+ def measure_computer(client, vlm_model: str, embedding_model: str):
971
+ """Measure this computer with the vision model and the embedding model beside it (vlm/calibration.py), with no questions asked.
972
+
973
+ Returns (device settings, None), or (None, problems) when a model does not run on this computer: ``problems`` maps the name
974
+ of the model that failed (the vision model, or the embedding model when that is the one) to what is wrong with it."""
975
+ from imagent.vlm.calibration import NotPossible, calibrate
976
+ say("Measuring this computer with the vision model. This runs by itself and can take a few minutes…")
977
+ try:
978
+ device = calibrate(client, vlm_model, embedding_model, lambda message: say(f" {message}"), on_out_of_memory=_ask_about_memory)
979
+ except NotPossible as exc:
980
+ return None, {exc.model or vlm_model: str(exc)}
981
+ except Exception as exc:
982
+ return None, {vlm_model: f"could not be measured ({type(exc).__name__}: {exc})."}
983
+ say(f"✓ Pictures up to {device['image_long_edge']} pixels, a memory window of {device['num_ctx']}, "
984
+ f"waiting up to {device['timeout_seconds']} seconds for a reply.", "fg:ansigreen")
985
+ if device["one_model_at_a_time"]:
986
+ say("⚠ The vision and embedding models do not fit in memory together on this computer. Imagent will load one at a time, "
987
+ "which makes indexing a little slower.", "fg:ansimagenta")
988
+ return device, None
989
+
990
+
991
+ def _remove_failed(client, rejected: set, fixed: dict) -> None:
992
+ """Take off this computer the models that did not work, so they do not keep using its disk.
993
+
994
+ Only what Imagent itself downloaded or copied (the list in install_record.json, which the uninstaller uses too) is removed: a
995
+ model that was on the computer before is never touched. Nothing is removed that a model which is kept needs.
996
+ ``rejected`` holds the names as typed, ``fixed`` maps each typed name to the name Imagent uses."""
997
+ record = app_config.load_install_record()
998
+ ours = {m for m in record.get("ollama_models", []) if isinstance(m, str)}
999
+ pins = record["pinned_models"] if isinstance(record.get("pinned_models"), dict) else {}
1000
+ kept = set()
1001
+ for typed, used in fixed.items():
1002
+ if typed not in rejected:
1003
+ kept |= {_normalize(typed), used, pins.get(used)}
1004
+ removed = set()
1005
+ for typed in sorted(rejected):
1006
+ names = [name for name in (fixed.get(typed), _normalize(typed)) if name in ours and name not in kept]
1007
+ deleted = _delete_models(client, names)
1008
+ removed |= deleted
1009
+ if deleted:
1010
+ say(f"✓ Removed {typed}, which did not work on this computer, to free its disk space.", "fg:ansigreen")
1011
+ _forget_removed(record, removed)
1012
+
1013
+
1014
+ def _delete_models(client, names) -> set:
1015
+ """Delete each model from Ollama. Returns the names that were removed; one that cannot be removed is said so and left."""
1016
+ removed = set()
1017
+ for name in names:
1018
+ try:
1019
+ client.delete(name)
1020
+ removed.add(name)
1021
+ except Exception as exc:
1022
+ say(f"⚠ Could not remove {name} ({type(exc).__name__}: {exc}). You can remove it with: ollama rm {name}", "fg:ansimagenta")
1023
+ return removed
1024
+
1025
+
1026
+ def _forget_removed(record: dict, removed: set) -> None:
1027
+ """Take the removed models off the list in install_record.json that the uninstaller uses."""
1028
+ if removed:
1029
+ pins = record["pinned_models"] if isinstance(record.get("pinned_models"), dict) else {}
1030
+ app_config.save_install_record({**record, "ollama_models": [m for m in record.get("ollama_models", []) if m not in removed],
1031
+ "pinned_models": {name: base for name, base in pins.items() if name not in removed}})
1032
+
1033
+
1034
+ def _remove_unused(client, vlm: str, embedding: str, text_model: str) -> None:
1035
+ """Take off this computer what an earlier try of setup installed and the confirmed models do not use, to free its disk space.
1036
+
1037
+ Only what Imagent itself downloaded or copied (the list in install_record.json) is removed, never a model that was on the
1038
+ computer before. A model of the confirmed set stays, with the fixed copy made from it, so nothing is downloaded twice."""
1039
+ record = app_config.load_install_record()
1040
+ pins = record["pinned_models"] if isinstance(record.get("pinned_models"), dict) else {}
1041
+ needed = {_normalize(name) for name in (vlm, embedding, text_model)}
1042
+ needed |= {pinned for pinned, base in pins.items() if base in needed}
1043
+ unused = [m for m in record.get("ollama_models", []) if isinstance(m, str) and m not in needed]
1044
+ installed = {_normalize(m.model) for m in client.list().models}
1045
+ deleted = _delete_models(client, [name for name in unused if name in installed])
1046
+ if deleted:
1047
+ say("✓ Removed the models of an earlier try that these do not use, to free their disk space.", "fg:ansigreen")
1048
+ _forget_removed(record, deleted | {name for name in unused if name not in installed}) # a model already gone is off the list too
1049
+
1050
+
1051
+ def download_and_verify(host: str, vlm: str, embedding: str, text_model: str):
1052
+ """Download all models and verify them. Returns (settings, problems); settings is None on failure.
1053
+
1054
+ ``problems`` maps the name of each model that did not work, as typed, to what is wrong with it."""
1055
+ with ollama_client(host) as client:
1056
+ if client is None:
1057
+ return None, {}
1058
+ try:
1059
+ _remove_unused(client, vlm, embedding, text_model) # before the download, so the disk has room for the new models
1060
+ _pull_models(client, [vlm, embedding, text_model])
1061
+ except Exception as exc:
1062
+ print()
1063
+ say(f"✗ Download failed: {exc}", RED)
1064
+ return None, {}
1065
+ from imagent.vlm.client import pin_model
1066
+ fixed = {} # each model as the user typed it -> the name Imagent will use; one copy when two roles share a model
1067
+ for typed in dict.fromkeys((vlm, embedding, text_model)):
1068
+ original = _normalize(typed)
1069
+ try:
1070
+ fixed[typed], _ = pin_model(client, original)
1071
+ app_config.record_pinned_model(fixed[typed], original)
1072
+ say(f"✓ Saved a copy of {original} that stays exactly as it is now, even if the model is updated later.", "fg:ansigreen")
1073
+ except Exception as exc:
1074
+ fixed[typed] = original
1075
+ say(f"⚠ Could not save a fixed copy of {original} ({type(exc).__name__}: {exc}). Imagent will use it as it is "
1076
+ "and stop if it ever changes.", "fg:ansimagenta")
1077
+ say("Checking that the models work…")
1078
+ try:
1079
+ settings, problems = verify_models(client, fixed[vlm], fixed[embedding], fixed[text_model])
1080
+ except Exception as exc:
1081
+ say(f"✗ Could not check the models: {exc}", RED)
1082
+ return None, {}
1083
+ typed_as = {used: typed for typed, used in fixed.items()}
1084
+ problems = {typed_as.get(name, name): reason for name, reason in problems.items()}
1085
+ if settings is not None:
1086
+ device, measure_problems = measure_computer(client, settings["vlm_model"], settings["embedding_model"])
1087
+ if measure_problems:
1088
+ settings = None
1089
+ problems = {typed_as.get(name, name): reason for name, reason in measure_problems.items()}
1090
+ for name, reason in problems.items(): # said before the removal below, so the reason comes first
1091
+ say(f"✗ '{name}' {reason}", RED)
1092
+ _remove_failed(client, set(problems), fixed)
1093
+ return None, problems
1094
+ settings["device"] = device
1095
+ for name, reason in problems.items():
1096
+ say(f"✗ '{name}' {reason}", RED)
1097
+ return settings, problems
1098
+
1099
+
1100
+ # --- Choosing models (first run only) ------------------------------------------
1101
+
1102
+ PENDING_MODELS_KEY = "pending_models" # in config.json: the names confirmed on the review screen, until setup finishes
1103
+
1104
+
1105
+ def _load_pending_models() -> tuple[str, str, str]:
1106
+ """(vlm, embedding, text_model) confirmed in an earlier run of setup that did not finish, each "" when unknown."""
1107
+ pending = app_config.load_config().get(PENDING_MODELS_KEY)
1108
+ if not isinstance(pending, dict):
1109
+ return "", "", ""
1110
+ return tuple(pending[key].strip() if isinstance(pending.get(key), str) else "" for key in ("vlm", "embedding", "text"))
1111
+
1112
+
1113
+ def _store_pending_models(vlm: str, embedding: str, text_model: str) -> None:
1114
+ """Keep the names in config.json so that a setup that stops part way can show them again. Nothing is downloaded from them."""
1115
+ config = {key: value for key, value in app_config.load_config().items() if key != PENDING_MODELS_KEY}
1116
+ if vlm or embedding or text_model:
1117
+ config[PENDING_MODELS_KEY] = {"vlm": vlm, "embedding": embedding, "text": text_model}
1118
+ app_config.save_config(config)
1119
+
1120
+
1121
+ def _forget_pending_models(names) -> None:
1122
+ """Drop from the saved names the models that were not found or did not work, so they are not shown again."""
1123
+ vlm, embedding, text_model = _load_pending_models()
1124
+ _store_pending_models("" if vlm in names else vlm, "" if embedding in names else embedding,
1125
+ "" if text_model in names else text_model)
1126
+
1127
+
1128
+ def choose_models(saved_host: str):
1129
+ """Input boxes -> verify on ollama.com -> specs -> download -> verify.
1130
+
1131
+ Returns (settings, host). The caller locks the settings into the database."""
1132
+ from imagent.vlm.client import is_local # needs the packages that ensure_packages installed
1133
+ step("Models")
1134
+ host = saved_host or DEFAULT_HOST
1135
+ vlm, embedding, text_model = _load_pending_models()
1136
+ failed: dict = {} # every model that was tried here and did not work, with the reason: the AI prompt tells the AI
1137
+ while True:
1138
+ vlm, embedding, text_model = ask_models(vlm, embedding, text_model, failed)
1139
+ _store_pending_models(vlm, embedding, text_model) # kept at once, so a setup that stops before the download shows them again
1140
+ proceed, missing = review_models(vlm, embedding, text_model, is_local(host))
1141
+ if not proceed:
1142
+ # Clear only the names that were not found; keep the valid ones.
1143
+ vlm = "" if vlm in missing else vlm
1144
+ embedding = "" if embedding in missing else embedding
1145
+ text_model = "" if text_model in missing else text_model
1146
+ _forget_pending_models(missing)
1147
+ step("Models")
1148
+ continue
1149
+ _store_pending_models(vlm, embedding, text_model)
1150
+ step("Download")
1151
+ settings, rejected = download_and_verify(host, vlm, embedding, text_model)
1152
+ if settings is not None:
1153
+ return settings, host
1154
+ failed.update(rejected)
1155
+ _forget_pending_models(set(rejected))
1156
+ vlm = "" if vlm in rejected else vlm
1157
+ embedding = "" if embedding in rejected else embedding
1158
+ text_model = "" if text_model in rejected else text_model
1159
+ step("Models")
1160
+
1161
+
1162
+ # --- Re-run: status of the locked models ---------------------------------------
1163
+
1164
+ def _installed(client) -> dict:
1165
+ return {_normalize(m.model): (m.size or 0, m.digest) for m in client.list().models}
1166
+
1167
+
1168
+ def _reinstall(client, name: str) -> None:
1169
+ """Pull a locked model that was removed from Ollama, after a disk-space check.
1170
+
1171
+ A pinned copy (see vlm.client.pin_model) is not on ollama.com: it is made again from the model it was copied from,
1172
+ if that is still the same version."""
1173
+ from imagent.vlm.client import is_pinned, pinned_name
1174
+ if is_pinned(name):
1175
+ base = (app_config.load_install_record().get("pinned_models") or {}).get(name, "")
1176
+ try:
1177
+ digest = {m.model: m.digest for m in client.list().models}.get(base)
1178
+ if digest and pinned_name(base, digest) == name:
1179
+ client.copy(base, name)
1180
+ say(f"✓ {name} was made again from {base}.", "fg:ansigreen")
1181
+ return
1182
+ except Exception as exc:
1183
+ say(f"✗ Could not make {name} again ({type(exc).__name__}: {exc}).", RED)
1184
+ return
1185
+ say(f"✗ {name} was removed from Ollama, and {base or 'the model it was copied from'} is not the same version any more, "
1186
+ "so the original cannot be restored. Uninstall Imagent and set it up again to use the models that are installed "
1187
+ "(this clears the index).", RED)
1188
+ return
1189
+ try:
1190
+ needed = fetch_model_specs(name)["bytes"]
1191
+ if needed * 1.1 > shutil.disk_usage(Path.home()).free:
1192
+ say(f"✗ Not enough free disk space for {name} ({_fmt_bytes(needed)}). Free up space and try again.", RED)
1193
+ return
1194
+ except ModelNotFound:
1195
+ say(f"✗ '{name}' no longer exists on ollama.com, so it cannot be reinstalled.", RED)
1196
+ return
1197
+ except RegistryUnreachable:
1198
+ pass # offline check failed; let the pull report any real problem
1199
+ try:
1200
+ _pull_models(client, [name])
1201
+ except Exception as exc:
1202
+ print()
1203
+ say(f"✗ Download failed: {exc}", RED)
1204
+
1205
+
1206
+ def manage_models(settings: dict, host: str) -> None:
1207
+ """Setup was run before: show the locked models, and ask only when one was removed (to reinstall it)."""
1208
+ say("Setup was already completed. Checking your installed models…\n")
1209
+ with ollama_client(host) as client:
1210
+ if client is None:
1211
+ sys.exit(1)
1212
+ while True:
1213
+ try:
1214
+ installed = _installed(client)
1215
+ except Exception as exc:
1216
+ fail(f"Could not read the model list from Ollama: {exc}")
1217
+
1218
+ # One entry per model name; the text model may be the same model as the VLM.
1219
+ locked: dict = {}
1220
+ for role, key in (("VLM", "vlm"), ("Embedding", "embedding"), ("Text", "judge")):
1221
+ entry = locked.setdefault(settings[f"{key}_model"], {"roles": [], "digest": settings[f"{key}_digest"]})
1222
+ entry["roles"].append(role)
1223
+ in_use = [(" + ".join(entry["roles"]), name, entry["digest"]) for name, entry in locked.items() if name in installed]
1224
+ missing = [(" + ".join(entry["roles"]), name) for name, entry in locked.items() if name not in installed]
1225
+ others = sorted(n for n in installed if n not in locked)
1226
+ width = max([len(n) for n in [*(name for _, name, _ in in_use), *others]] + [1])
1227
+
1228
+ say("Installed models:", "bold")
1229
+ for role, name, digest in in_use:
1230
+ say(f"✓ {name:<{width}} {_fmt_bytes(installed[name][0]):>8} {role} (in use)", "fg:ansigreen")
1231
+ if digest and installed[name][1] != digest:
1232
+ say(" ⚠ This is not the same version it was when you set up Imagent, so Imagent will not run until the original is back.", "fg:ansimagenta")
1233
+ for name in others:
1234
+ say(f" {name:<{width}} {_fmt_bytes(installed[name][0]):>8}")
1235
+ if not installed:
1236
+ say(" (no models installed)")
1237
+ say("")
1238
+ say("Note: the models are locked once set. Each embedding model produces different vectors for",
1239
+ "fg:ansibrightblack")
1240
+ say("the same text, so switching models would break all existing image searches. To use other",
1241
+ "fg:ansibrightblack")
1242
+ say("models, uninstall Imagent and set it up again (this clears the index).", "fg:ansibrightblack")
1243
+ say("")
1244
+
1245
+ choices = [
1246
+ questionary.Choice(
1247
+ [(RED, f"○ {role} model: {name} is not installed. Select to reinstall")], value=("reinstall", name))
1248
+ for role, name in missing
1249
+ ]
1250
+ if not missing:
1251
+ return # nothing to fix: nothing to ask
1252
+ action, name = ask(questionary.select(
1253
+ "What would you like to do?", choices=choices, default=choices[0].value,
1254
+ qmark=QMARK, pointer=POINTER, style=STYLE))
1255
+ _erase_last_line()
1256
+
1257
+ _reinstall(client, name)
1258
+ say("")
1259
+
1260
+
1261
+ def check_test_pictures() -> None:
1262
+ """Download the test pictures once (about 23 MB), unpack them into Imagent's data folder and run the steps of indexing that need no model over them.
1263
+
1264
+ Nothing is asked. A problem here is reported but does not stop setup: it is a check, and Imagent works without it."""
1265
+ from imagent.image_processing import sample_pictures
1266
+ folder = app_config.IMAGENT_HOME / "test_pictures"
1267
+ say("Preparing the test pictures (downloaded once, about 23 MB) and checking that this computer can read them…")
1268
+ findings: list[str] = []
1269
+ try:
1270
+ sample_pictures.unpack(folder)
1271
+ expected = sample_pictures.make_extremes(folder, say=lambda message: say(f" {message}", "fg:ansimagenta"))
1272
+ outcomes = sample_pictures.check_pictures(folder, expected, say=findings.append)
1273
+ except Exception as exc:
1274
+ say(f"⚠ The test pictures could not be prepared ({type(exc).__name__}: {exc}). Imagent works without them.", "fg:ansimagenta")
1275
+ return
1276
+ summary = ", ".join(f"{count} {outcome}" for outcome, count in sorted(outcomes.items()))
1277
+ say(f"✓ Checked {sum(outcomes.values())} test pictures: {summary}.", "fg:ansigreen")
1278
+ for finding in findings:
1279
+ say(f"⚠ {finding}", "fg:ansimagenta")
1280
+
1281
+
1282
+ def measure_again_if_needed(settings: dict, host: str) -> None:
1283
+ """Setup was run before: measure this computer if it never was (the models are locked, so they never change and need no new measurement)."""
1284
+ conn = init_db(str(app_config.DB_PATH))
1285
+ try:
1286
+ device = get_device_settings(conn)
1287
+ finally:
1288
+ conn.close()
1289
+ with ollama_client(host) as client:
1290
+ if client is None:
1291
+ sys.exit(1)
1292
+ try:
1293
+ digest = {m.model: m.digest for m in client.list().models}.get(settings["vlm_model"])
1294
+ except Exception as exc:
1295
+ fail(f"Could not read the model list from Ollama: {exc}")
1296
+ if digest is None or (device is not None and device["one_model_at_a_time"] is not None):
1297
+ return # a missing model was offered for reinstall above; a measured computer stays measured
1298
+ device, problems = measure_computer(client, settings["vlm_model"], settings["embedding_model"])
1299
+ if problems:
1300
+ name, reason = next(iter(problems.items()))
1301
+ fail(f"'{name}' {reason}")
1302
+ conn = init_db(str(app_config.DB_PATH))
1303
+ try:
1304
+ with conn:
1305
+ set_device_settings(conn, device, digest)
1306
+ finally:
1307
+ conn.close()
1308
+
1309
+
1310
+ def keep_deleted_label(number: int) -> str:
1311
+ """How a number of remembered pictures is named in a menu."""
1312
+ return f"{number} deleted pictures" if number else "None: forget a picture as soon as it is deleted"
1313
+
1314
+
1315
+ def ask_keep_deleted() -> int:
1316
+ """Explain what remembering deleted pictures is for, and ask how many to remember: one of ``KEEP_DELETED_CHOICES`` (0 remembers none)."""
1317
+ say("When you delete a picture, Imagent forgets it at the next scan. It can instead remember what it learned about the picture:")
1318
+ say("its description and search data (not the picture, and not where it was).")
1319
+ say("If the same picture comes back later (restored from a backup, copied, or moved into a folder you add later), Imagent")
1320
+ say("recognises it by its pixels and uses what it remembers, so it does not have to be analysed again. That saves time when")
1321
+ say("indexing. When there are more than the number you choose, the oldest are forgotten first.\n")
1322
+ choices = [questionary.Choice(keep_deleted_label(number), value=number) for number in KEEP_DELETED_CHOICES]
1323
+ question = questionary.select(
1324
+ "How many deleted pictures should Imagent remember?", choices=choices,
1325
+ default=next(c for c in choices if c.value == KEEP_DELETED_DEFAULT), qmark=QMARK, pointer=POINTER, style=STYLE,
1326
+ )
1327
+ # questionary also marks the default as "selected", which the style underlines for good. Keep only the pointer on it.
1328
+ control = next(w.content for w in question.application.layout.find_all_windows() if hasattr(w.content, "selected_options"))
1329
+ control.selected_options.clear()
1330
+ return ask(question)
1331
+
1332
+
1333
+ def choose_keep_deleted() -> None:
1334
+ """Ask what happens to the data of a deleted picture, and store the answer. When it was answered before, nothing is asked."""
1335
+ conn = init_db(str(app_config.DB_PATH))
1336
+ try:
1337
+ if get_keep_deleted(conn) is not None:
1338
+ return
1339
+ step("Deleted pictures")
1340
+ keep = ask_keep_deleted()
1341
+ with conn:
1342
+ set_keep_deleted(conn, keep)
1343
+ finally:
1344
+ conn.close()
1345
+ say(f"✓ Imagent will remember the last {keep} deleted pictures." if keep else "✓ Imagent will not remember deleted pictures.",
1346
+ "fg:green")
1347
+
1348
+
1349
+ # --- Main ---------------------------------------------------------------------
1350
+
1351
+ def main() -> None:
1352
+ make_output_safe()
1353
+ if not sys.stdin.isatty():
1354
+ fail(f"Setup needs an interactive terminal. Run it directly: {app_config.SETUP_COMMAND}")
1355
+
1356
+ step("Your computer")
1357
+ say(system_details())
1358
+
1359
+ step("Required tools")
1360
+ prepare_ocr()
1361
+ say()
1362
+ ensure_ollama_installed()
1363
+
1364
+ try:
1365
+ conn = init_db(str(app_config.DB_PATH))
1366
+ except RuntimeError as exc: # SQLite too old for the schema
1367
+ fail(str(exc))
1368
+ try:
1369
+ settings = get_model_settings(conn)
1370
+ finally:
1371
+ conn.close()
1372
+ host = app_config.load_config().get("ollama_host", "")
1373
+ from imagent.vlm.client import is_local
1374
+ if host and not is_local(host):
1375
+ say(f"⚠ config.json points to an Ollama on another computer ({host}). Imagent only works with an Ollama on this "
1376
+ f"computer, so the address is set back to {DEFAULT_HOST}.", "fg:ansimagenta")
1377
+ host = DEFAULT_HOST
1378
+ app_config.save_config({**app_config.load_config(), "ollama_host": host})
1379
+
1380
+ if settings is not None:
1381
+ step("Installed models")
1382
+ if not host: # config.json was deleted; the models are still locked in the database
1383
+ host = DEFAULT_HOST
1384
+ app_config.save_config({"ollama_host": host})
1385
+ manage_models(settings, host)
1386
+ measure_again_if_needed(settings, host)
1387
+ choose_keep_deleted()
1388
+ clear_screen()
1389
+ say("✓ Setup complete.", "fg:green")
1390
+ return
1391
+
1392
+ settings, host = choose_models(host)
1393
+ device = settings.pop("device")
1394
+ app_config.save_config({"ollama_host": host})
1395
+ conn = init_db(str(app_config.DB_PATH))
1396
+ try:
1397
+ with conn:
1398
+ set_device_settings(conn, device, settings["vlm_digest"])
1399
+ set_model_settings(conn, settings) # last step: this row marks setup as complete
1400
+ except sqlite3.IntegrityError:
1401
+ fail("Imagent was already set up by another run of setup.")
1402
+ finally:
1403
+ conn.close()
1404
+ check_test_pictures()
1405
+ choose_keep_deleted()
1406
+ clear_screen()
1407
+ say(f"\n✓ Setup complete. Your models are locked in.", "fg:green")
1408
+
1409
+