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.
- imagent/__init__.py +0 -0
- imagent/__main__.py +5 -0
- imagent/cli.py +128 -0
- imagent/commands/__init__.py +0 -0
- imagent/commands/after_add.py +82 -0
- imagent/commands/delete.py +200 -0
- imagent/commands/failed.py +24 -0
- imagent/commands/forget.py +63 -0
- imagent/commands/help.py +82 -0
- imagent/commands/menu.py +155 -0
- imagent/commands/scan.py +1394 -0
- imagent/commands/search.py +432 -0
- imagent/commands/settings.py +139 -0
- imagent/commands/setup.py +1409 -0
- imagent/commands/uninstall.py +379 -0
- imagent/config.py +331 -0
- imagent/db/__init__.py +1 -0
- imagent/db/connection.py +237 -0
- imagent/db/operations.py +683 -0
- imagent/db/schema.sql +454 -0
- imagent/image_processing/__init__.py +14 -0
- imagent/image_processing/convert.py +48 -0
- imagent/image_processing/features.py +88 -0
- imagent/image_processing/hashing.py +49 -0
- imagent/image_processing/memory.py +101 -0
- imagent/image_processing/metadata.py +122 -0
- imagent/image_processing/ocr.py +129 -0
- imagent/image_processing/preprocess.py +33 -0
- imagent/image_processing/problems.py +53 -0
- imagent/image_processing/sample_pictures.py +214 -0
- imagent/os_specific/__init__.py +15 -0
- imagent/os_specific/convert.py +34 -0
- imagent/os_specific/files.py +64 -0
- imagent/os_specific/locking.py +31 -0
- imagent/os_specific/memory.py +153 -0
- imagent/os_specific/process.py +19 -0
- imagent/os_specific/storage.py +102 -0
- imagent/pipeline/__init__.py +1 -0
- imagent/pipeline/console.py +111 -0
- imagent/pipeline/discovery.py +107 -0
- imagent/pipeline/error_logger.py +69 -0
- imagent/pipeline/error_messages.py +56 -0
- imagent/pipeline/failure.py +51 -0
- imagent/pipeline/folder_picker.py +289 -0
- imagent/pipeline/locking.py +44 -0
- imagent/pipeline/progress.py +243 -0
- imagent/pipeline/serialisation.py +20 -0
- imagent/pipeline/storage.py +30 -0
- imagent/pipeline/validation.py +68 -0
- imagent/pipeline/versions.py +56 -0
- imagent/prompts/analysis_prompt.txt +8 -0
- imagent/prompts/analysis_schema.json +12 -0
- imagent/prompts/query_prompt.txt +14 -0
- imagent/text_processing/__init__.py +1 -0
- imagent/text_processing/cleaners.py +32 -0
- imagent/text_processing/formatters.py +79 -0
- imagent/vlm/__init__.py +1 -0
- imagent/vlm/analyzer.py +348 -0
- imagent/vlm/calibration.py +288 -0
- imagent/vlm/client.py +302 -0
- imagent/vlm/reply_validation.py +72 -0
- imagent/vlm/response_format.py +7 -0
- imagent_cli-0.1.0.dist-info/METADATA +171 -0
- imagent_cli-0.1.0.dist-info/RECORD +68 -0
- imagent_cli-0.1.0.dist-info/WHEEL +5 -0
- imagent_cli-0.1.0.dist-info/entry_points.txt +2 -0
- imagent_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- imagent_cli-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/progress.py — The progress displays of an indexing run (``Progress``) and of a search (``SearchProgress``).
|
|
3
|
+
|
|
4
|
+
Indexing:
|
|
5
|
+
|
|
6
|
+
While an image is processed, two lines are shown on a terminal: its file name, and what it is doing with the time so far.
|
|
7
|
+
When it is finished they are replaced by four lines (file name, description, status, time taken), then a blank line.
|
|
8
|
+
When output is not a terminal (a pipe or a file) only the finished blocks are printed.
|
|
9
|
+
|
|
10
|
+
Search: one live line (spinner and what is being done, such as "Searching…") that changes as the search moves on
|
|
11
|
+
and disappears when it is over. It is shown on a terminal only; nothing about the steps is printed when output is piped.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import platform
|
|
18
|
+
import shutil
|
|
19
|
+
import sys
|
|
20
|
+
import textwrap
|
|
21
|
+
import threading
|
|
22
|
+
import time
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from imagent.pipeline.console import file_link
|
|
26
|
+
|
|
27
|
+
_SPINNER = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
|
|
28
|
+
_REFRESH_SECONDS = 0.2
|
|
29
|
+
_TIMED = ("indexed", "updated", "FAILED") # results that took real work, so their time is shown
|
|
30
|
+
_STATUS_COLOURS = {"indexed": "32", "updated": "32", "FAILED": "31"} # anything else is dim
|
|
31
|
+
_MIN_WIDTH = 40
|
|
32
|
+
_PIPED_WIDTH = 120
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def format_duration(seconds: float, decimals: int = 0) -> str:
|
|
36
|
+
"""12s, 2m 30s, 1h 05m 30s or 2d 03h 05m 30s: minutes join once it is 60 seconds, hours at 60 minutes, days at 24 hours.
|
|
37
|
+
With ``decimals`` a time below a minute shows that many digits after the point: 12.3s."""
|
|
38
|
+
if decimals and seconds < 60:
|
|
39
|
+
return f"{seconds:.{decimals}f}s"
|
|
40
|
+
total = int(seconds)
|
|
41
|
+
days, rest = divmod(total, 86400)
|
|
42
|
+
hours, rest = divmod(rest, 3600)
|
|
43
|
+
minutes, secs = divmod(rest, 60)
|
|
44
|
+
if days:
|
|
45
|
+
return f"{days}d {hours:02d}h {minutes:02d}m {secs:02d}s"
|
|
46
|
+
if hours:
|
|
47
|
+
return f"{hours}h {minutes:02d}m {secs:02d}s"
|
|
48
|
+
if minutes:
|
|
49
|
+
return f"{minutes}m {secs:02d}s"
|
|
50
|
+
return f"{secs}s"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _clip(text: str, width: int) -> str:
|
|
54
|
+
return text if len(text) <= width else text[: max(width - 1, 0)] + "…"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Progress:
|
|
58
|
+
"""Shows which image is being processed and what it is doing, and what became of each one."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, total: int, stream=None):
|
|
61
|
+
self._stream = stream or sys.stdout
|
|
62
|
+
self._total = total
|
|
63
|
+
self._digits = len(str(total))
|
|
64
|
+
self._live = self._stream.isatty() and os.environ.get("TERM") != "dumb"
|
|
65
|
+
self._colour = self._live and "NO_COLOR" not in os.environ
|
|
66
|
+
self._lock = threading.Lock()
|
|
67
|
+
self._index = 0
|
|
68
|
+
self._name = ""
|
|
69
|
+
self._path = ""
|
|
70
|
+
self._stage = ""
|
|
71
|
+
self._started = 0.0
|
|
72
|
+
self._active = False # an image is being processed, so its two lines are shown
|
|
73
|
+
self._live_shown = False
|
|
74
|
+
self._stop = threading.Event()
|
|
75
|
+
self._ticker: threading.Thread | None = None
|
|
76
|
+
if self._live and platform.system() == "Windows":
|
|
77
|
+
os.system("") # makes the Windows console understand ANSI escape codes
|
|
78
|
+
|
|
79
|
+
def start(self, index: int, path: str | Path) -> None:
|
|
80
|
+
"""Begin the ``index``-th image (counting from 1)."""
|
|
81
|
+
with self._lock:
|
|
82
|
+
self._index = index
|
|
83
|
+
self._name = Path(path).name
|
|
84
|
+
self._path = path
|
|
85
|
+
self._stage = "starting"
|
|
86
|
+
self._started = time.monotonic()
|
|
87
|
+
self._active = True
|
|
88
|
+
if self._live:
|
|
89
|
+
self._redraw()
|
|
90
|
+
if self._ticker is None: # keeps the spinner and the elapsed time moving during a long model call
|
|
91
|
+
self._ticker = threading.Thread(target=self._tick, daemon=True)
|
|
92
|
+
self._ticker.start()
|
|
93
|
+
|
|
94
|
+
def stage(self, text: str) -> None:
|
|
95
|
+
"""Say what the current image is doing now."""
|
|
96
|
+
with self._lock:
|
|
97
|
+
self._stage = text
|
|
98
|
+
if self._live and self._active:
|
|
99
|
+
self._redraw()
|
|
100
|
+
|
|
101
|
+
def done(self, result: str, detail: str = "") -> None:
|
|
102
|
+
"""Finish the current image: print its block. ``detail`` is a description or an error."""
|
|
103
|
+
with self._lock:
|
|
104
|
+
seconds = time.monotonic() - self._started
|
|
105
|
+
self._active = False
|
|
106
|
+
self._erase()
|
|
107
|
+
timing = format_duration(seconds, decimals=1) if result in _TIMED else "–"
|
|
108
|
+
self._write_block(" ".join(detail.split()) or "–", timing, result)
|
|
109
|
+
|
|
110
|
+
def close(self) -> None:
|
|
111
|
+
"""Remove the two live lines. Safe to call more than once."""
|
|
112
|
+
self._stop.set()
|
|
113
|
+
if self._ticker is not None:
|
|
114
|
+
self._ticker.join()
|
|
115
|
+
with self._lock:
|
|
116
|
+
self._active = False
|
|
117
|
+
self._erase()
|
|
118
|
+
|
|
119
|
+
def _tick(self) -> None:
|
|
120
|
+
while not self._stop.wait(_REFRESH_SECONDS):
|
|
121
|
+
with self._lock:
|
|
122
|
+
if self._active:
|
|
123
|
+
self._redraw()
|
|
124
|
+
|
|
125
|
+
def _width(self) -> int:
|
|
126
|
+
if not self._live:
|
|
127
|
+
return _PIPED_WIDTH
|
|
128
|
+
# The last column is left empty so a line never wraps; some terminals report a width of 0.
|
|
129
|
+
return max(shutil.get_terminal_size((80, 24)).columns - 1, _MIN_WIDTH)
|
|
130
|
+
|
|
131
|
+
def _paint(self, text: str, code: str) -> str:
|
|
132
|
+
return f"\033[{code}m{text}\033[0m" if self._colour and text and code else text
|
|
133
|
+
|
|
134
|
+
def _write_block(self, detail: str, timing: str, result: str) -> None:
|
|
135
|
+
"""Write the four lines of the current image (a long description wraps), then a blank line."""
|
|
136
|
+
width = self._width()
|
|
137
|
+
lines = [self._name_line(width)]
|
|
138
|
+
lines += [self._paint(text, "31" if result == "FAILED" else "") for text in textwrap.wrap(detail, width)]
|
|
139
|
+
lines += [self._paint(result, _STATUS_COLOURS.get(result, "2")), timing]
|
|
140
|
+
self._stream.write("\n".join(lines) + "\n\n")
|
|
141
|
+
self._stream.flush()
|
|
142
|
+
|
|
143
|
+
def _name_line(self, width: int) -> str:
|
|
144
|
+
"""The file name, with its place in the run after it."""
|
|
145
|
+
position = f"({self._index:>{self._digits}}/{self._total})"
|
|
146
|
+
name = file_link(_clip(self._name, width - len(position) - 2), self._path, self._stream)
|
|
147
|
+
return f"{self._paint(name, '1')} {self._paint(position, '2')}"
|
|
148
|
+
|
|
149
|
+
def _erase(self) -> None:
|
|
150
|
+
"""Remove the two live lines; the cursor sits at the end of the second."""
|
|
151
|
+
if self._live_shown:
|
|
152
|
+
self._stream.write("\r\033[1A\033[J")
|
|
153
|
+
self._live_shown = False
|
|
154
|
+
|
|
155
|
+
def _redraw(self) -> None:
|
|
156
|
+
self._erase()
|
|
157
|
+
width = self._width()
|
|
158
|
+
spinner = _SPINNER[int(time.monotonic() / _REFRESH_SECONDS) % len(_SPINNER)]
|
|
159
|
+
elapsed = format_duration(time.monotonic() - self._started)
|
|
160
|
+
self._stream.write(self._name_line(width) + "\n" + _clip(f"{spinner} {self._stage}… {elapsed}", width))
|
|
161
|
+
self._stream.flush()
|
|
162
|
+
self._live_shown = True
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class SearchProgress:
|
|
166
|
+
"""Shows what a search is doing as one live line that is replaced by the next step and removed at the end."""
|
|
167
|
+
|
|
168
|
+
def __init__(self, stream=None):
|
|
169
|
+
self._stream = stream or sys.stdout
|
|
170
|
+
self._live = self._stream.isatty() and os.environ.get("TERM") != "dumb"
|
|
171
|
+
self._lock = threading.Lock()
|
|
172
|
+
self._text: str | None = None # the step in progress
|
|
173
|
+
self._live_shown = False
|
|
174
|
+
self._stop = threading.Event()
|
|
175
|
+
self._ticker: threading.Thread | None = None
|
|
176
|
+
if self._live and platform.system() == "Windows":
|
|
177
|
+
os.system("") # makes the Windows console understand ANSI escape codes
|
|
178
|
+
|
|
179
|
+
def step(self, text: str) -> None:
|
|
180
|
+
"""Show ``text`` as what is being done now, in place of the step before it."""
|
|
181
|
+
with self._lock:
|
|
182
|
+
self._text = text
|
|
183
|
+
if self._live:
|
|
184
|
+
self._redraw()
|
|
185
|
+
if self._ticker is None: # keeps the spinner moving during a long model call
|
|
186
|
+
self._ticker = threading.Thread(target=self._tick, daemon=True)
|
|
187
|
+
self._ticker.start()
|
|
188
|
+
|
|
189
|
+
def fail(self, note: str = "") -> None:
|
|
190
|
+
"""Remove the live line because the step failed; ``note``, if given, says what happened instead."""
|
|
191
|
+
with self._lock:
|
|
192
|
+
self._finish(note)
|
|
193
|
+
|
|
194
|
+
def say(self, message: str) -> None:
|
|
195
|
+
"""Print a message without breaking the live line."""
|
|
196
|
+
with self._lock:
|
|
197
|
+
self._erase()
|
|
198
|
+
self._stream.write(message + "\n")
|
|
199
|
+
if self._live and self._text is not None:
|
|
200
|
+
self._redraw()
|
|
201
|
+
self._stream.flush()
|
|
202
|
+
|
|
203
|
+
def close(self) -> None:
|
|
204
|
+
"""Remove the live line. Safe to call more than once."""
|
|
205
|
+
self._stop.set()
|
|
206
|
+
if self._ticker is not None:
|
|
207
|
+
self._ticker.join()
|
|
208
|
+
with self._lock:
|
|
209
|
+
self._finish()
|
|
210
|
+
|
|
211
|
+
def _tick(self) -> None:
|
|
212
|
+
while not self._stop.wait(_REFRESH_SECONDS):
|
|
213
|
+
with self._lock:
|
|
214
|
+
if self._text is not None:
|
|
215
|
+
self._redraw()
|
|
216
|
+
|
|
217
|
+
def _width(self) -> int:
|
|
218
|
+
if not self._live:
|
|
219
|
+
return _PIPED_WIDTH
|
|
220
|
+
return max(shutil.get_terminal_size((80, 24)).columns - 1, _MIN_WIDTH)
|
|
221
|
+
|
|
222
|
+
def _finish(self, note: str = "") -> None:
|
|
223
|
+
"""Remove the live line, and print ``note`` in its place if there is one."""
|
|
224
|
+
if self._text is None:
|
|
225
|
+
return
|
|
226
|
+
self._erase()
|
|
227
|
+
if note:
|
|
228
|
+
self._stream.write(note + "\n")
|
|
229
|
+
self._stream.flush()
|
|
230
|
+
self._text = None
|
|
231
|
+
|
|
232
|
+
def _erase(self) -> None:
|
|
233
|
+
"""Remove the live line; the cursor sits at its end."""
|
|
234
|
+
if self._live_shown:
|
|
235
|
+
self._stream.write("\r\033[J")
|
|
236
|
+
self._live_shown = False
|
|
237
|
+
|
|
238
|
+
def _redraw(self) -> None:
|
|
239
|
+
self._erase()
|
|
240
|
+
spinner = _SPINNER[int(time.monotonic() / _REFRESH_SECONDS) % len(_SPINNER)]
|
|
241
|
+
self._stream.write(_clip(f"{spinner} {self._text}…", self._width()))
|
|
242
|
+
self._stream.flush()
|
|
243
|
+
self._live_shown = True
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/serialisation.py — Pack embedding vectors for BLOB storage.
|
|
3
|
+
|
|
4
|
+
Vectors are stored as little-endian float32 (4 bytes per dimension) on every platform,
|
|
5
|
+
so a database copied between computers reads back the same. Search decodes them with
|
|
6
|
+
``numpy.frombuffer(blob, dtype="<f4")``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import array
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def serialize_embedding(embedding: list[float]) -> bytes:
|
|
16
|
+
"""Pack a float list into little-endian float32 bytes."""
|
|
17
|
+
packed = array.array("f", embedding)
|
|
18
|
+
if sys.byteorder == "big": # explicit branch: the array module writes the machine's native byte order
|
|
19
|
+
packed.byteswap()
|
|
20
|
+
return packed.tobytes()
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/storage.py — Tell whether a folder is on this computer's own disk.
|
|
3
|
+
|
|
4
|
+
Imagent works with pictures stored on the computer it runs on. A network drive can disappear in the middle of a run and
|
|
5
|
+
an external drive can be unplugged, so folders on them are refused with a clear message instead of failing image by image.
|
|
6
|
+
|
|
7
|
+
Each system says it differently, and none says it perfectly, so this only refuses what it is sure of: when the answer
|
|
8
|
+
cannot be found the folder is allowed, and the rest of the program copes with a drive that goes away (see config.MAX_CONSECUTIVE_SERVICE_FAILURES).
|
|
9
|
+
Not checked: a USB hard drive on Windows, which Windows reports as a fixed disk.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from imagent.os_specific.storage import EXTERNAL, NETWORK, classify # EXTERNAL is part of this module's interface: callers and tests name storage.EXTERNAL
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def storage_problem(path: str | Path) -> str | None:
|
|
21
|
+
"""A sentence saying why the folder cannot be used, or None if it is on this computer's own disk or that cannot be told."""
|
|
22
|
+
try:
|
|
23
|
+
kind = classify(os.path.realpath(path))
|
|
24
|
+
except Exception:
|
|
25
|
+
return None
|
|
26
|
+
if kind is None:
|
|
27
|
+
return None
|
|
28
|
+
where = "a network drive" if kind == NETWORK else "an external or removable drive"
|
|
29
|
+
return (f"{path} is on {where}. Imagent only works with pictures stored on this computer's own disk, "
|
|
30
|
+
"because a drive like that can disappear in the middle of a run. Copy the pictures to this computer, then scan that folder.")
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/validation.py — Validate the user-supplied root folder before indexing begins.
|
|
3
|
+
|
|
4
|
+
Exits the process immediately with a clear error message if the path is unusable,
|
|
5
|
+
so downstream code can assume the root is valid and readable.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from imagent.os_specific.files import comparable_path
|
|
15
|
+
from imagent.pipeline.storage import storage_problem
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def validate_folder(raw_path: str) -> Path:
|
|
19
|
+
"""Validate *raw_path* and return a resolved ``Path``.
|
|
20
|
+
|
|
21
|
+
Checks (in order):
|
|
22
|
+
1. The path is not empty.
|
|
23
|
+
2. The path exists on disk.
|
|
24
|
+
3. The path is a directory (not a file or symlink to a file).
|
|
25
|
+
4. The current process has read permission on the directory.
|
|
26
|
+
5. The directory is on this computer's own disk (see pipeline/storage.py).
|
|
27
|
+
|
|
28
|
+
On any failure, prints a human-readable error to stdout and calls
|
|
29
|
+
``sys.exit(1)``. On success, returns the resolved ``Path``.
|
|
30
|
+
"""
|
|
31
|
+
if not raw_path:
|
|
32
|
+
print("Error: No folder path provided.")
|
|
33
|
+
sys.exit(1)
|
|
34
|
+
|
|
35
|
+
path = Path(raw_path).expanduser().resolve()
|
|
36
|
+
|
|
37
|
+
if not path.exists():
|
|
38
|
+
print(f"Error: Path does not exist: {path}")
|
|
39
|
+
sys.exit(1)
|
|
40
|
+
|
|
41
|
+
if not path.is_dir():
|
|
42
|
+
print(f"Error: Path is not a directory: {path}")
|
|
43
|
+
sys.exit(1)
|
|
44
|
+
|
|
45
|
+
if not os.access(path, os.R_OK):
|
|
46
|
+
print(f"Error: Directory is not readable (permission denied): {path}")
|
|
47
|
+
sys.exit(1)
|
|
48
|
+
|
|
49
|
+
problem = storage_problem(path)
|
|
50
|
+
if problem:
|
|
51
|
+
print(f"Error: {problem}")
|
|
52
|
+
sys.exit(1)
|
|
53
|
+
|
|
54
|
+
return path
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def find_overlapping_root(root: Path, known_roots: list[str]) -> str | None:
|
|
58
|
+
"""Return a known root that contains *root* or lies inside it, or None.
|
|
59
|
+
|
|
60
|
+
The same folder is not an overlap (that is a rescan). Nested folders are rejected
|
|
61
|
+
because one file would then belong to two roots.
|
|
62
|
+
"""
|
|
63
|
+
new = comparable_path(str(root))
|
|
64
|
+
for known in known_roots:
|
|
65
|
+
old = comparable_path(known)
|
|
66
|
+
if new != old and (new.startswith(old + os.sep) or old.startswith(new + os.sep)):
|
|
67
|
+
return known
|
|
68
|
+
return None
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/versions.py — The versions of everything that produces an indexed record.
|
|
3
|
+
|
|
4
|
+
Stored with each record (see db/schema.sql), they show which records were made with something older than what is
|
|
5
|
+
installed now, and decide when a file set aside for its model's replies is worth another try.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
from importlib import metadata
|
|
13
|
+
|
|
14
|
+
from imagent import config
|
|
15
|
+
from imagent.text_processing.formatters import SEARCH_TEXT_VERSION
|
|
16
|
+
from imagent.vlm.client import server_version
|
|
17
|
+
|
|
18
|
+
# The versions that decide whether a file parked for its model's replies could do better now.
|
|
19
|
+
MODEL_KEYS = ("vlm_digest", "prompt_hash", "schema_hash")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _fingerprint(text: str) -> str:
|
|
23
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _package_version(name: str) -> str | None:
|
|
27
|
+
try:
|
|
28
|
+
return metadata.version(name)
|
|
29
|
+
except metadata.PackageNotFoundError:
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def collect_versions(client, settings: dict) -> dict:
|
|
34
|
+
"""The versions in use right now: the models' digests as Ollama reports them, fingerprints of the prompt and
|
|
35
|
+
the reply schema, and the versions of the search-text format, the OCR library, Ollama and Imagent."""
|
|
36
|
+
try:
|
|
37
|
+
digests = {model.model: model.digest for model in client.list().models}
|
|
38
|
+
except Exception:
|
|
39
|
+
digests = {}
|
|
40
|
+
ollama_version = server_version(config.OLLAMA_HOST) if config.OLLAMA_HOST else None
|
|
41
|
+
return {
|
|
42
|
+
"vlm_digest": digests.get(settings["vlm_model"]),
|
|
43
|
+
"embedding_digest": digests.get(settings["embedding_model"]),
|
|
44
|
+
"prompt_hash": _fingerprint(config.ANALYSIS_PROMPT),
|
|
45
|
+
"schema_hash": _fingerprint(json.dumps(config.ANALYSIS_SCHEMA, sort_keys=True)),
|
|
46
|
+
"search_text_version": SEARCH_TEXT_VERSION,
|
|
47
|
+
"ocr_version": _package_version("rapidocr"),
|
|
48
|
+
"ollama_version": ".".join(map(str, ollama_version)) if ollama_version else None,
|
|
49
|
+
"app_version": config.APP_VERSION,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def model_versions(versions: dict) -> dict | None:
|
|
54
|
+
"""The part of ``versions`` that decides whether a parked file is worth another try; None if any of it is not known."""
|
|
55
|
+
picked = {key: versions.get(key) for key in MODEL_KEYS}
|
|
56
|
+
return picked if all(picked.values()) else None
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Analyze this image for a search index and fill the fields. Only report what is clearly visible; use an empty list when something is not visible.
|
|
2
|
+
- short_description: under 10 words.
|
|
3
|
+
- scene: 3 to 4 sentences on the overall scene, the setting and the composition. Name any famous landmark or monument you recognise.
|
|
4
|
+
- objects_and_layout: 3 to 5 sentences naming every visible object and where it is (left, right, center, foreground, background).
|
|
5
|
+
- people_details: 2 to 4 sentences: the exact number of people, their clothing, actions and expressions. If none, say so.
|
|
6
|
+
- colors_light_mood: 2 to 3 sentences on the main colors, lighting, weather, time-of-day cues and the mood.
|
|
7
|
+
- tags: 8 to 10 different short descriptive tags.
|
|
8
|
+
Do not transcribe signs or other text; that is read separately.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"type": "object",
|
|
3
|
+
"properties": {
|
|
4
|
+
"short_description": {"type": "string"},
|
|
5
|
+
"scene": {"type": "string"},
|
|
6
|
+
"objects_and_layout": {"type": "string"},
|
|
7
|
+
"people_details": {"type": "string"},
|
|
8
|
+
"colors_light_mood": {"type": "string"},
|
|
9
|
+
"tags": {"type": "array", "items": {"type": "string"}}
|
|
10
|
+
},
|
|
11
|
+
"required": ["short_description", "scene", "objects_and_layout", "people_details", "colors_light_mood", "tags"]
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
You are a query understanding assistant for a local image search engine.
|
|
2
|
+
Given a user's natural language search query, produce:
|
|
3
|
+
|
|
4
|
+
1. normalized_query: the query with typos fixed and abbreviations expanded, otherwise unchanged.
|
|
5
|
+
2. required_details: every concrete, checkable requirement in the query (subject, setting,
|
|
6
|
+
visible text, color, brand, time of day) as short phrases. Do not invent requirements
|
|
7
|
+
the user didn't state.
|
|
8
|
+
3. hypothetical_description: write this AS IF you were describing a real photo that perfectly
|
|
9
|
+
matches the query — dense, factual, using concrete nouns and details a vision model would
|
|
10
|
+
plausibly generate. This is used to search against real image descriptions, so match their
|
|
11
|
+
style: cover the scene, objects, people, visible text, and setting. Do not hedge or say
|
|
12
|
+
"an image of" — just describe the scene directly.
|
|
13
|
+
|
|
14
|
+
Never add requirements or details not implied by the query.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# text_processing package
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
def normalize_whitespace(text: str) -> str:
|
|
4
|
+
return re.sub(r"\s+", " ", text).strip()
|
|
5
|
+
|
|
6
|
+
def dedupe_preserve_order(items: list[str]) -> list[str]:
|
|
7
|
+
seen: set[str] = set()
|
|
8
|
+
result: list[str] = []
|
|
9
|
+
for item in items:
|
|
10
|
+
normalized = item.casefold().strip()
|
|
11
|
+
if not normalized or normalized in seen:
|
|
12
|
+
continue
|
|
13
|
+
seen.add(normalized)
|
|
14
|
+
result.append(item.strip())
|
|
15
|
+
return result
|
|
16
|
+
|
|
17
|
+
def lead_sentence(text: str) -> str:
|
|
18
|
+
normalized = normalize_whitespace(text)
|
|
19
|
+
match = re.match(r"^(.+?[.!?])(?:\s|$)", normalized)
|
|
20
|
+
if match:
|
|
21
|
+
return match.group(1).strip()
|
|
22
|
+
return normalized
|
|
23
|
+
|
|
24
|
+
def normalize_terms(values: list[str]) -> list[str]:
|
|
25
|
+
return dedupe_preserve_order([normalize_whitespace(value) for value in values if normalize_whitespace(value)])
|
|
26
|
+
|
|
27
|
+
def split_sections(lines: list[str]) -> str:
|
|
28
|
+
cleaned = [line for line in lines if line and line.strip()]
|
|
29
|
+
return "\n".join(cleaned).strip()
|
|
30
|
+
|
|
31
|
+
def join_bullets(items: list[str]) -> list[str]:
|
|
32
|
+
return [f"- {item}" for item in items if item.strip()]
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from imagent.text_processing.cleaners import (
|
|
4
|
+
normalize_whitespace,
|
|
5
|
+
normalize_terms,
|
|
6
|
+
lead_sentence,
|
|
7
|
+
join_bullets,
|
|
8
|
+
split_sections,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
SEARCH_TEXT_VERSION = 1 # raise it whenever build_search_text changes what it makes: stored with each record, it shows which are out of date
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _heading(key: str) -> str:
|
|
16
|
+
return key.replace("_", " ").strip().capitalize()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _text(value) -> str:
|
|
20
|
+
"""A scalar or nested value as one line of text; empty if there is nothing to say."""
|
|
21
|
+
if value is None or value == "" or value == [] or value == {}:
|
|
22
|
+
return ""
|
|
23
|
+
if isinstance(value, (dict, list)):
|
|
24
|
+
return json.dumps(value, ensure_ascii=False)
|
|
25
|
+
return normalize_whitespace(str(value))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def build_description(reply: dict, summary_field: str) -> str:
|
|
29
|
+
"""The prose of the model's reply: its text fields in the order the model wrote them, without the one-line summary."""
|
|
30
|
+
texts = [value.strip() for key, value in reply.items() if key != summary_field and isinstance(value, str)]
|
|
31
|
+
return "\n\n".join(text for text in texts if text)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _unique(items: list, seen: set[str]) -> list[str]:
|
|
35
|
+
"""The items as text, each once; what is in ``seen`` is left out and what is kept is added to it."""
|
|
36
|
+
kept: list[str] = []
|
|
37
|
+
for item in normalize_terms([_text(item) for item in items]):
|
|
38
|
+
canonical = item.casefold()
|
|
39
|
+
if canonical not in seen:
|
|
40
|
+
seen.add(canonical)
|
|
41
|
+
kept.append(item)
|
|
42
|
+
return kept
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_search_text(reply: dict, ocr_text: list[str], summary_field: str) -> str:
|
|
46
|
+
"""The text that is embedded for one image, built from whatever fields the model's reply has.
|
|
47
|
+
|
|
48
|
+
Text fields make up the description; the summary follows if it adds anything; each list field gets its own
|
|
49
|
+
section named after it, any other field is one line of its own; the text read in the image comes last.
|
|
50
|
+
"""
|
|
51
|
+
seen: set[str] = set()
|
|
52
|
+
sections: list[str] = []
|
|
53
|
+
|
|
54
|
+
description = normalize_whitespace(build_description(reply, summary_field))
|
|
55
|
+
if description:
|
|
56
|
+
sections.append(description)
|
|
57
|
+
seen.add(description.casefold())
|
|
58
|
+
|
|
59
|
+
summary = reply.get(summary_field)
|
|
60
|
+
lead = lead_sentence(summary) if isinstance(summary, str) else ""
|
|
61
|
+
if lead and lead.casefold() != description.casefold():
|
|
62
|
+
sections.append(lead)
|
|
63
|
+
seen.add(lead.casefold())
|
|
64
|
+
|
|
65
|
+
for key, value in reply.items():
|
|
66
|
+
if key == summary_field or isinstance(value, str):
|
|
67
|
+
continue
|
|
68
|
+
if isinstance(value, list):
|
|
69
|
+
items = _unique(value, seen)
|
|
70
|
+
if items:
|
|
71
|
+
sections.extend(["", f"{_heading(key)}:", *join_bullets(items)])
|
|
72
|
+
elif _text(value):
|
|
73
|
+
sections.extend(["", f"{_heading(key)}: {_text(value)}"])
|
|
74
|
+
|
|
75
|
+
ocr = _unique(ocr_text, seen)
|
|
76
|
+
if ocr:
|
|
77
|
+
sections.extend(["", "Visible text:", *ocr])
|
|
78
|
+
|
|
79
|
+
return split_sections(sections)
|
imagent/vlm/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# vlm package
|