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
imagent/config.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import platform
|
|
7
|
+
import shutil
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# ---------------------------------------------------------------------------
|
|
12
|
+
# Storage location. Every setting lives in this file; no environment variables are read.
|
|
13
|
+
# ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
def _data_dir() -> Path:
|
|
16
|
+
"""Per-user folder for the database and config.json: ``~/.imagent`` on every OS.
|
|
17
|
+
|
|
18
|
+
It must be on a local disk: SQLite's WAL mode is not safe on network drives.
|
|
19
|
+
"""
|
|
20
|
+
try:
|
|
21
|
+
home = Path.home()
|
|
22
|
+
except (RuntimeError, KeyError): # no HOME / user profile, as in some containers and services
|
|
23
|
+
raise SystemExit("Error: cannot find your home folder, where Imagent keeps its data.")
|
|
24
|
+
return home / ".imagent"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
IMAGENT_HOME: Path = _data_dir()
|
|
28
|
+
DB_PATH: Path = IMAGENT_HOME / "imagent.db"
|
|
29
|
+
CONFIG_PATH: Path = IMAGENT_HOME / "config.json"
|
|
30
|
+
# Programs that setup installs for Imagent (Ollama, when the computer has none) live here, beside the data folder and not in it:
|
|
31
|
+
# uninstall deletes the data folder first and then asks whether to keep each program.
|
|
32
|
+
TOOLS_DIR: Path = IMAGENT_HOME.with_name(IMAGENT_HOME.name + "-tools")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_config() -> dict:
|
|
36
|
+
"""Return config.json as a dict, or {} if the file is missing, unreadable or not a JSON object."""
|
|
37
|
+
try:
|
|
38
|
+
data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
|
|
39
|
+
except (OSError, ValueError):
|
|
40
|
+
return {}
|
|
41
|
+
return data if isinstance(data, dict) else {}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _write_json(path: Path, data: dict) -> None:
|
|
45
|
+
"""Write ``data`` to ``path`` beside the real file and then swap it in, so a crash or a power cut
|
|
46
|
+
leaves either the old file or the new one, never a half-written one."""
|
|
47
|
+
IMAGENT_HOME.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
temp = path.with_name(path.name + ".tmp")
|
|
49
|
+
with open(temp, "w", encoding="utf-8") as handle:
|
|
50
|
+
handle.write(json.dumps(data, indent=2) + "\n")
|
|
51
|
+
handle.flush()
|
|
52
|
+
os.fsync(handle.fileno())
|
|
53
|
+
os.replace(temp, path)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def save_config(data: dict) -> None:
|
|
57
|
+
"""Write config.json (user preferences). The chosen models are not here: they are locked in the database. Only while setup is
|
|
58
|
+
unfinished, the model names confirmed so far are kept here to fill in the screen again."""
|
|
59
|
+
_write_json(CONFIG_PATH, data)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _install_record_path() -> Path:
|
|
63
|
+
return IMAGENT_HOME / "install_record.json"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def load_install_record() -> dict:
|
|
67
|
+
"""Return what imagent setup added to this computer ({"ollama_models": [...]}), or {} if nothing is recorded.
|
|
68
|
+
|
|
69
|
+
The uninstaller removes only what is listed here, so a model you already had before Imagent is never touched.
|
|
70
|
+
"""
|
|
71
|
+
try:
|
|
72
|
+
data = json.loads(_install_record_path().read_text(encoding="utf-8"))
|
|
73
|
+
except (OSError, ValueError):
|
|
74
|
+
return {}
|
|
75
|
+
return data if isinstance(data, dict) else {}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def save_install_record(data: dict) -> None:
|
|
79
|
+
_write_json(_install_record_path(), data)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def record_pinned_model(pinned: str, base: str) -> None:
|
|
83
|
+
"""Note that setup copied the model ``base`` under the name ``pinned``: the uninstaller removes the copy, and it can be made again from ``base``."""
|
|
84
|
+
record = load_install_record()
|
|
85
|
+
models = [m for m in record.get("ollama_models", []) if isinstance(m, str)]
|
|
86
|
+
if pinned not in models:
|
|
87
|
+
models.append(pinned)
|
|
88
|
+
pins = record["pinned_models"] if isinstance(record.get("pinned_models"), dict) else {}
|
|
89
|
+
save_install_record({**record, "ollama_models": models, "pinned_models": {**pins, pinned: base}})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# --- Programs installed by setup -----------------------------------------------
|
|
93
|
+
# Each lives in its own folder of TOOLS_DIR, with a small file saying what it is, so uninstall can describe it and offer to
|
|
94
|
+
# remove it even after the data folder (and the install record in it) is gone.
|
|
95
|
+
TOOL_INFO_FILE = "imagent-tool.json"
|
|
96
|
+
OLLAMA_DIR: Path = TOOLS_DIR / "ollama" # holds program/ (what the archive unpacks to), models/ and the info file
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def save_tool_info(folder: Path, name: str, description: str, version: str) -> None:
|
|
100
|
+
(folder / TOOL_INFO_FILE).write_text(json.dumps({"name": name, "description": description, "version": version}, indent=2) + "\n",
|
|
101
|
+
encoding="utf-8")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def installed_tools() -> list[dict]:
|
|
105
|
+
"""The programs setup installed that are still on this computer: [{"name", "description", "version", "path"}]."""
|
|
106
|
+
tools = []
|
|
107
|
+
for folder in sorted(TOOLS_DIR.iterdir()) if TOOLS_DIR.is_dir() else []:
|
|
108
|
+
try:
|
|
109
|
+
info = json.loads((folder / TOOL_INFO_FILE).read_text(encoding="utf-8"))
|
|
110
|
+
except (OSError, ValueError):
|
|
111
|
+
continue
|
|
112
|
+
if isinstance(info, dict) and isinstance(info.get("name"), str):
|
|
113
|
+
tools.append({"name": info["name"], "description": str(info.get("description", "")),
|
|
114
|
+
"version": str(info.get("version", "")), "path": folder})
|
|
115
|
+
return tools
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# --- Ollama program ------------------------------------------------------------
|
|
119
|
+
# The Ollama that setup installs when the computer has none (or an older one than Imagent needs): the official standalone build
|
|
120
|
+
# for this OS and CPU, from Ollama's own release, pinned to one version. The release lists the SHA-256 of every file in its
|
|
121
|
+
# sha256sum.txt; that list is checked against the one sum pinned here, so the file names and their sums are read from the list
|
|
122
|
+
# and none of them is written in this code. Running it needs no administrator rights and no change to PATH, and removing it is
|
|
123
|
+
# deleting its folder.
|
|
124
|
+
OLLAMA_VERSION = "0.40.17"
|
|
125
|
+
OLLAMA_MANIFEST_SHA256 = "dc2f480e48d4f8dfd37d127e6a54347cf7f3fd80a52beb1e1ca611d47bdf4dcd" # of sha256sum.txt in that release
|
|
126
|
+
OLLAMA_MANIFEST = "sha256sum.txt"
|
|
127
|
+
OLLAMA_RELEASE_URL = "https://github.com/ollama/ollama/releases/download/v{version}/{file}"
|
|
128
|
+
OLLAMA_ARCHIVE_ENDINGS = (".tgz", ".tar.zst", ".zip")
|
|
129
|
+
|
|
130
|
+
# The test pictures setup checks this computer with (image_processing/sample_pictures.py): 30 CC0 photographs and a manifest of where
|
|
131
|
+
# each came from, as one zip. It is not part of the installed package, so the install stays small; setup downloads it once from
|
|
132
|
+
# the project's v0.1.0 GitHub release (where the zip is attached) and refuses any file whose SHA-256 is not the one pinned here. The same
|
|
133
|
+
# zip is kept in tests/data/.
|
|
134
|
+
TEST_PICTURES_URL = "https://github.com/the-walkerrr/Imagent/releases/download/v0.1.0/images.zip"
|
|
135
|
+
TEST_PICTURES_SHA256 = "5e746b8294caf043f289c7e3c9a7280121d9bdd05b196142ebdb134d74c22bba"
|
|
136
|
+
TEST_PICTURES_TIMEOUT = 60 # seconds to reach the server, or to wait between two parts of the download
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def ollama_release_url(file: str) -> str:
|
|
140
|
+
return OLLAMA_RELEASE_URL.format(version=OLLAMA_VERSION, file=file)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def ollama_build_prefix() -> str | None:
|
|
144
|
+
"""The start of the file names of Ollama's build for this OS and CPU (``ollama-linux-amd64``), or None when it has none.
|
|
145
|
+
The macOS build is one file for both CPUs, so its name has no CPU in it."""
|
|
146
|
+
system = {"Darwin": "darwin", "Linux": "linux", "Windows": "windows"}.get(platform.system())
|
|
147
|
+
cpu = {"x86_64": "amd64", "amd64": "amd64", "arm64": "arm64", "aarch64": "arm64"}.get(platform.machine().lower())
|
|
148
|
+
if system is None or cpu is None:
|
|
149
|
+
return None
|
|
150
|
+
return "ollama-darwin" if system == "darwin" else f"ollama-{system}-{cpu}"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def ollama_checksums(manifest: str) -> dict:
|
|
154
|
+
"""File name -> SHA-256 from the text of a release's sha256sum.txt (lines like ``<sum> ./<name>``)."""
|
|
155
|
+
sums = {}
|
|
156
|
+
for line in manifest.splitlines():
|
|
157
|
+
parts = line.split(None, 1)
|
|
158
|
+
if len(parts) == 2 and len(parts[0]) == 64 and all(c in "0123456789abcdef" for c in parts[0].lower()):
|
|
159
|
+
sums[parts[1].strip().lstrip("*").removeprefix("./")] = parts[0].lower()
|
|
160
|
+
return sums
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def ollama_downloads(manifest: str, extras: tuple[str, ...] = ()) -> list[tuple[str, str, str]]:
|
|
164
|
+
"""(url, file name, sha256) of every file to install, from the text of the release's sha256sum.txt: the build for this computer
|
|
165
|
+
first, then the extra file of each name in ``extras`` (``rocm``, ``jetpack6``…) that the release has, to be unpacked over it.
|
|
166
|
+
Empty when the release has no build for this computer's OS and CPU."""
|
|
167
|
+
prefix, sums = ollama_build_prefix(), ollama_checksums(manifest)
|
|
168
|
+
if prefix is None:
|
|
169
|
+
return []
|
|
170
|
+
found = []
|
|
171
|
+
for stem in (prefix, *(f"{prefix}-{extra}" for extra in extras)):
|
|
172
|
+
name = next((stem + ending for ending in OLLAMA_ARCHIVE_ENDINGS if stem + ending in sums), None)
|
|
173
|
+
if name is not None:
|
|
174
|
+
found.append((ollama_release_url(name), name, sums[name]))
|
|
175
|
+
elif stem == prefix:
|
|
176
|
+
return [] # without the build itself an extra file has nothing to go over
|
|
177
|
+
return found
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def private_ollama_binary() -> str | None:
|
|
181
|
+
"""The `ollama` program that setup installed, or None if it did not (or it is gone)."""
|
|
182
|
+
name = "ollama.exe" if platform.system() == "Windows" else "ollama"
|
|
183
|
+
program = OLLAMA_DIR / "program"
|
|
184
|
+
for path in (program / name, program / "bin" / name): # Windows and macOS unpack it at the top, Linux in bin/
|
|
185
|
+
if path.is_file():
|
|
186
|
+
return str(path)
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def ollama_binary() -> str | None:
|
|
191
|
+
"""The `ollama` program Imagent runs: its own copy when setup installed one (the models are in that copy's folder), otherwise the one on PATH."""
|
|
192
|
+
return private_ollama_binary() or shutil.which("ollama")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def ollama_environment(host: str | None) -> dict | None:
|
|
196
|
+
"""The environment to start ``ollama serve`` with: the address to listen on and, when the program is Imagent's own, a home
|
|
197
|
+
inside its folder. Ollama keeps its models, its key pair and its cache in a ``.ollama`` folder in the user's home (the models
|
|
198
|
+
can be moved with OLLAMA_MODELS, the rest cannot), so without this, removing Imagent's copy would leave files behind in a folder
|
|
199
|
+
shared with any Ollama the user has. None when there is nothing to add."""
|
|
200
|
+
extra = {}
|
|
201
|
+
if host: # otherwise the server listens on its default port, not the saved one
|
|
202
|
+
extra["OLLAMA_HOST"] = host
|
|
203
|
+
if private_ollama_binary():
|
|
204
|
+
extra["OLLAMA_MODELS"] = str(OLLAMA_DIR / "models") # explicit, so an OLLAMA_MODELS of the user's own cannot send them elsewhere
|
|
205
|
+
extra["HOME"] = extra["USERPROFILE"] = str(OLLAMA_DIR / "home") # USERPROFILE is the home on Windows
|
|
206
|
+
return {**os.environ, **extra} if extra else None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# User preferences written by imagent setup.
|
|
210
|
+
OLLAMA_HOST: str = load_config().get("ollama_host", "")
|
|
211
|
+
|
|
212
|
+
# --- Ollama ------------------------------------------------------------------
|
|
213
|
+
OLLAMA_CONNECT_TIMEOUT: int = 10 # seconds to reach the server
|
|
214
|
+
# These four depend on the computer. The values here are only where setup starts measuring: setup stores what it measured
|
|
215
|
+
# (vlm/calibration.py) and apply_device_settings puts it in their place before every run.
|
|
216
|
+
OLLAMA_TIMEOUT: int = 300 # seconds to wait for a reply (a cold model load counts) or between download updates
|
|
217
|
+
OLLAMA_NUM_CTX: int = 8192
|
|
218
|
+
OLLAMA_USE_MMAP: bool = False # load each model fully into memory instead of paging it in from disk
|
|
219
|
+
OLLAMA_MAX_OUTPUT_TOKENS: int = 2200 # cap on the image-analysis reply; without it a runaway reply fills the whole context window
|
|
220
|
+
QUERY_MAX_OUTPUT_TOKENS: int = 600 # cap on the reply that reads a search query; at temperature 0 a runaway reply repeats on every search and would otherwise last until the wait runs out
|
|
221
|
+
# What happens when the vision model's reply cannot be used. Each kind of trouble has its own steps (vlm/analyzer.py):
|
|
222
|
+
# - a reply that ended at the output cap: one retry with different sampling, then the cap is raised step by step;
|
|
223
|
+
# - a complete reply that does not fit the schema: the problems are sent back to the model and it answers again.
|
|
224
|
+
ANALYSIS_RETRIES: int = 1 # extra tries when a complete reply does not fit the schema
|
|
225
|
+
ANALYSIS_RETRY_TEMPERATURE: float = 0.4 # a retry must differ from the first try: at temperature 0 the same input gives the same reply
|
|
226
|
+
ANALYSIS_RETRY_REPEAT_PENALTY: float = 1.15 # sampling after a cut-off reply, which may be a loop; Ollama's own default is 1.1
|
|
227
|
+
ANALYSIS_CAP_STEP: float = 1.5 # each raise multiplies the output cap by this ...
|
|
228
|
+
ANALYSIS_CAP_RAISES: int = 3 # ... up to this many times, and never beyond what fits in the context window after the prompt
|
|
229
|
+
# Trouble reaching the model, each with its own step (vlm/analyzer.py): no reply in time -> wait longer; the server crashed
|
|
230
|
+
# or ran out of memory -> restart it, or free memory, and ask the same again once.
|
|
231
|
+
OLLAMA_TIMEOUT_STEP: int = 2 # each wait is this many times the one before ...
|
|
232
|
+
OLLAMA_TIMEOUT_RAISES: int = 2 # ... up to this many times
|
|
233
|
+
OLLAMA_RECOVERY_WAIT: int = 5 # seconds to wait after freeing memory before asking again
|
|
234
|
+
|
|
235
|
+
# Sent with every request to the VLM and to the judge model. num_ctx and use_mmap must be
|
|
236
|
+
# identical across all requests to one model: Ollama reloads it whenever one of them changes.
|
|
237
|
+
LLM_OPTIONS: dict = {"num_ctx": OLLAMA_NUM_CTX, "use_mmap": OLLAMA_USE_MMAP, "temperature": 0, "seed": 0}
|
|
238
|
+
EMBED_OPTIONS: dict = {"use_mmap": OLLAMA_USE_MMAP}
|
|
239
|
+
|
|
240
|
+
# --- Images ------------------------------------------------------------------
|
|
241
|
+
OCR_MIN_CONFIDENCE: float = 0.6 # OCR blocks scoring below this are dropped
|
|
242
|
+
OCR_TILE_SHARE: float = 0.5 # a tile is this share of the largest image the OCR engine reads without shrinking it: it finds text only above about 2% of the image side, so smaller tiles read smaller text
|
|
243
|
+
OCR_TILE_OVERLAP: float = 0.1 # share of a tile that the next one covers again, so text on a border is read whole in one of them
|
|
244
|
+
IMAGE_MEMORY_SHARE: float = 0.5 # share of the memory free right now that one image may use at its peak (image_processing/memory.py)
|
|
245
|
+
IMAGE_MEMORY_SHARE_LAST_TRY: float = 0.75 # the share for one last check of an image still too large after every model is unloaded (vlm/analyzer.py)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
IMAGE_EDGE_CEILING: int = 1024 # the largest long side setup tries for the image sent to the vision model: beyond it the extra detail is not worth the time
|
|
249
|
+
IMAGE_MAX_LONG_EDGE: int = IMAGE_EDGE_CEILING # the long side actually used: the largest the computer managed, never above the ceiling
|
|
250
|
+
IMAGE_JPEG_QUALITY: int = 85
|
|
251
|
+
ONE_MODEL_AT_A_TIME: bool = False # True when setup found that the vision and embedding models do not fit in memory together (vlm/calibration.py)
|
|
252
|
+
|
|
253
|
+
# --- Measuring the computer at setup (vlm/calibration.py) ---------------------
|
|
254
|
+
CALIBRATION_EDGE_STEP: float = 0.75 # each smaller image tried is this share of the one before
|
|
255
|
+
CALIBRATION_MIN_EDGE: int = 336 # below this long side the vision model gets too little detail to describe a picture usefully
|
|
256
|
+
CALIBRATION_MEMORY_HEADROOM: float = 0.25 # share of the free memory that must stay free after a model is loaded into it; else it is paged in from disk
|
|
257
|
+
CALIBRATION_TIMEOUT_MARGIN: float = 2.0 # the wait is the measured time for the largest first reply times this
|
|
258
|
+
CALIBRATION_EMBED_TOKENS: int = 500 # length, in tokens, of the text the embedding model is given to see whether it fits in memory beside the vision model: about one stored description
|
|
259
|
+
CALIBRATION_TRIAL_TOKENS: int = 48 # tokens a trial reply is asked for: enough to time the model, not to finish a description
|
|
260
|
+
CALIBRATION_TOP_APPS: int = 5 # programs listed, largest first, when the vision model runs out of memory, so the person can close some
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def apply_device_settings(device: dict) -> None:
|
|
264
|
+
"""Put what setup measured about this computer in place of the starting values, for this run.
|
|
265
|
+
|
|
266
|
+
The two option dicts are changed in place: code that took them earlier sees the new values."""
|
|
267
|
+
global OLLAMA_TIMEOUT, OLLAMA_NUM_CTX, OLLAMA_USE_MMAP, IMAGE_MAX_LONG_EDGE, ONE_MODEL_AT_A_TIME
|
|
268
|
+
OLLAMA_TIMEOUT = device["timeout_seconds"]
|
|
269
|
+
OLLAMA_NUM_CTX = device["num_ctx"]
|
|
270
|
+
OLLAMA_USE_MMAP = device["use_mmap"]
|
|
271
|
+
IMAGE_MAX_LONG_EDGE = device["image_long_edge"]
|
|
272
|
+
ONE_MODEL_AT_A_TIME = bool(device.get("one_model_at_a_time")) # None: not measured yet, so the two models are left to share the memory
|
|
273
|
+
LLM_OPTIONS.update(num_ctx=OLLAMA_NUM_CTX, use_mmap=OLLAMA_USE_MMAP)
|
|
274
|
+
EMBED_OPTIONS.update(use_mmap=OLLAMA_USE_MMAP)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def device_settings() -> dict:
|
|
278
|
+
"""The device settings in place right now, in the form ``apply_device_settings`` takes."""
|
|
279
|
+
return {"timeout_seconds": OLLAMA_TIMEOUT, "num_ctx": OLLAMA_NUM_CTX, "use_mmap": OLLAMA_USE_MMAP,
|
|
280
|
+
"image_long_edge": IMAGE_MAX_LONG_EDGE, "one_model_at_a_time": ONE_MODEL_AT_A_TIME}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@contextlib.contextmanager
|
|
284
|
+
def temporary_device_settings(**changes):
|
|
285
|
+
"""Run the block with some of the device settings changed (``timeout_seconds``, ``num_ctx``, ``use_mmap``,
|
|
286
|
+
``image_long_edge``), then put back the ones that were in place: a try with other settings never changes the usual ones."""
|
|
287
|
+
before = device_settings()
|
|
288
|
+
apply_device_settings({**before, **changes})
|
|
289
|
+
try:
|
|
290
|
+
yield
|
|
291
|
+
finally:
|
|
292
|
+
apply_device_settings(before)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# --- Database and indexing ---------------------------------------------------
|
|
296
|
+
SQLITE_BUSY_TIMEOUT_S: int = 30 # how long a connection waits for another process's write lock
|
|
297
|
+
SCAN_GUARD_MIN_FILES: int = 10 # a scan that finds at least this many indexed images gone ...
|
|
298
|
+
SCAN_GUARD_MAX_SHARE: float = 0.5 # ... and more than this share of the folder's indexed images asks before forgetting them
|
|
299
|
+
BACKLOG_MAX_ATTEMPTS: int = 3 # a file that fails this many times is left alone until it changes
|
|
300
|
+
RESCAN_WAIT_SECONDS: int = 60 # after an indexing round, how long the user can choose before the scan runs again by itself
|
|
301
|
+
MAX_CONSECUTIVE_SERVICE_FAILURES: int = 3 # indexing stops after this many Ollama failures in a row
|
|
302
|
+
SERVICE_TRIES: int = 3 # tries for an image whose failure is Ollama's or the machine's (each try runs the steps in vlm/analyzer.py), before the user is told
|
|
303
|
+
CONVERT_TIMEOUT: int = 300 # seconds the operating system's tool may take to convert one picture Pillow cannot open
|
|
304
|
+
RETRY_RATE_WINDOW: int = 10 # indexing stops when, among this many of the latest analysed images ...
|
|
305
|
+
RETRY_RATE_STOP: float = 0.5 # ... at least this share needed the model's reply retried: the model or the prompt is the problem, not the files
|
|
306
|
+
ERROR_LOG_MAX_ROWS: int = 1000 # oldest error_logs rows beyond this are deleted
|
|
307
|
+
|
|
308
|
+
# --- Search ------------------------------------------------------------------
|
|
309
|
+
DB_BATCH_ROWS: int = 1000 # rows read from the database at a time by search: the memory it uses is about this many rows, however many images are indexed
|
|
310
|
+
UNCERTAIN_TOP_K: int = 3 # results returned per search (the closest images)
|
|
311
|
+
SEARCH_MAX_MISSING_SKIPPED: int = 100 # closest images skipped because their file is gone, before the search gives up looking
|
|
312
|
+
SEARCH_DETAILS: tuple = ("short", "full") # what a search shows for each picture: the one-line summary or the whole description
|
|
313
|
+
SEARCH_DETAIL_DEFAULT: str = "short" # used until the user chooses in settings
|
|
314
|
+
|
|
315
|
+
# --- Versions ----------------------------------------------------------------
|
|
316
|
+
APP_VERSION: str = "0.1.0" # stored with every indexed record (pipeline/versions.py)
|
|
317
|
+
|
|
318
|
+
# --- Launchers ---------------------------------------------------------------
|
|
319
|
+
# What messages tell the user to run, for the OS they are on.
|
|
320
|
+
SETUP_COMMAND: str = "imagent setup"
|
|
321
|
+
SCAN_COMMAND: str = "imagent scan"
|
|
322
|
+
ADD_COMMAND: str = "imagent add"
|
|
323
|
+
|
|
324
|
+
# --- Prompts -----------------------------------------------------------------
|
|
325
|
+
PROMPTS_DIR: Path = Path(__file__).parent / "prompts"
|
|
326
|
+
ANALYSIS_PROMPT: str = (PROMPTS_DIR / "analysis_prompt.txt").read_text(encoding="utf-8")
|
|
327
|
+
# The shape of the vision model's reply: a JSON schema sent to Ollama and used to check the reply. The fields live in this
|
|
328
|
+
# file and in the prompt only; no code names them, except the one below.
|
|
329
|
+
ANALYSIS_SCHEMA: dict = json.loads((PROMPTS_DIR / "analysis_schema.json").read_text(encoding="utf-8"))
|
|
330
|
+
SUMMARY_FIELD: str = "short_description" # the field of the reply stored as the image's one-line summary, shown in search results
|
|
331
|
+
QUERY_PROMPT: str = (PROMPTS_DIR / "query_prompt.txt").read_text(encoding="utf-8")
|
imagent/db/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# db package
|
imagent/db/connection.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/db/connection.py — Database initialisation and connection factory.
|
|
3
|
+
|
|
4
|
+
Opens (or creates) the SQLite database, brings its schema up to date, and configures
|
|
5
|
+
per-connection PRAGMAs required by the pipeline.
|
|
6
|
+
|
|
7
|
+
The schema version is kept in ``PRAGMA user_version``. A new database gets ``schema.sql``
|
|
8
|
+
(always the latest schema); an older one is upgraded by running the steps of ``_MIGRATIONS``
|
|
9
|
+
in a single transaction, so a crash or a power cut leaves it exactly as it was.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import sqlite3
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from imagent import config
|
|
17
|
+
from imagent.pipeline.error_messages import all_messages
|
|
18
|
+
|
|
19
|
+
# schema.sql sits next to this file
|
|
20
|
+
_SCHEMA_PATH = Path(__file__).parent / "schema.sql"
|
|
21
|
+
|
|
22
|
+
# The upserts (INSERT ... ON CONFLICT DO UPDATE) used throughout arrived in SQLite 3.24 (June 2018).
|
|
23
|
+
_MIN_SQLITE_VERSION = (3, 24, 0)
|
|
24
|
+
|
|
25
|
+
# The version of the schema in schema.sql. Raise it, and add the steps to _MIGRATIONS, with every schema change.
|
|
26
|
+
SCHEMA_VERSION = 6
|
|
27
|
+
|
|
28
|
+
# Version 1 is the schema of databases made before versions were recorded (user_version 0 with tables).
|
|
29
|
+
# _MIGRATIONS[n] holds the statements that turn version n - 1 into version n.
|
|
30
|
+
_MIGRATIONS: dict[int, list[str]] = {
|
|
31
|
+
# 2: the full-text-search tables were never queried, so they are no longer kept.
|
|
32
|
+
2: [
|
|
33
|
+
"DROP TRIGGER IF EXISTS trg_image_data_delete_fts",
|
|
34
|
+
"DROP TABLE IF EXISTS image_search_fts",
|
|
35
|
+
"DROP TABLE IF EXISTS image_text_fts",
|
|
36
|
+
],
|
|
37
|
+
# 3: what setup measured about the computer.
|
|
38
|
+
3: [
|
|
39
|
+
"""CREATE TABLE IF NOT EXISTS device_settings (
|
|
40
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
41
|
+
num_ctx INTEGER NOT NULL,
|
|
42
|
+
use_mmap INTEGER NOT NULL CHECK (use_mmap IN (0, 1)),
|
|
43
|
+
image_long_edge INTEGER NOT NULL,
|
|
44
|
+
timeout_seconds INTEGER NOT NULL,
|
|
45
|
+
vlm_digest TEXT,
|
|
46
|
+
measurements TEXT NOT NULL,
|
|
47
|
+
app_version TEXT NOT NULL,
|
|
48
|
+
calibrated_at DATETIME NOT NULL
|
|
49
|
+
)""",
|
|
50
|
+
],
|
|
51
|
+
# 4: whether the vision and embedding models fit in memory together.
|
|
52
|
+
4: [
|
|
53
|
+
"ALTER TABLE device_settings ADD COLUMN one_model_at_a_time INTEGER CHECK (one_model_at_a_time IN (0, 1))",
|
|
54
|
+
],
|
|
55
|
+
# 5: how many deleted pictures' analyses are kept, and those analyses.
|
|
56
|
+
5: [
|
|
57
|
+
"""CREATE TABLE IF NOT EXISTS index_preferences (
|
|
58
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
59
|
+
keep_deleted INTEGER NOT NULL CHECK (keep_deleted >= 0)
|
|
60
|
+
)""",
|
|
61
|
+
"""CREATE TABLE IF NOT EXISTS deleted_analyses (
|
|
62
|
+
pixel_hash TEXT PRIMARY KEY,
|
|
63
|
+
short_description TEXT,
|
|
64
|
+
description TEXT,
|
|
65
|
+
vlm_metadata_json TEXT NOT NULL,
|
|
66
|
+
metadata_version INTEGER NOT NULL,
|
|
67
|
+
vlm_model TEXT,
|
|
68
|
+
vlm_digest TEXT,
|
|
69
|
+
prompt_hash TEXT,
|
|
70
|
+
schema_hash TEXT,
|
|
71
|
+
search_text_version INTEGER,
|
|
72
|
+
ocr_version TEXT,
|
|
73
|
+
ollama_version TEXT,
|
|
74
|
+
app_version TEXT,
|
|
75
|
+
embedding BLOB NOT NULL,
|
|
76
|
+
embedding_model TEXT,
|
|
77
|
+
embedding_digest TEXT,
|
|
78
|
+
embedding_dim INTEGER,
|
|
79
|
+
deleted_at DATETIME NOT NULL
|
|
80
|
+
)""",
|
|
81
|
+
],
|
|
82
|
+
# 6: the user's settings join keep_deleted in index_preferences, and keep_deleted may be unset (NULL) while the others are set: SQLite
|
|
83
|
+
# cannot drop a NOT NULL, so the table is made again.
|
|
84
|
+
6: [
|
|
85
|
+
"ALTER TABLE index_preferences RENAME TO index_preferences_old",
|
|
86
|
+
"""CREATE TABLE index_preferences (
|
|
87
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
88
|
+
keep_deleted INTEGER CHECK (keep_deleted IS NULL OR keep_deleted >= 0),
|
|
89
|
+
search_detail TEXT CHECK (search_detail IN ('short', 'full'))
|
|
90
|
+
)""",
|
|
91
|
+
"INSERT INTO index_preferences (id, keep_deleted) SELECT id, keep_deleted FROM index_preferences_old",
|
|
92
|
+
"DROP TABLE index_preferences_old",
|
|
93
|
+
],
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class DatabaseProblem(RuntimeError):
|
|
98
|
+
"""The database cannot be used; the message says why and what to do, in plain words."""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def describe_db_error(exc: Exception) -> str:
|
|
102
|
+
"""Explain an ``sqlite3.Error`` to the user, with what they can do about it. It never says where the files are."""
|
|
103
|
+
text = str(exc).lower()
|
|
104
|
+
if "locked" in text or "busy" in text:
|
|
105
|
+
return "The Imagent database is busy because another Imagent program is writing to it. Wait a moment and try again."
|
|
106
|
+
if "full" in text:
|
|
107
|
+
return "The disk is full, so nothing more can be saved. Free up some space and run again; finished work is kept."
|
|
108
|
+
if "readonly" in text or "read-only" in text:
|
|
109
|
+
return "The Imagent database is read-only. Check the permissions of its file and its folder."
|
|
110
|
+
if "unable to open" in text:
|
|
111
|
+
return "Imagent cannot open its database. Check that its data folder exists and that you can write to it."
|
|
112
|
+
if "disk i/o" in text:
|
|
113
|
+
return "The disk reported an input/output error. If the data lives on an external or network drive, check it is connected."
|
|
114
|
+
if "not a database" in text or "malformed" in text or "corrupt" in text:
|
|
115
|
+
return (f"The Imagent database is damaged. If you have a copy of it, restore the copy. "
|
|
116
|
+
f"Otherwise rename or delete the database file in Imagent's data folder, run {config.SETUP_COMMAND} again, and scan your folders again. "
|
|
117
|
+
"Your image files are not affected.")
|
|
118
|
+
return f"The Imagent database reported an error ({type(exc).__name__}: {exc})."
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _version(conn: sqlite3.Connection) -> int:
|
|
122
|
+
return conn.execute("PRAGMA user_version").fetchone()[0]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _statements(script: str) -> list[str]:
|
|
126
|
+
"""Split a SQL script into statements, so each can run inside one explicit transaction."""
|
|
127
|
+
statements, buffer = [], ""
|
|
128
|
+
for line in script.splitlines(keepends=True):
|
|
129
|
+
buffer += line
|
|
130
|
+
if sqlite3.complete_statement(buffer):
|
|
131
|
+
statements.append(buffer.strip())
|
|
132
|
+
buffer = ""
|
|
133
|
+
return statements
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _upgrade(conn: sqlite3.Connection) -> None:
|
|
137
|
+
"""Create the schema in a new database, or bring an older one up to ``SCHEMA_VERSION``."""
|
|
138
|
+
if _version(conn) == SCHEMA_VERSION:
|
|
139
|
+
return
|
|
140
|
+
# Python's own transaction handling is switched off while the schema changes, so the whole
|
|
141
|
+
# change is one explicit transaction. IMMEDIATE takes the write lock first, so two programs
|
|
142
|
+
# starting together cannot both migrate.
|
|
143
|
+
conn.isolation_level = None
|
|
144
|
+
try:
|
|
145
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
146
|
+
try:
|
|
147
|
+
version = _version(conn) # read again: another program may have finished the job meanwhile
|
|
148
|
+
if version > SCHEMA_VERSION:
|
|
149
|
+
raise DatabaseProblem(
|
|
150
|
+
f"This database was made by a newer version of Imagent (schema {version}; this one knows "
|
|
151
|
+
f"{SCHEMA_VERSION}). Update Imagent, or it could damage the database."
|
|
152
|
+
)
|
|
153
|
+
if version < SCHEMA_VERSION:
|
|
154
|
+
has_tables = conn.execute(
|
|
155
|
+
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'image_data'"
|
|
156
|
+
).fetchone()
|
|
157
|
+
if version == 0 and not has_tables:
|
|
158
|
+
for statement in _statements(_SCHEMA_PATH.read_text(encoding="utf-8")):
|
|
159
|
+
conn.execute(statement)
|
|
160
|
+
else:
|
|
161
|
+
for target in range(max(version, 1) + 1, SCHEMA_VERSION + 1):
|
|
162
|
+
for statement in _MIGRATIONS[target]:
|
|
163
|
+
conn.execute(statement)
|
|
164
|
+
conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
|
|
165
|
+
conn.execute("COMMIT")
|
|
166
|
+
except BaseException:
|
|
167
|
+
if conn.in_transaction:
|
|
168
|
+
conn.execute("ROLLBACK")
|
|
169
|
+
raise
|
|
170
|
+
finally:
|
|
171
|
+
conn.isolation_level = "" # back to Python's default
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _sync_error_messages(conn: sqlite3.Connection) -> None:
|
|
175
|
+
"""Make the ``error_messages`` table the same as ``pipeline/error_messages.py``. It writes only when something differs,
|
|
176
|
+
so opening the database does not take the write lock when nothing has changed."""
|
|
177
|
+
wanted = all_messages()
|
|
178
|
+
if {row["error_id"]: row["message"] for row in conn.execute("SELECT error_id, message FROM error_messages")} == wanted:
|
|
179
|
+
return
|
|
180
|
+
with conn:
|
|
181
|
+
conn.execute("DELETE FROM error_messages")
|
|
182
|
+
conn.executemany("INSERT INTO error_messages (error_id, message) VALUES (?, ?)", wanted.items())
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def init_db(db_path: str) -> sqlite3.Connection:
|
|
186
|
+
"""Open (or create) the SQLite database and bring its schema up to date.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
db_path: Absolute or relative path to the .db file.
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
An open ``sqlite3.Connection`` with ``row_factory`` set to
|
|
193
|
+
``sqlite3.Row`` so columns are accessible by name.
|
|
194
|
+
|
|
195
|
+
Raises:
|
|
196
|
+
DatabaseProblem: the database cannot be used (damaged, locked, newer than this
|
|
197
|
+
program, no space, SQLite too old); the message tells the user what to do.
|
|
198
|
+
"""
|
|
199
|
+
if sqlite3.sqlite_version_info < _MIN_SQLITE_VERSION:
|
|
200
|
+
needed = ".".join(map(str, _MIN_SQLITE_VERSION))
|
|
201
|
+
raise DatabaseProblem(
|
|
202
|
+
f"SQLite {sqlite3.sqlite_version} is too old; Imagent needs {needed} or newer. "
|
|
203
|
+
"Install a newer Python (python.org builds bundle a recent SQLite)."
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
data_dir = Path(db_path).parent
|
|
207
|
+
try:
|
|
208
|
+
data_dir.mkdir(parents=True, exist_ok=True)
|
|
209
|
+
if os.name == "posix":
|
|
210
|
+
data_dir.chmod(0o700) # the database holds file paths and GPS positions: this user only
|
|
211
|
+
except OSError as exc:
|
|
212
|
+
raise DatabaseProblem(f"Imagent cannot use its data folder ({exc.strerror or exc}). "
|
|
213
|
+
"Check that you can write to it.") from exc
|
|
214
|
+
|
|
215
|
+
conn = None
|
|
216
|
+
try:
|
|
217
|
+
# `timeout` is how long a write waits for another process's lock before raising "database is locked".
|
|
218
|
+
conn = sqlite3.connect(db_path, timeout=config.SQLITE_BUSY_TIMEOUT_S)
|
|
219
|
+
conn.row_factory = sqlite3.Row
|
|
220
|
+
# WAL mode allows concurrent reads during writes — better for long pipeline runs.
|
|
221
|
+
conn.execute("PRAGMA journal_mode = WAL")
|
|
222
|
+
conn.execute("PRAGMA foreign_keys = ON")
|
|
223
|
+
_upgrade(conn)
|
|
224
|
+
_sync_error_messages(conn)
|
|
225
|
+
except sqlite3.Error as exc:
|
|
226
|
+
if conn is not None:
|
|
227
|
+
conn.close()
|
|
228
|
+
raise DatabaseProblem(describe_db_error(exc)) from exc
|
|
229
|
+
except BaseException:
|
|
230
|
+
if conn is not None:
|
|
231
|
+
conn.close()
|
|
232
|
+
raise
|
|
233
|
+
|
|
234
|
+
if os.name == "posix":
|
|
235
|
+
Path(db_path).chmod(0o600)
|
|
236
|
+
|
|
237
|
+
return conn
|