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,379 @@
1
+ """
2
+ imagent/commands/uninstall.py — Take Imagent off this computer: show what will be lost, ask three times, then delete.
3
+
4
+ Run by ``imagent uninstall``. It removes:
5
+ * the Ollama models that setup downloaded or copied (listed in install_record.json); a model you already had
6
+ before Imagent is never removed;
7
+ * Imagent's data folder (the index database, config.json, logs);
8
+ and, last, each program setup installed for Imagent (its own copy of Ollama, when the computer had none): for each one it describes
9
+ the program and asks whether to remove it too, and the answer is no unless you type y.
10
+ It never touches your image files, any other Ollama model, or an Ollama you had before Imagent. The program itself is removed afterwards
11
+ with ``pipx uninstall imagent-cli`` (a running program cannot remove itself), and the last message says so.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import secrets
19
+ import shutil
20
+ import sqlite3
21
+ import stat
22
+ import string
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ import urllib.error
27
+ import urllib.request
28
+ from contextlib import contextmanager
29
+ from pathlib import Path
30
+ from urllib.parse import urlparse
31
+
32
+ from imagent import config
33
+ from imagent.pipeline.console import make_output_safe
34
+ from imagent.os_specific.process import background_process_options
35
+ from imagent.pipeline.locking import AlreadyRunning, single_instance
36
+
37
+ DEFAULT_HOST = "http://localhost:11434"
38
+ FINAL_CODE_LENGTH = 10
39
+ CANCELLED = "Uninstall cancelled. Nothing was deleted."
40
+ REMOVE_PROGRAM = "To finish, remove the program itself with: pipx uninstall imagent-cli (or: pip uninstall imagent-cli, if you used pip)"
41
+
42
+
43
+ # --- Sizes and numbers --------------------------------------------------------
44
+
45
+ def _folder_size(path: Path) -> int:
46
+ """Bytes in the files under ``path`` (links are not followed); 0 if it does not exist."""
47
+ total = 0
48
+ for folder, _, files in os.walk(path):
49
+ for name in files:
50
+ try:
51
+ status = os.lstat(os.path.join(folder, name))
52
+ except OSError:
53
+ continue
54
+ if stat.S_ISREG(status.st_mode):
55
+ total += status.st_size
56
+ return total
57
+
58
+
59
+ def _fmt_bytes(n: float) -> str:
60
+ for unit, size in (("GB", 1e9), ("MB", 1e6), ("KB", 1e3)):
61
+ if n >= size:
62
+ return f"{n / size:.1f} {unit}"
63
+ return f"{int(n)} B"
64
+
65
+
66
+ def _fmt_duration(milliseconds: int) -> str:
67
+ days, rest = divmod(milliseconds // 1000, 86400)
68
+ hours, rest = divmod(rest, 3600)
69
+ minutes, seconds = divmod(rest, 60)
70
+ if days:
71
+ return f"{days} d {hours} h {minutes} min {seconds} s"
72
+ if hours:
73
+ return f"{hours} h {minutes} min {seconds} s"
74
+ return f"{minutes} min {seconds} s" if minutes else f"{seconds} s"
75
+
76
+
77
+ def _style(text: str, code: str) -> str:
78
+ """``text`` with the ANSI style ``code`` when printing to a terminal that understands it, otherwise unchanged."""
79
+ if not sys.stdout.isatty() or os.environ.get("TERM") == "dumb":
80
+ return text
81
+ return f"\033[{code}m{text}\033[0m"
82
+
83
+
84
+ def _bold(text: str) -> str:
85
+ return _style(text, "1")
86
+
87
+
88
+ def _green(text: str) -> str:
89
+ return _style(text, "32")
90
+
91
+
92
+ # --- What is in the database ---------------------------------------------------
93
+
94
+ def read_stats() -> dict:
95
+ """Counts from the index database, read-only. Every value is None when it cannot be read (no database, damaged)."""
96
+ stats = {"images": None, "folders": [], "queued": None, "errors": None, "analysis_ms": None, "locked_models": []}
97
+ if not config.DB_PATH.exists():
98
+ return stats
99
+ try:
100
+ conn = sqlite3.connect(f"{config.DB_PATH.as_uri()}?mode=ro", uri=True, timeout=5)
101
+ except sqlite3.Error:
102
+ return stats
103
+ try:
104
+ for key, sql in (("images", "SELECT COUNT(*) FROM image_data"), ("queued", "SELECT COUNT(*) FROM backlog"),
105
+ ("errors", "SELECT COUNT(*) FROM error_logs"),
106
+ ("analysis_ms", "SELECT COALESCE(SUM(processing_time_ms), 0) FROM image_data")):
107
+ try:
108
+ stats[key] = conn.execute(sql).fetchone()[0]
109
+ except sqlite3.Error:
110
+ pass
111
+ try:
112
+ stats["folders"] = [row[0] for row in conn.execute("SELECT path FROM scan_roots ORDER BY path")]
113
+ except sqlite3.Error:
114
+ pass
115
+ try:
116
+ row = conn.execute("SELECT vlm_model, embedding_model, judge_model FROM model_settings").fetchone()
117
+ stats["locked_models"] = list(dict.fromkeys(row)) if row else []
118
+ except sqlite3.Error:
119
+ pass
120
+ finally:
121
+ conn.close()
122
+ return stats
123
+
124
+
125
+ # --- Ollama (plain HTTP, so no package is needed) --------------------------------
126
+
127
+ def _base_url(host: str) -> str:
128
+ """Same rule as vlm.client: a host with no scheme gets Ollama's port 11434, one with a scheme the scheme's port."""
129
+ has_scheme = "://" in host
130
+ parsed = urlparse(host if has_scheme else f"http://{host}")
131
+ port = parsed.port or (11434 if not has_scheme else 443 if parsed.scheme == "https" else 80)
132
+ name = parsed.hostname or "127.0.0.1"
133
+ return f"{parsed.scheme}://{f'[{name}]' if ':' in name else name}:{port}"
134
+
135
+
136
+ def _is_local(host: str) -> bool:
137
+ parsed = urlparse(host if "://" in host else f"http://{host}")
138
+ return parsed.hostname in ("localhost", "127.0.0.1", "::1")
139
+
140
+
141
+ def _call(base: str, method: str, path: str, body: dict | None = None, timeout: int = 10):
142
+ request = urllib.request.Request(
143
+ f"{base}{path}", method=method, data=None if body is None else json.dumps(body).encode(),
144
+ headers={"Content-Type": "application/json"})
145
+ with urllib.request.urlopen(request, timeout=timeout) as response:
146
+ payload = response.read()
147
+ return json.loads(payload) if payload else {}
148
+
149
+
150
+ def _reachable(base: str) -> bool:
151
+ try:
152
+ _call(base, "GET", "/api/version", timeout=3)
153
+ return True
154
+ except (urllib.error.URLError, OSError, ValueError):
155
+ return False
156
+
157
+
158
+ @contextmanager
159
+ def _ollama(host: str):
160
+ """Yield the server's base URL once Ollama answers, or None. Starts ``ollama serve`` only if needed, and stops it afterwards."""
161
+ base = _base_url(host)
162
+ process = None
163
+ try:
164
+ if not _reachable(base):
165
+ if _is_local(host) and config.ollama_binary():
166
+ try:
167
+ process = subprocess.Popen([config.ollama_binary(), "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
168
+ env=config.ollama_environment(host),
169
+ **background_process_options())
170
+ except OSError:
171
+ process = None
172
+ for _ in range(30 if process else 0):
173
+ if _reachable(base):
174
+ break
175
+ time.sleep(1)
176
+ yield base if _reachable(base) else None
177
+ finally:
178
+ if process is not None:
179
+ process.terminate()
180
+ try:
181
+ process.wait(timeout=10)
182
+ except subprocess.TimeoutExpired:
183
+ process.kill()
184
+
185
+
186
+ def _installed_models(base: str | None) -> dict[str, int] | None:
187
+ """{model name: size in bytes} of what Ollama has, or None if it cannot be asked."""
188
+ if base is None:
189
+ return None
190
+ try:
191
+ return {m["name"]: int(m.get("size") or 0) for m in _call(base, "GET", "/api/tags")["models"]}
192
+ except (urllib.error.URLError, OSError, ValueError, KeyError, TypeError):
193
+ return None
194
+
195
+
196
+ # --- The plan -------------------------------------------------------------------
197
+
198
+ def make_plan(base: str | None, stats: dict) -> dict:
199
+ """Work out what will be removed, and what is left alone and why."""
200
+ recorded = [m for m in config.load_install_record().get("ollama_models", []) if isinstance(m, str)]
201
+ present = _installed_models(base)
202
+ plan = {
203
+ "models": [], "models_unreachable": [], "models_gone": [],
204
+ "not_recorded": [m for m in stats["locked_models"] if m not in recorded],
205
+ "data_dir": config.IMAGENT_HOME if config.IMAGENT_HOME.exists() else None,
206
+ "tools": config.installed_tools(),
207
+ }
208
+ for name in recorded:
209
+ if present is None:
210
+ plan["models_unreachable"].append(name)
211
+ elif name in present:
212
+ plan["models"].append((name, present[name]))
213
+ else:
214
+ plan["models_gone"].append(name)
215
+ plan["data_size"] = _folder_size(plan["data_dir"]) if plan["data_dir"] else 0
216
+ plan["db_size"] = sum(config.DB_PATH.with_name(config.DB_PATH.name + suffix).stat().st_size
217
+ for suffix in ("", "-wal", "-shm")
218
+ if config.DB_PATH.with_name(config.DB_PATH.name + suffix).exists())
219
+ plan["models_size"] = sum(size for _, size in plan["models"])
220
+ return plan
221
+
222
+
223
+ def nothing_to_remove(plan: dict) -> bool:
224
+ return not (plan["data_dir"] or plan["models"])
225
+
226
+
227
+ def show_plan(stats: dict, plan: dict) -> None:
228
+ unknown = "unknown"
229
+ width = 22 # the label column; values and folder paths start right after it
230
+
231
+ def row(label: str, value: str) -> None:
232
+ print(f" {_bold(label)}{' ' * (width - len(label))}{value}")
233
+
234
+ print("\n Uninstalling Imagent deletes all of this, and it cannot be undone.")
235
+ print(f" {_green('Your images are not affected and stay the same.')}\n")
236
+ row("Indexed images", str(stats["images"]) if stats["images"] is not None else unknown)
237
+ folders = stats["folders"]
238
+ row("Scanned folders", str(len(folders)) if folders or stats["images"] is not None else unknown)
239
+ for folder in folders:
240
+ print(f" {' ' * width}{folder}")
241
+ row("Total time analyzed", _fmt_duration(stats["analysis_ms"]) if stats["analysis_ms"] is not None else unknown)
242
+ row("Storage used", _fmt_bytes(plan["data_size"] + plan["models_size"]))
243
+ if plan["models_unreachable"]:
244
+ print("\n Could not reach Ollama, so these models will NOT be removed (remove them yourself with")
245
+ print(" `ollama rm <name>` on the computer where Ollama runs): " + ", ".join(plan["models_unreachable"]))
246
+ if plan["not_recorded"]:
247
+ print("\n Not removed, because Imagent has no record of downloading them (you may have had them, or")
248
+ print(" they were downloaded before Imagent kept a record): " + ", ".join(plan["not_recorded"]))
249
+ print(" To remove one yourself: ollama rm <name>")
250
+
251
+
252
+ # --- Three confirmations ------------------------------------------------------------
253
+
254
+ def make_final_code() -> str:
255
+ """A new random string of letters and digits, typed in the last confirmation so it cannot be answered from habit."""
256
+ alphabet = string.ascii_letters + string.digits
257
+ return "".join(secrets.choice(alphabet) for _ in range(FINAL_CODE_LENGTH))
258
+
259
+
260
+ def confirm_three_times(stats: dict) -> bool:
261
+ """Ask three different questions; any wrong answer cancels everything."""
262
+ print(f"\n {_bold('Confirmation')}")
263
+ if input(" 1/3 Do you want to uninstall Imagent and delete everything above? Type yes: ").strip().lower() != "yes":
264
+ return False
265
+ expected = str(stats["images"] if stats["images"] is not None else 0)
266
+ if input(" 2/3 How many indexed images will be lost? (see the list above): ").strip() != expected:
267
+ print(" That is not the number in the list.")
268
+ return False
269
+ code = make_final_code()
270
+ if input(f" 3/3 This is the last chance. Type exactly \"{code}\": ").strip() != code:
271
+ return False
272
+ return True
273
+
274
+
275
+ # --- Deleting -----------------------------------------------------------------------
276
+
277
+ def _remove_tree(path: Path) -> bool:
278
+ """Delete a folder, clearing read-only flags (Windows) and retrying. Returns whether it is gone."""
279
+ def clear_and_retry(function, target, _):
280
+ try:
281
+ os.chmod(target, stat.S_IWRITE)
282
+ function(target)
283
+ except OSError:
284
+ pass
285
+ option = {"onexc": clear_and_retry} if sys.version_info >= (3, 12) else {"onerror": clear_and_retry}
286
+ shutil.rmtree(path, **option)
287
+ return not path.exists()
288
+
289
+
290
+ def delete_everything(plan: dict, base: str | None) -> list[str]:
291
+ """Do the deleting, one step at a time, and return the problems (empty when everything went well)."""
292
+ problems = []
293
+ for name, _ in plan["models"]:
294
+ try:
295
+ _call(base, "DELETE", "/api/delete", {"model": name}, timeout=120)
296
+ print(f" ✓ Removed the Ollama model {name}")
297
+ except (urllib.error.URLError, OSError, ValueError) as exc:
298
+ problems.append(f"Could not remove the Ollama model {name} ({exc}). Remove it with: ollama rm {name}")
299
+ if plan["data_dir"]:
300
+ if config.IMAGENT_HOME.name.lstrip(".").lower() != "imagent": # (the folder is ~/.imagent) never delete a folder this program did not name itself
301
+ problems.append("Did not delete the data folder: it is not named like Imagent's own folder.")
302
+ elif _remove_tree(config.IMAGENT_HOME):
303
+ print(" ✓ Deleted the data folder")
304
+ else:
305
+ problems.append("Could not delete everything in the data folder. Delete the folder yourself.")
306
+ return problems
307
+
308
+
309
+ # --- Programs setup installed (asked about last) -----------------------------------------
310
+
311
+ def offer_tool_removal(tools: list[dict]) -> list[str]:
312
+ """For each program setup installed, say what it is and ask whether to remove it too. Returns the problems.
313
+
314
+ Removing one is deleting its folder in the tools folder, so nothing else on the computer can be touched."""
315
+ problems = []
316
+ for tool in tools:
317
+ path = tool["path"]
318
+ version = f" {tool['version']}" if tool["version"] else ""
319
+ print(f"\n {_bold(tool['name'] + version)}: {tool['description']}")
320
+ print(f" It takes {_fmt_bytes(_folder_size(path))} at {path}")
321
+ if input(f" Remove {tool['name']} too? [y/N]: ").strip().lower() not in ("y", "yes"):
322
+ print(f" {tool['name']} was kept. To remove it later, delete the folder {path}")
323
+ elif path.resolve().parent != config.TOOLS_DIR.resolve(): # never delete a folder outside the tools folder
324
+ problems.append(f"Did not remove {tool['name']}: its folder is not inside Imagent's tools folder. Delete {path} yourself.")
325
+ elif _remove_tree(path):
326
+ print(f" ✓ Removed {tool['name']}")
327
+ else:
328
+ problems.append(f"Could not remove everything of {tool['name']}. Delete the folder {path} yourself.")
329
+ try:
330
+ config.TOOLS_DIR.rmdir() # only succeeds when nothing is left in it
331
+ except OSError:
332
+ pass
333
+ return problems
334
+
335
+
336
+ # --- Entry point -------------------------------------------------------------------------
337
+
338
+ def main() -> None:
339
+ make_output_safe()
340
+ if not sys.stdin.isatty():
341
+ sys.exit("Uninstalling needs an interactive terminal. Run: imagent uninstall")
342
+
343
+ stats = read_stats()
344
+ host = config.load_config().get("ollama_host") or DEFAULT_HOST
345
+ print("\n Looking at what Imagent has added…")
346
+ with _ollama(host) as base:
347
+ plan = make_plan(base, stats)
348
+ if nothing_to_remove(plan):
349
+ if not plan["tools"]:
350
+ print("\n Nothing to uninstall: Imagent has not added anything to this computer (or it was already removed).")
351
+ print(f" {REMOVE_PROGRAM}")
352
+ return
353
+ print("\n Imagent's data and models are already removed.")
354
+ problems = []
355
+ else:
356
+ show_plan(stats, plan)
357
+ if not confirm_three_times(stats):
358
+ sys.exit(f"\n{CANCELLED}")
359
+ if config.IMAGENT_HOME.exists():
360
+ try:
361
+ with single_instance("indexing", "Indexing"): # deleting under a running index would make it fail on every image
362
+ pass
363
+ except AlreadyRunning as exc:
364
+ sys.exit(f"\n{exc} Nothing was deleted.")
365
+ print()
366
+ problems = delete_everything(plan, base)
367
+
368
+ problems += offer_tool_removal(plan["tools"]) # after the block above, so a server started only for the models is stopped first
369
+
370
+ print()
371
+ if problems:
372
+ print(" Finished, with problems:")
373
+ for problem in problems:
374
+ print(f" ✗ {problem}")
375
+ else:
376
+ print(" ✓ Imagent is uninstalled.")
377
+ print(f" {REMOVE_PROGRAM}")
378
+ sys.exit(1 if problems else 0)
379
+