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
imagent/vlm/client.py ADDED
@@ -0,0 +1,302 @@
1
+ """
2
+ imagent/vlm/client.py — The Ollama client (with timeouts) and the readiness check run before every
3
+ indexing or search session.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import atexit
9
+ import io
10
+ import signal
11
+ import subprocess
12
+ import sys
13
+ import time
14
+ from urllib.parse import urlparse
15
+
16
+ import httpx
17
+ import ollama
18
+ from PIL import Image
19
+
20
+ from imagent import config
21
+ from imagent.db.operations import get_device_settings, get_model_settings
22
+ from imagent.os_specific.process import background_process_options
23
+
24
+
25
+ _FIRST_POLL_PAUSE = 0.2 # seconds between the first questions to a server that was just started; it doubles up to one second
26
+
27
+ # Structured output (the JSON schema sent with each request) arrived in Ollama 0.5.0.
28
+ MIN_OLLAMA_VERSION = (0, 5, 0)
29
+
30
+
31
+ class NotReady(Exception):
32
+ """Setup is incomplete or Ollama cannot serve the locked models; the message tells the user what to do."""
33
+
34
+
35
+ def check_pictures_readable() -> None:
36
+ """Confirm Pillow can write and read back a picture, so a broken install stops a run before it starts and does not fail on every image.
37
+
38
+ Done in memory: nothing is written to disk. Raises NotReady otherwise."""
39
+ try:
40
+ buffer = io.BytesIO()
41
+ Image.new("RGB", (2, 2)).save(buffer, "PNG")
42
+ buffer.seek(0)
43
+ Image.open(buffer).load()
44
+ except Exception as exc:
45
+ raise NotReady(f"Pillow, the library Imagent reads pictures with, does not work on this computer ({type(exc).__name__}: {exc}). "
46
+ "Reinstall Imagent: pipx reinstall imagent.") from exc
47
+
48
+
49
+ def make_client(host: str | None = None, timeout: float | None = None) -> ollama.Client:
50
+ """Return an Ollama client that can never wait forever.
51
+
52
+ ``host`` defaults to the one saved by setup, ``timeout`` (seconds to wait for a reply) to ``config.OLLAMA_TIMEOUT``.
53
+ The read timeout also applies between the progress updates of a download, so a stalled download ends too.
54
+ """
55
+ timeout = httpx.Timeout(timeout or config.OLLAMA_TIMEOUT, connect=config.OLLAMA_CONNECT_TIMEOUT)
56
+ return ollama.Client(host=host or config.OLLAMA_HOST, timeout=timeout)
57
+
58
+
59
+ def is_local(host: str) -> bool:
60
+ """True if ``host`` is this machine, the only kind of Ollama server Imagent can start."""
61
+ parsed = urlparse(host if "://" in host else f"http://{host}")
62
+ return parsed.hostname in ("localhost", "127.0.0.1", "::1")
63
+
64
+
65
+ def is_reachable(client: ollama.Client) -> bool:
66
+ """True if the Ollama server answers."""
67
+ try:
68
+ client.list()
69
+ return True
70
+ except Exception:
71
+ return False
72
+
73
+
74
+ def _base_url(host: str) -> str:
75
+ """The address the Ollama client uses for ``host``: a host with no scheme gets port 11434, one with a scheme the scheme's port."""
76
+ has_scheme = "://" in host
77
+ parsed = urlparse(host if has_scheme else f"http://{host}")
78
+ port = parsed.port or (11434 if not has_scheme else 443 if parsed.scheme == "https" else 80)
79
+ name = parsed.hostname or "127.0.0.1"
80
+ return f"{parsed.scheme}://{f'[{name}]' if ':' in name else name}:{port}"
81
+
82
+
83
+ def short_error(exc: BaseException, limit: int = 200) -> str:
84
+ """``exc`` in one short line, for a message to the user: the kind of error and what it said, which can be a whole web page when
85
+ another program answers at Ollama's address (shown as a sentence instead), or long, which is cut."""
86
+ text = " ".join(str(exc).split())
87
+ if "<html" in text.lower() or "<!doctype" in text.lower():
88
+ return f"{type(exc).__name__}: another program answered at this address with a web page, not Ollama"
89
+ return f"{type(exc).__name__}: {text if len(text) <= limit else text[:limit].rstrip() + '…'}"
90
+
91
+
92
+ def server_version(host: str) -> tuple[int, ...] | None:
93
+ """The version of the Ollama server at ``host`` as numbers, e.g. (0, 6, 4); None if it cannot be told.
94
+
95
+ A development build reports 0.0.0, which says nothing, so it is None too.
96
+ """
97
+ try:
98
+ reply = httpx.get(f"{_base_url(host)}/api/version", timeout=config.OLLAMA_CONNECT_TIMEOUT)
99
+ version = tuple(int(part) for part in reply.json()["version"].split("-")[0].split(".")[:3])
100
+ except Exception:
101
+ return None
102
+ return version if any(version) else None
103
+
104
+
105
+ def _exit_on_signal(signum, frame) -> None:
106
+ sys.exit(128 + signum) # a normal exit, so ``atexit`` and ``finally`` blocks run and the server is stopped
107
+
108
+
109
+ def _stop_server_when_killed() -> None:
110
+ """Make a closed terminal (SIGHUP) or a plain ``kill`` (SIGTERM) end the program normally instead of abruptly."""
111
+ for name in ("SIGTERM", "SIGHUP"): # SIGHUP does not exist on Windows
112
+ number = getattr(signal, name, None)
113
+ if number is not None:
114
+ try:
115
+ signal.signal(number, _exit_on_signal)
116
+ except ValueError: # not the main thread
117
+ pass
118
+
119
+
120
+ def start_server(client: ollama.Client, host: str | None = None, wait_seconds: int = 30) -> subprocess.Popen | None:
121
+ """Start ``ollama serve`` in the background, on the address of ``host`` (default: the one saved by setup), and wait until it answers.
122
+
123
+ Returns the process, or None if the command could not be run, the server ended by itself, or it never answered within
124
+ ``wait_seconds`` (it is stopped again in that case). The caller must stop the process with ``stop_server``.
125
+ A terminal closed or a ``kill`` while it runs also stops it.
126
+ """
127
+ host = host or config.OLLAMA_HOST
128
+ try:
129
+ process = subprocess.Popen([config.ollama_binary() or "ollama", "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
130
+ env=config.ollama_environment(host), **background_process_options())
131
+ except OSError:
132
+ return None
133
+ _stop_server_when_killed()
134
+ deadline = time.monotonic() + wait_seconds
135
+ pause = _FIRST_POLL_PAUSE
136
+ while True:
137
+ if process.poll() is not None: # it ended by itself (the port is taken, it crashed): waiting longer would only wait for nothing
138
+ return None
139
+ if is_reachable(client):
140
+ return process
141
+ if time.monotonic() >= deadline:
142
+ break
143
+ time.sleep(pause)
144
+ pause = min(pause * 2, 1.0) # a server that is quick to start is noticed quickly; a slow one is asked about once a second
145
+ stop_server(process)
146
+ return None
147
+
148
+
149
+ def stop_server(process: subprocess.Popen) -> None:
150
+ """Stop a server started with ``start_server``."""
151
+ process.terminate()
152
+ try:
153
+ process.wait(timeout=10)
154
+ except subprocess.TimeoutExpired:
155
+ process.kill()
156
+
157
+
158
+ def restart_server(client: ollama.Client) -> bool:
159
+ """Make sure the Ollama server answers, starting it again if it went down (only possible when it is on this computer).
160
+
161
+ The server this starts is stopped when the program ends. True if the server answers.
162
+ """
163
+ if is_reachable(client):
164
+ return True
165
+ if not (is_local(config.OLLAMA_HOST) and config.ollama_binary()):
166
+ return False
167
+ process = start_server(client, config.OLLAMA_HOST)
168
+ if process is None:
169
+ return False
170
+ atexit.register(_stop_started_server, process)
171
+ return True
172
+
173
+
174
+ def _stop_started_server(process: subprocess.Popen) -> None:
175
+ stop_server(process)
176
+
177
+
178
+ def check_ready(conn, roles: tuple[str, ...]) -> tuple[ollama.Client, dict]:
179
+ """Confirm setup is done and Ollama is reachable with the locked models for ``roles`` installed.
180
+
181
+ ``roles`` are the models this run uses: ("vlm", "embedding") to index, ("judge", "embedding") to search.
182
+ Returns the client and the locked model settings (names, digests, embedding_dim).
183
+ Raises NotReady otherwise, so a run stops at once instead of failing on every image. Every model is locked: one that is
184
+ not exactly the version set up (its digest changed) stops the run too.
185
+
186
+ If Ollama is not running and the host is this machine, it is started here and stopped
187
+ again when the program exits.
188
+ """
189
+ check_pictures_readable()
190
+ settings = get_model_settings(conn)
191
+ if settings is None:
192
+ raise NotReady(f"Imagent is not set up yet. Run: {config.SETUP_COMMAND}")
193
+ device = get_device_settings(conn)
194
+ if device is None:
195
+ raise NotReady(f"Imagent has not measured this computer yet. Run: {config.SETUP_COMMAND}; it does that by itself.")
196
+ config.apply_device_settings(device)
197
+ if not config.OLLAMA_HOST:
198
+ raise NotReady("Imagent's settings file (config.json) is missing or damaged, so it does not know where Ollama is. "
199
+ f"Run: {config.SETUP_COMMAND}. It restores the address; your models and index are kept.")
200
+ if not is_local(config.OLLAMA_HOST):
201
+ raise NotReady(f"Imagent only works with an Ollama that runs on this computer, but config.json points to {config.OLLAMA_HOST}. "
202
+ f"Run: {config.SETUP_COMMAND}. It restores the local address; your models and index are kept.")
203
+
204
+ client = make_client()
205
+ if not is_reachable(client) and is_local(config.OLLAMA_HOST) and config.ollama_binary():
206
+ process = start_server(client, config.OLLAMA_HOST)
207
+ if process is not None:
208
+ atexit.register(_stop_started_server, process)
209
+ try:
210
+ installed = {model.model: model.digest for model in client.list().models}
211
+ except Exception as exc:
212
+ install_hint = (f" Ollama is not installed. Run: {config.SETUP_COMMAND}; it installs Ollama."
213
+ if is_local(config.OLLAMA_HOST) and not config.ollama_binary() else " Start Ollama and try again.")
214
+ raise NotReady(f"Cannot reach Ollama at {config.OLLAMA_HOST} ({short_error(exc)}).{install_hint}") from exc
215
+
216
+ version = server_version(config.OLLAMA_HOST)
217
+ if version is not None and version < MIN_OLLAMA_VERSION:
218
+ raise NotReady(
219
+ f"Your Ollama is version {'.'.join(map(str, version))}, which is too old: Imagent needs "
220
+ f"{'.'.join(map(str, MIN_OLLAMA_VERSION))} or newer. Update it from https://ollama.com/download and try again."
221
+ )
222
+
223
+ for role in roles:
224
+ name = settings[f"{role}_model"]
225
+ digest = installed.get(name)
226
+ if digest is None:
227
+ raise NotReady(f"The {role} model '{name}' is not installed in Ollama. Run: {config.SETUP_COMMAND}")
228
+ stored = settings[f"{role}_digest"]
229
+ if stored and digest != stored:
230
+ effect = ("Vectors made by another version cannot be compared with the ones already stored, so searches would miss "
231
+ "images and new images would be indexed wrongly." if role == "embedding" else
232
+ "Imagent's results depend on the exact models it was set up with.")
233
+ raise NotReady(
234
+ f"The {role} model '{name}' is not the same version it was when you set up Imagent. {effect} "
235
+ "The models are locked and cannot be changed: put the original version of the model back "
236
+ f"(running {config.SETUP_COMMAND} restores it when it can), or uninstall Imagent and set it up again, which clears the index.")
237
+ if role == "vlm":
238
+ try:
239
+ abilities = client.show(name).capabilities
240
+ except Exception:
241
+ abilities = None # an Ollama that cannot say: setup already checked this model
242
+ if isinstance(abilities, list) and "vision" not in abilities:
243
+ raise NotReady(f"The vision model '{name}' cannot look at images (Ollama lists its abilities as: "
244
+ f"{', '.join(abilities) or 'none'}). Imagent cannot index with it.")
245
+ return client, settings
246
+
247
+
248
+ # A model that setup copies under a name of its own, so that pulling a newer version of the original cannot change what
249
+ # Imagent uses: Ollama keeps the old files for as long as the copy exists.
250
+ PIN_PREFIX = "imagent-pin/"
251
+
252
+
253
+ def is_pinned(name: str) -> bool:
254
+ return name.startswith(PIN_PREFIX)
255
+
256
+
257
+ def pinned_name(model: str, digest: str) -> str:
258
+ """The name of the copy of ``model`` (as it is now, by its digest), e.g. ``imagent-pin/bge-m3:3a1f9c2d7e11``."""
259
+ return f"{PIN_PREFIX}{model.split(':')[0].split('/')[-1]}:{digest.split(':')[-1][:12]}"
260
+
261
+
262
+ def pin_model(client: ollama.Client, model: str) -> tuple[str, str]:
263
+ """Copy ``model`` under its pinned name unless that copy exists. Returns the pinned name and the digest of its weights."""
264
+ digests = {installed.model: installed.digest for installed in client.list().models}
265
+ digest = digests[model]
266
+ target = pinned_name(model, digest)
267
+ if target not in digests:
268
+ client.copy(model, target)
269
+ return target, digest
270
+
271
+
272
+ def other_models_running(client: ollama.Client, keep: list[str]) -> list[str]:
273
+ """The names of the models Ollama has in memory right now that are not in ``keep``.
274
+
275
+ Best effort: if Ollama cannot say, the answer is none.
276
+ """
277
+ try:
278
+ return [model.model for model in client.ps().models if model.model not in keep]
279
+ except Exception:
280
+ return []
281
+
282
+
283
+ def load_model(client: ollama.Client, name: str, embedding: bool = False) -> None:
284
+ """Ask Ollama to load a model into memory now (best effort), so the first request does not wait for it.
285
+
286
+ Uses the same options as the real requests, so Ollama keeps the model it loaded here.
287
+ """
288
+ try:
289
+ if embedding:
290
+ client.embed(model=name, input=["warm up"], options=config.EMBED_OPTIONS)
291
+ else:
292
+ client.generate(model=name, prompt="", options=config.LLM_OPTIONS)
293
+ except Exception:
294
+ pass # the real request reports any problem with its own message
295
+
296
+
297
+ def unload_model(client: ollama.Client, name: str) -> None:
298
+ """Ask Ollama to free a model's memory now (best effort), so the next phase has room for its own models."""
299
+ try:
300
+ client.generate(model=name, prompt="", keep_alive=0)
301
+ except Exception:
302
+ pass # only an optimisation; Ollama unloads idle models by itself
@@ -0,0 +1,72 @@
1
+ """
2
+ imagent/vlm/reply_validation.py — Check the vision model's reply against the JSON schema, without knowing any field.
3
+
4
+ The schema (``config.ANALYSIS_SCHEMA``) is sent to Ollama, which already holds the reply to it while it is being
5
+ written, so what is checked here is what can still go wrong: a reply that was cut off, is not an object, lacks a
6
+ required field, has a field of the wrong type, or says nothing at all. A reply that passes is used exactly as the model
7
+ wrote it; nothing is trimmed, dropped or filled in.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+
14
+ _TYPES = {"string": str, "boolean": bool, "array": list, "object": dict, "null": type(None)}
15
+
16
+
17
+ def _type_matches(value, name: str) -> bool:
18
+ if name == "integer":
19
+ return isinstance(value, int) and not isinstance(value, bool)
20
+ if name == "number":
21
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
22
+ return isinstance(value, _TYPES[name])
23
+
24
+
25
+ def _check(value, schema: dict, path: str, found: list[str]) -> None:
26
+ expected = schema.get("type")
27
+ if expected is not None:
28
+ names = expected if isinstance(expected, list) else [expected]
29
+ if not any(_type_matches(value, name) for name in names):
30
+ found.append(f"{path}: expected {' or '.join(names)}")
31
+ return
32
+ if "enum" in schema and value not in schema["enum"]:
33
+ found.append(f"{path}: must be one of {schema['enum']}")
34
+ if isinstance(value, dict):
35
+ for key in schema.get("required", []):
36
+ if key not in value:
37
+ found.append(f"{path}.{key}: missing")
38
+ for key, sub_schema in schema.get("properties", {}).items():
39
+ if key in value:
40
+ _check(value[key], sub_schema, f"{path}.{key}", found)
41
+ if isinstance(value, list) and "items" in schema:
42
+ for index, item in enumerate(value):
43
+ _check(item, schema["items"], f"{path}[{index}]", found)
44
+
45
+
46
+ def _says_nothing(value) -> bool:
47
+ """True if no text is found anywhere in ``value``."""
48
+ if isinstance(value, str):
49
+ return not value.strip()
50
+ if isinstance(value, dict):
51
+ return all(_says_nothing(item) for item in value.values())
52
+ if isinstance(value, list):
53
+ return all(_says_nothing(item) for item in value)
54
+ return True
55
+
56
+
57
+ def check_reply(text: str | None, schema: dict) -> tuple[dict | None, list[str]]:
58
+ """Return ``(reply, [])`` if ``text`` is a JSON object that fits ``schema``, else ``(None, problems)``.
59
+
60
+ ``problems`` say what is wrong, in words that can be sent back to the model.
61
+ """
62
+ try:
63
+ value = json.loads(text or "")
64
+ except ValueError as exc:
65
+ return None, [f"reply: not valid JSON ({exc})"]
66
+ found: list[str] = []
67
+ if not isinstance(value, dict):
68
+ return None, ["reply: expected a JSON object"]
69
+ _check(value, schema, "reply", found)
70
+ if not found and _says_nothing(value):
71
+ found.append("reply: every field is empty")
72
+ return (None if found else value), found
@@ -0,0 +1,7 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class QueryUnderstanding(BaseModel):
5
+ normalized_query: str
6
+ required_details: list[str]
7
+ hypothetical_description: str
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: imagent-cli
3
+ Version: 0.1.0
4
+ Summary: Local image indexing and search tool: private, offline, and cross-platform.
5
+ Author-email: Divakar Mahanthi <divakarnaidumahanthi@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/the-walkerrr/Imagent
8
+ Project-URL: Source, https://github.com/the-walkerrr/Imagent
9
+ Project-URL: Issues, https://github.com/the-walkerrr/Imagent/issues
10
+ Project-URL: Changelog, https://github.com/the-walkerrr/Imagent/blob/main/CHANGELOG.md
11
+ Keywords: image search,photo search,semantic search,vision language model,ollama,ocr,offline,privacy
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: Microsoft :: Windows
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Multimedia :: Graphics
25
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: pydantic>=2.0.0
30
+ Requires-Dist: ollama>=0.6.0
31
+ Requires-Dist: httpx>=0.27.0
32
+ Requires-Dist: questionary>=2.0.0
33
+ Requires-Dist: Pillow>=10.0.0
34
+ Requires-Dist: pillow-heif>=1.0.0
35
+ Requires-Dist: numpy>=1.24.0
36
+ Requires-Dist: rapidocr>=3.10.0
37
+ Requires-Dist: onnxruntime>=1.16.0
38
+ Requires-Dist: zstandard>=0.23.0
39
+ Provides-Extra: dev
40
+ Requires-Dist: build; extra == "dev"
41
+ Requires-Dist: twine; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # Imagent (Beta)
45
+
46
+ **Local image indexing and search tool.**
47
+
48
+ - **Private:** everything runs on your computer, and your images never leave it.
49
+ - **Offline:** after setup, no internet connection is needed.
50
+ - **Cross-platform:** macOS, Linux and Windows.
51
+ - **Wide format support:** JPG, PNG, WebP, HEIC/HEIF, BMP, TIFF, GIF and AVIF.
52
+
53
+ ## Requirements
54
+
55
+ Python 3.11 or newer (tested on 3.11 to 3.14). You do not need to install [Ollama](https://ollama.com) yourself: setup installs its own copy for Imagent when the computer has none (see below).
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install imagent-cli
61
+ ```
62
+
63
+ This adds the `imagent` command to your computer. If `pip` is not found, use `python3 -m pip install imagent-cli` (Windows: `py -m pip install imagent-cli`).
64
+
65
+ If pip stops with `externally-managed-environment` (common with Homebrew Python on macOS and with recent Linux distributions, which do not allow installs into the system Python), install it with [pipx](https://pipx.pypa.io) instead, which gives `imagent` its own hidden environment and still makes the command available everywhere:
66
+
67
+ ```bash
68
+ pipx install imagent-cli
69
+ ```
70
+
71
+ To work on Imagent itself, see [CONTRIBUTING.md](CONTRIBUTING.md).
72
+
73
+ Then set it up (once). It checks Ollama (and installs it if needed), downloads the three models, locks them, downloads a small set of test pictures (23 MB, once) to check that your computer can read them, measures your computer and asks how many deleted pictures to remember (see below):
74
+
75
+ ```bash
76
+ imagent setup
77
+ ```
78
+
79
+ ## Use
80
+
81
+ ```bash
82
+ imagent search "red car at night" # show the pictures that best match a description
83
+ imagent search # keep searching until you type exit
84
+ imagent search --full "red car" # show each result's full description instead of its one-line summary (--short for the summary)
85
+ imagent add ~/Pictures # add a folder, then choose what to do next: scan and index it, add another, delete folders, search
86
+ imagent add # the same, picking the folder from suggestions as you type
87
+ imagent scan # scan every folder you added, then index what is pending (asks for a folder if none is added yet)
88
+ imagent delete ~/Pictures # remove a folder from the scan list and what was indexed from it (several folders can be given; quote a path with spaces)
89
+ imagent delete # the same, ticking the folders to remove from the scan list
90
+ imagent failed # list the pictures that could not be indexed, and why
91
+ imagent forget # delete what Imagent remembers about deleted pictures (two confirmations)
92
+ imagent settings # change the settings below from a menu, or uninstall
93
+ imagent help # explain each command briefly
94
+ imagent # open a menu (arrow keys and Enter) with the common choices
95
+ ```
96
+
97
+ `imagent --help` lists the commands. To index: run `imagent add` with a folder, or without one to pick it from a list, then choose "Scan and index this folder" (the menu comes back after each choice, so you can add more folders), then `imagent search`. Run `imagent scan` later to bring all of them up to date.
98
+
99
+ ## Settings
100
+
101
+ `imagent settings` (also in the menu) changes these, each picked from a list; they are kept in the index database:
102
+
103
+ - **Deleted pictures Imagent remembers:** none, 100, 500 (the default), 1000, 2000 or 5000. Choosing fewer than are remembered now forgets the oldest ones, after asking.
104
+ - **Search results show:** the one-line summary (the default) or the whole description. `imagent search --full` and `--short` change it for one search.
105
+
106
+ The models and what setup measured about your computer are not settings: they are locked at setup (see below). Uninstall is in the settings menu too.
107
+
108
+ ## Pictures that come back
109
+
110
+ A picture is recognised by its pixels, whatever its name, folder or embedded details (EXIF) are. The vision model looks at each picture once:
111
+
112
+ - **Copies and renames:** a new file with the same pixels as a picture already indexed gets that picture's description and search data again, so it is not analysed a second time. A renamed or moved file keeps its index, also when it was moved into another folder you added, whichever of the two folders is scanned first.
113
+ - **Deleted pictures:** when a scan finds that a picture was deleted, Imagent can remember what it learned about it (its description and search data; not the picture, and not where it was). If the same picture comes back later (restored from a backup, copied, or moved into a folder you add later), it is not analysed again. Search never shows remembered pictures.
114
+
115
+ Setup asks how many deleted pictures to remember: pick one from the list (none, 100, 500, 1000, 2000 or 5000). When there are more than that, the oldest are forgotten first. Until you have answered, nothing is remembered. To delete what is remembered now, run `imagent forget` (or choose it in the menu); your indexed pictures and your choice are not touched.
116
+
117
+ When copies of one picture are indexed (in one folder or several), a search shows them as one result and lists where the other copies are, so its results are different pictures. Deleting a folder does not keep the analysis of a picture whose copy is still indexed in another folder: it is still in use.
118
+
119
+ A picture with transparent parts is shown to the model, and to the text reader, on a white background, as an image viewer shows it. A picture Imagent is not allowed to read (its permissions) is set aside with a message saying so, and tried again on every scan, so allowing it to be read is enough. The scan summary counts pictures that could not be indexed on a line of their own ("Failed"), not as waiting to be indexed.
120
+
121
+ A description is only used again when it was made with the same models, prompt and text-reading engine as a new one would be; otherwise the picture is analysed again.
122
+
123
+ ## When a model does not fit your computer
124
+
125
+ Setup tries each model for real. If one cannot run here, or cannot write a description in the form Imagent needs, setup says which one, removes what it downloaded for it (a model that was already on your computer is never removed) and asks again; the prompt you copy for an AI chat then lists the models that already failed.
126
+
127
+ If a picture cannot be indexed because Ollama ran out of memory, stopped or did not reply in time, `imagent scan` lists those pictures and why, and asks whether to try them again with lower settings (a longer wait, the model paged in from disk, a smaller picture). The lower settings apply only to those pictures, each by what went wrong with it; your usual settings do not change. The default answer is no.
128
+
129
+ ## The models are locked
130
+
131
+ `imagent setup` saves a private copy of each of the three models (vision, text and embedding), so a later `ollama pull` cannot change them. Different embedding models give different vectors for the same text, so changing a model would break every search of what is already indexed. To use other models, uninstall Imagent and set it up again (this clears the index).
132
+
133
+ ## Where your data lives
134
+
135
+ Everything is in `~/.imagent` (on Windows, `.imagent` in your user folder), on every OS.
136
+
137
+ Holds `imagent.db` (the index), `config.json`, `install_record.json` (what setup added, so uninstall removes only that) and `last_error.log`.
138
+
139
+ ## Ollama
140
+
141
+ If `imagent setup` finds no Ollama, or one that is too old, it downloads Ollama's official build for your computer into a folder of its own next to the data folder, with no administrator rights, no package manager and no change to `PATH`. The download is large, so make sure there is enough free disk space. Every file is checked against Ollama's published checksums, and those are checked against a checksum built into Imagent. This copy is used only by Imagent, and it keeps its models there too. An Ollama you already have, if it is recent enough, is used as it is and nothing is installed.
142
+
143
+ Imagent's own Ollama is in `~/.imagent-tools/ollama` (on Windows, `.imagent-tools\ollama` in your user folder), on every OS.
144
+
145
+ The copy has no GPU drivers, so an NVIDIA GPU is used only if its driver is already installed. For an AMD GPU (Linux or Windows) or an NVIDIA Jetson board, setup also downloads the extra files Ollama publishes for it. A computer with an NVIDIA GPU gets no extra files, even when it has an AMD one too, and neither does a Mac.
146
+
147
+ ## Uninstall
148
+
149
+ ```bash
150
+ imagent uninstall # (or Uninstall in `imagent settings`) deletes the index, the data folder and the models Imagent downloaded (three confirmations), then asks whether to remove Imagent's own Ollama too
151
+ pip uninstall imagent-cli # removes the program itself
152
+ ```
153
+
154
+ Your pictures, an Ollama you installed yourself and any model you had before Imagent are never touched. Imagent's own Ollama is removed only if you answer yes (the default is to keep it); you can delete its folder yourself at any time.
155
+
156
+ ## Troubleshooting
157
+
158
+ | Message | What to do |
159
+ | --- | --- |
160
+ | `Imagent is not set up yet` | Run `imagent setup`. |
161
+ | `No indexed images found` | Run `imagent add` with a folder first. |
162
+ | `The ... model ... is not the same version` | The models are locked. Put the original version back (`imagent setup` restores it when it can), or uninstall and set up again, which clears the index. |
163
+ | `...is on a network drive` / `...external or removable drive` | Copy the pictures to your computer's own disk. |
164
+
165
+ ## Contributing
166
+
167
+ Bug reports and pull requests are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md) for how to set up, run the tests and send a change. Changes by version are in [CHANGELOG.md](CHANGELOG.md). To report a security problem, see [SECURITY.md](SECURITY.md).
168
+
169
+ ## License
170
+
171
+ Imagent is released under the [MIT License](LICENSE). The test pictures that setup downloads are public-domain or CC0 photographs from Wikimedia Commons; their sources and authors are in the `manifest.json` inside the download.
@@ -0,0 +1,68 @@
1
+ imagent/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ imagent/__main__.py,sha256=-_6YLn8ccLCHf6N_uq5mayHWeO2u1HlaEvszCui9K3M,128
3
+ imagent/cli.py,sha256=VzS-D14jt8JuokS-l-ps1F3pkfqz8fDnblPR1miOaqI,8145
4
+ imagent/config.py,sha256=GnMZzKNq8X7-DnCZ-XUgPAVXuFAfpB_XRFtzvvnkBTI,20171
5
+ imagent/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ imagent/commands/after_add.py,sha256=U8gKUnJUUNoabc-oglR6euFv7pYK7EOvy1FvlfZmNZE,3776
7
+ imagent/commands/delete.py,sha256=oE3rRr3Cx8ry9FUg75efzO2ruO5ltUWN_BWqe0ZCCbQ,10698
8
+ imagent/commands/failed.py,sha256=Q_VDAHtz9dn-QsV_el74ocUKXX-zX7sk5qUr4R2Vgsc,727
9
+ imagent/commands/forget.py,sha256=58MiUB6qDj0SyayxY5_NUnc-PIPxuqQ9AVHtHk65jBM,2942
10
+ imagent/commands/help.py,sha256=56Xx9V5mYQUdL1Tj_KY41txGSALny8C62Zhl-9WALgE,4810
11
+ imagent/commands/menu.py,sha256=lFgGoTcJbYGAExec8uqI4dxytfdwdGkXWWonz4WTBxQ,6469
12
+ imagent/commands/scan.py,sha256=XNDfaNw30MseFLn7X-IdwDHnI9tp75ER6MHw42bJuD0,72076
13
+ imagent/commands/search.py,sha256=OTCbCR_vMzEgc3KzGdAo1Iban_792xOS7qzl6qqvQCA,21538
14
+ imagent/commands/settings.py,sha256=YimLcQAkhQdnYuJdenT-MIrdy6ejLmtaqEim7rUuqzE,7163
15
+ imagent/commands/setup.py,sha256=z5hSNtJfvssLl65QqEk5CKjdAYpKVb4UtjjZC9v9YQ8,72742
16
+ imagent/commands/uninstall.py,sha256=_oAvvx9GonqllDXW7CcIZ4vpdnX6ZZ03pN8MSqruocI,16410
17
+ imagent/db/__init__.py,sha256=SMiJDPTgF7Nlgz9-AAlxFt82au4cshEmuDhPjfNJEvo,13
18
+ imagent/db/connection.py,sha256=AB33iZts3bifFWd9SYKxeGL6AKhaQqLvMoiyuNSQHUA,10532
19
+ imagent/db/operations.py,sha256=zuITwFbVMkhjem16BsUyuOZ6JkuhIizuMXStX0TnxR0,35225
20
+ imagent/db/schema.sql,sha256=AZ2i0n7gTqg4tq99oHORxVf85Gh55zncx7zkAWJe7aU,21451
21
+ imagent/image_processing/__init__.py,sha256=42exoJjPJU5yBnM1hvytzP5n7yT97h0ntgp1q5uY4EI,894
22
+ imagent/image_processing/convert.py,sha256=bcOmmwPXq73gnKpolzWVM2BuSnRFk-AUkdbwxXWnXQk,2231
23
+ imagent/image_processing/features.py,sha256=apmt8dOpZfx_nMa-DwJZ3UK6hOwn0gaXuIAlJK5mAs0,3261
24
+ imagent/image_processing/hashing.py,sha256=lBoc5rtAleuXhDFxa81G6ZwL4u5OgMrSQjnZ81gCkt8,2196
25
+ imagent/image_processing/memory.py,sha256=BvKWng3pXV9K8xX3c4Hl6-VO2lvbD0fjBgL7ODffLc0,6072
26
+ imagent/image_processing/metadata.py,sha256=jVuBvWObzuc0BRNKIx465TM1Y3lqMI60_zdciNlu4uY,5102
27
+ imagent/image_processing/ocr.py,sha256=tm0ZILqkdmJanjjcT6LpnPB3-ThUgB3yfGdS7aXYifs,6319
28
+ imagent/image_processing/preprocess.py,sha256=ODS0AeYMCXhPVu3fE3tbzv1tUqQqvQXjWcXg_SlfqB4,1599
29
+ imagent/image_processing/problems.py,sha256=xE-hLtiFuj924v0JG0hJkPdNKBygv6SGg9Qy_Gi2sGM,3067
30
+ imagent/image_processing/sample_pictures.py,sha256=-up53BKekrFUhl34esWyipSeeKxRK4uUsRAiMFGqZEg,11431
31
+ imagent/os_specific/__init__.py,sha256=jBxLmQrUE9H5vnE_XdN97dytA-n2QOvT5OQZNJlRXv0,716
32
+ imagent/os_specific/convert.py,sha256=6gxtf4cvo8tKPyq5Y229jcGdRSARngJKok7-E-D_ax4,1661
33
+ imagent/os_specific/files.py,sha256=BzsmBS3RxoXh-jqWXD2zXJMUiQv79FCRD0D43bnH64I,3195
34
+ imagent/os_specific/locking.py,sha256=JvtdCCjkR01CxSHs11sWl5fDrk4-ibovtz2lMCWgyTg,936
35
+ imagent/os_specific/memory.py,sha256=9TZiw2melR7sDczsahudKfwi4eMsoiSKsjibb1kdLwE,7136
36
+ imagent/os_specific/process.py,sha256=uQgK7iZMX9_vrGoQEkjh93uLhrrD6BlfH9riUiz8Vmo,1002
37
+ imagent/os_specific/storage.py,sha256=uGqcgQ68KSfSmhfrlqpNjZYhB20HYLFNZhcC6r_3lWM,4179
38
+ imagent/pipeline/__init__.py,sha256=J-UBkF9AwvCtbomxzg_LvaNYDNa45UHMZmV1jDvkFI4,19
39
+ imagent/pipeline/console.py,sha256=fgmkl-BnUI8wQtkTe9ZZS7CG1rZV-Xp5SgESs8waqIY,4637
40
+ imagent/pipeline/discovery.py,sha256=fSlsn9YHKAshyIj36birbwWy5WLoUn_1UTAzD5I6AjQ,5406
41
+ imagent/pipeline/error_logger.py,sha256=RqzihrJBrV_I2SwKJwLWPqxmhON0i0BCM4JX0f2tJv8,2461
42
+ imagent/pipeline/error_messages.py,sha256=1N3w_DitO4grNtRYwoU4xhiNRGJDIw5RQb4JPrbQRNU,3833
43
+ imagent/pipeline/failure.py,sha256=uouHC0N055mAdLgBtif3euwz2VkGtxj7CsVmKKYRWmA,3020
44
+ imagent/pipeline/folder_picker.py,sha256=xZkDdTdQzhhvFMduBJCgtyb4oE9ucCZmOmK_3qITm-Y,12643
45
+ imagent/pipeline/locking.py,sha256=Mpb2dg4O0zf4VtDVlC_NF9_uyTsT5DEm8B1WsxwgJg8,1497
46
+ imagent/pipeline/progress.py,sha256=tuhlYIP-wONG52uYTVii_JeKwq6USk8-jtUQsv4JiKM,9797
47
+ imagent/pipeline/serialisation.py,sha256=Fwo41Gnrt_yPmF1v3wzegmxyci9cV96ddy9mNYxllJ0,686
48
+ imagent/pipeline/storage.py,sha256=bReZTyl7j216zga5IqyAVqprXrXNHe_RQsGUCN4FSis,1570
49
+ imagent/pipeline/validation.py,sha256=zsi7dZA9cRn7rTS_wb-pjQgI5zxv1GqYEONwHCeQmHQ,2141
50
+ imagent/pipeline/versions.py,sha256=mv0LB4Hib5VICYDMDKAGABmXSRjbZDX-6o5z0gEM_-s,2273
51
+ imagent/prompts/analysis_prompt.txt,sha256=rEvJPRRMkuC4xIenkfuYlXGZ1Tz0MGPV3yNnY5daPEw,789
52
+ imagent/prompts/analysis_schema.json,sha256=VcbLbDBWHSKGCjEgk4U16H8hHlGUE7BUuKJmaAcTUq0,431
53
+ imagent/prompts/query_prompt.txt,sha256=JA1D-8T80GcBS6mW87l3BOrztKp27SOjQl8NlD76aJM,922
54
+ imagent/text_processing/__init__.py,sha256=YaMa4Gq5vYwAknz5543vanHy81BVxxRCiQvzwo8Du74,26
55
+ imagent/text_processing/cleaners.py,sha256=gEm49IGi64w3OnlgzfXhymC0qOZ2iZ3fUgBaYnvuFG4,1073
56
+ imagent/text_processing/formatters.py,sha256=G9AqW6MRfysef2K09ByueQMtf7pp5FlKvX_uJFzHXKg,2902
57
+ imagent/vlm/__init__.py,sha256=-8JBbOp9OIhGv1v_lX0Pg6F4QE5ZqDXKvr9bk8V6JW0,14
58
+ imagent/vlm/analyzer.py,sha256=pHqVvlO_vnF5XuP6QP7PGhZGe1BeIpnKYxLQCitc7gU,17656
59
+ imagent/vlm/calibration.py,sha256=F336iAVx2XwZOQFGfEgdZ0yQS_TIDvPcJE8FyOu1nIA,16028
60
+ imagent/vlm/client.py,sha256=LTjb_syX3m921LIWjJALGktULWWYI01cPfLW8W3z9N8,13898
61
+ imagent/vlm/reply_validation.py,sha256=lechLi_JRQ-zss2IfiGKqn-tTgNiYwkYWXrBLqf1yVw,3021
62
+ imagent/vlm/response_format.py,sha256=ZOMdtJEAw8kAcNPd2AlHlHgljJ2EbVYoKXlGMggxaf0,162
63
+ imagent_cli-0.1.0.dist-info/licenses/LICENSE,sha256=uHB-qencrlneoWkZC9NvTqSwhCzhuruxdM__2uzCVNk,1073
64
+ imagent_cli-0.1.0.dist-info/METADATA,sha256=oBwzyT0rAEp1a8O-MCVSM6tIAwbXMKdbemfU9TswPOQ,11756
65
+ imagent_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
66
+ imagent_cli-0.1.0.dist-info/entry_points.txt,sha256=V0n8lV9Q8t3LyfcNdOi8wrOcmImxh3Gdkabeww2vgTQ,45
67
+ imagent_cli-0.1.0.dist-info/top_level.txt,sha256=iQx-WCk7j0oK2VUSN3IzVrpJ1d8bQZWIWXpgh6K3yJo,8
68
+ imagent_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ imagent = imagent.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Divakar Mahanthi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ imagent