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/db/schema.sql
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
-- The latest schema, applied to a new database by db/connection.py (version SCHEMA_VERSION there).
|
|
2
|
+
-- Changing it means raising that version and adding the steps that upgrade older databases to _MIGRATIONS.
|
|
3
|
+
-- Foreign keys are switched on for every connection by db/connection.py (the pragma does nothing inside a transaction).
|
|
4
|
+
|
|
5
|
+
-- ============================================================================
|
|
6
|
+
-- TABLE: model_settings
|
|
7
|
+
--
|
|
8
|
+
-- What: The models this database was built with (a single row).
|
|
9
|
+
-- Why: Embedding vectors from different models cannot be compared, so the
|
|
10
|
+
-- models are locked together with the vectors they produced. The row is
|
|
11
|
+
-- inserted once by imagent setup and never updated; the CHECK keeps it to one row.
|
|
12
|
+
-- When: Written as the last step of setup, once all models are downloaded and verified.
|
|
13
|
+
-- ============================================================================
|
|
14
|
+
CREATE TABLE IF NOT EXISTS model_settings (
|
|
15
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
16
|
+
|
|
17
|
+
-- Ollama model names including the tag (e.g. 'nomic-embed-text:latest').
|
|
18
|
+
-- vlm_model describes images (indexing only); judge_model understands queries
|
|
19
|
+
-- (search only; it never sees an image); embedding_model is used by both.
|
|
20
|
+
-- The judge may be the same model as the VLM.
|
|
21
|
+
vlm_model TEXT NOT NULL,
|
|
22
|
+
embedding_model TEXT NOT NULL,
|
|
23
|
+
judge_model TEXT NOT NULL,
|
|
24
|
+
|
|
25
|
+
-- Ollama's digest of each model when it was set up. A different digest later
|
|
26
|
+
-- means the same tag now points at different weights; a warning is shown.
|
|
27
|
+
vlm_digest TEXT,
|
|
28
|
+
embedding_digest TEXT,
|
|
29
|
+
judge_digest TEXT,
|
|
30
|
+
|
|
31
|
+
-- Number of dimensions of the embedding model's vectors, measured at setup.
|
|
32
|
+
embedding_dim INTEGER NOT NULL,
|
|
33
|
+
|
|
34
|
+
locked_at DATETIME NOT NULL
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
-- ============================================================================
|
|
39
|
+
-- TABLE: device_settings
|
|
40
|
+
--
|
|
41
|
+
-- What: What setup measured about this computer with the locked models (a single row).
|
|
42
|
+
-- Why: How long to wait for a reply, how large a context and an image the models can take, and whether to
|
|
43
|
+
-- page models in from disk depend on the machine, so they are measured (vlm/calibration.py), not guessed.
|
|
44
|
+
-- When: Written with model_settings at the end of setup, and again (settings.vlm_digest differs) when the
|
|
45
|
+
-- vision model changes. Read by config.apply_device_settings before every run.
|
|
46
|
+
-- ============================================================================
|
|
47
|
+
CREATE TABLE IF NOT EXISTS device_settings (
|
|
48
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
49
|
+
|
|
50
|
+
-- The values every request to the models is sent with (see config.py: they must not change between requests).
|
|
51
|
+
num_ctx INTEGER NOT NULL,
|
|
52
|
+
use_mmap INTEGER NOT NULL CHECK (use_mmap IN (0, 1)),
|
|
53
|
+
|
|
54
|
+
-- Longest side, in pixels, of the image sent to the vision model.
|
|
55
|
+
image_long_edge INTEGER NOT NULL,
|
|
56
|
+
|
|
57
|
+
-- Seconds to wait for the first reply of a request; each wait that runs out is doubled (vlm/analyzer.py).
|
|
58
|
+
timeout_seconds INTEGER NOT NULL,
|
|
59
|
+
|
|
60
|
+
-- 1 when the vision and embedding models did not fit in memory together, so indexing loads one at a time; 0 when
|
|
61
|
+
-- they did; NULL when that was not tried (setup measures it again then).
|
|
62
|
+
one_model_at_a_time INTEGER CHECK (one_model_at_a_time IN (0, 1)),
|
|
63
|
+
|
|
64
|
+
-- The vision model these were measured with (its digest) and the numbers they came from, as JSON.
|
|
65
|
+
vlm_digest TEXT,
|
|
66
|
+
measurements TEXT NOT NULL,
|
|
67
|
+
|
|
68
|
+
app_version TEXT NOT NULL,
|
|
69
|
+
calibrated_at DATETIME NOT NULL
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
-- ============================================================================
|
|
74
|
+
-- TABLE: scan_roots
|
|
75
|
+
--
|
|
76
|
+
-- What: The folders the user has pointed Imagent at.
|
|
77
|
+
-- Why: A scan only reconciles the files of its own folder, so scanning one
|
|
78
|
+
-- folder can never delete what was indexed from another. Overlapping
|
|
79
|
+
-- folders are rejected, so every file belongs to exactly one root.
|
|
80
|
+
-- When: A row is added the first time a folder is scanned.
|
|
81
|
+
-- ============================================================================
|
|
82
|
+
CREATE TABLE IF NOT EXISTS scan_roots (
|
|
83
|
+
root_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
84
|
+
|
|
85
|
+
-- Resolved absolute path of the folder.
|
|
86
|
+
path TEXT NOT NULL UNIQUE,
|
|
87
|
+
|
|
88
|
+
added_at DATETIME NOT NULL,
|
|
89
|
+
last_scanned_at DATETIME
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
-- ============================================================================
|
|
94
|
+
-- TABLE: image_data
|
|
95
|
+
--
|
|
96
|
+
-- What: Stores primary metadata, file properties, and VLM analysis results
|
|
97
|
+
-- for every indexed image.
|
|
98
|
+
-- Why: Acts as the central registry of images, facilitating duplicate detection,
|
|
99
|
+
-- change detection, and serving as the primary source of natural language descriptions.
|
|
100
|
+
-- When: Populated or updated whenever an image is scanned, analyzed, or re-indexed.
|
|
101
|
+
-- ============================================================================
|
|
102
|
+
CREATE TABLE IF NOT EXISTS image_data (
|
|
103
|
+
-- Surrogate key, stable when the file is moved or renamed.
|
|
104
|
+
-- Referenced by text_embeddings and error_logs.
|
|
105
|
+
file_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
106
|
+
|
|
107
|
+
-- The folder this image was found under. Deleting a root deletes its images.
|
|
108
|
+
root_id INTEGER NOT NULL REFERENCES scan_roots(root_id) ON DELETE CASCADE,
|
|
109
|
+
|
|
110
|
+
-- Absolute path to the image on disk.
|
|
111
|
+
-- Used to locate the image and must be unique to prevent indexing the same path multiple times.
|
|
112
|
+
file_path TEXT NOT NULL UNIQUE,
|
|
113
|
+
|
|
114
|
+
-- SHA-256 hash of the file's bytes.
|
|
115
|
+
-- Used for change detection and for recognising a moved or renamed file.
|
|
116
|
+
hash TEXT NOT NULL,
|
|
117
|
+
|
|
118
|
+
-- SHA-256 hash of the picture itself: its pixels after the EXIF orientation is applied (see
|
|
119
|
+
-- image_processing/hashing.py), so it does not change when only metadata in the file does.
|
|
120
|
+
-- Used to tell an edited picture (analysed again) from a file whose EXIF or other embedded data changed (the
|
|
121
|
+
-- stored EXIF facts are refreshed, nothing is analysed), and to recognise a moved file whose metadata was edited.
|
|
122
|
+
-- NULL for a picture Pillow cannot read (analysed through a converted copy): its changes always count as edits.
|
|
123
|
+
pixel_hash TEXT,
|
|
124
|
+
|
|
125
|
+
-- One-line summary generated by the Vision-Language Model (VLM).
|
|
126
|
+
-- Used for quick previews and search result summaries.
|
|
127
|
+
short_description TEXT,
|
|
128
|
+
|
|
129
|
+
-- Detailed natural language description generated by the VLM.
|
|
130
|
+
-- Used for comprehensive search matches and details views.
|
|
131
|
+
description TEXT,
|
|
132
|
+
|
|
133
|
+
-- JSON string containing all remaining VLM metadata (e.g. tags, objects, people, OCR).
|
|
134
|
+
-- Excludes short_description and description to avoid redundancy.
|
|
135
|
+
-- Used as a flexible, evolvable storage to avoid schema migrations for structured metadata.
|
|
136
|
+
vlm_metadata_json TEXT NOT NULL,
|
|
137
|
+
|
|
138
|
+
-- Image width in pixels.
|
|
139
|
+
-- Used for filtering search results by dimensions or rendering UI layouts.
|
|
140
|
+
width INTEGER,
|
|
141
|
+
|
|
142
|
+
-- Image height in pixels.
|
|
143
|
+
-- Used for filtering search results by dimensions or rendering UI layouts.
|
|
144
|
+
height INTEGER,
|
|
145
|
+
|
|
146
|
+
-- File size of the image on disk in bytes.
|
|
147
|
+
-- Used for file stats, size filtering, and validating file status.
|
|
148
|
+
file_size INTEGER,
|
|
149
|
+
|
|
150
|
+
-- MIME type of the image (e.g., 'image/jpeg', 'image/png').
|
|
151
|
+
-- Used to identify format and determine decoder requirements.
|
|
152
|
+
mime_type TEXT,
|
|
153
|
+
|
|
154
|
+
-- File creation timestamp if the OS reports one (not available on every OS / Python version).
|
|
155
|
+
-- Used to sort or filter images chronologically by their capture/creation time.
|
|
156
|
+
created_at DATETIME,
|
|
157
|
+
|
|
158
|
+
-- Last modification timestamp of the image file on disk.
|
|
159
|
+
-- Used to check if a file has changed since it was last indexed.
|
|
160
|
+
modified_at DATETIME,
|
|
161
|
+
|
|
162
|
+
-- Timestamp indicating when this image was last indexed by Imagent.
|
|
163
|
+
-- Used to monitor index freshness and schedule maintenance/updates.
|
|
164
|
+
indexed_at DATETIME,
|
|
165
|
+
|
|
166
|
+
-- Total time taken to index this image (vision model + embeddings + DB write) in milliseconds.
|
|
167
|
+
-- Used for performance monitoring and metrics.
|
|
168
|
+
processing_time_ms INTEGER,
|
|
169
|
+
|
|
170
|
+
-- Version of the stored metadata structure.
|
|
171
|
+
-- Used to identify legacy metadata formats and trigger updates or migrations.
|
|
172
|
+
metadata_version INTEGER NOT NULL DEFAULT 1,
|
|
173
|
+
|
|
174
|
+
-- The name of the Vision-Language Model used to generate the metadata.
|
|
175
|
+
vlm_model TEXT,
|
|
176
|
+
|
|
177
|
+
-- Local capture date and time from the image's EXIF data (ISO 8601, no timezone), e.g. '2026-09-06T07:24:12'.
|
|
178
|
+
-- Used for date and time-of-day search; NULL when the image has no EXIF capture time.
|
|
179
|
+
taken_at TEXT,
|
|
180
|
+
|
|
181
|
+
-- Camera manufacturer and model from EXIF (e.g. 'iQOO', 'iQOO Neo9 Pro').
|
|
182
|
+
-- Used to filter or describe images by the device that took them; NULL when absent.
|
|
183
|
+
camera_make TEXT,
|
|
184
|
+
camera_model TEXT,
|
|
185
|
+
|
|
186
|
+
-- GPS position from EXIF in signed decimal degrees (south and west are negative).
|
|
187
|
+
-- Used for location search; NULL when the image has no GPS data.
|
|
188
|
+
gps_lat REAL,
|
|
189
|
+
gps_lon REAL,
|
|
190
|
+
|
|
191
|
+
-- What produced this record, so that records made with something older can be told apart and redone:
|
|
192
|
+
-- the vision model's digest (its exact weights), fingerprints of the prompt and of the reply schema,
|
|
193
|
+
-- the version of the way the search text is built, and the versions of the OCR library, Ollama and Imagent.
|
|
194
|
+
vlm_digest TEXT,
|
|
195
|
+
prompt_hash TEXT,
|
|
196
|
+
schema_hash TEXT,
|
|
197
|
+
search_text_version INTEGER,
|
|
198
|
+
ocr_version TEXT,
|
|
199
|
+
ollama_version TEXT,
|
|
200
|
+
app_version TEXT
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
-- Index on root_id: a scan loads every stored image of one root.
|
|
204
|
+
CREATE INDEX IF NOT EXISTS idx_image_data_root_id ON image_data(root_id);
|
|
205
|
+
|
|
206
|
+
-- Index on hash to optimize duplicate and moved-file detection queries.
|
|
207
|
+
CREATE INDEX IF NOT EXISTS idx_image_data_hash ON image_data(hash);
|
|
208
|
+
|
|
209
|
+
-- Index on modified_at to optimize delta-indexing scans detecting modified files.
|
|
210
|
+
CREATE INDEX IF NOT EXISTS idx_image_data_modified_at ON image_data(modified_at);
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
-- ============================================================================
|
|
214
|
+
-- TABLE: error_messages
|
|
215
|
+
--
|
|
216
|
+
-- What: The wording for each error id stored in backlog.error_id, with the gaps ({name}) that
|
|
217
|
+
-- backlog.error_params (JSON) fills.
|
|
218
|
+
-- Why: Lets the database be queried on its own (join backlog to this table) without the program.
|
|
219
|
+
-- When: A copy of pipeline/error_messages.py, refreshed by init_db each time the database is opened.
|
|
220
|
+
-- That file is the source: change the wording there, never here. 'tried_several_times' is the
|
|
221
|
+
-- sentence added to a message whose error_params has 'tries'. Not a foreign key of backlog,
|
|
222
|
+
-- because a row stays as it was stored when the wording changes.
|
|
223
|
+
-- ============================================================================
|
|
224
|
+
CREATE TABLE IF NOT EXISTS error_messages (
|
|
225
|
+
error_id TEXT PRIMARY KEY,
|
|
226
|
+
message TEXT NOT NULL
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
-- ============================================================================
|
|
231
|
+
-- TABLE: backlog
|
|
232
|
+
--
|
|
233
|
+
-- What: Stores files that need to be indexed or re-indexed after a filesystem scan.
|
|
234
|
+
-- Why: Decouples cheap filesystem scanning from expensive VLM processing.
|
|
235
|
+
-- When: Populated by commands/scan.py for new or modified files.
|
|
236
|
+
-- ============================================================================
|
|
237
|
+
CREATE TABLE IF NOT EXISTS backlog (
|
|
238
|
+
-- Keyed by path: a new file has no image_data row (and so no file_id) yet.
|
|
239
|
+
file_path TEXT PRIMARY KEY,
|
|
240
|
+
|
|
241
|
+
root_id INTEGER NOT NULL REFERENCES scan_roots(root_id) ON DELETE CASCADE,
|
|
242
|
+
|
|
243
|
+
-- Modification time seen by the scan that queued the file. When a later scan sees a
|
|
244
|
+
-- different one, the file changed again, so its failed attempts are forgotten.
|
|
245
|
+
modified_at DATETIME NOT NULL,
|
|
246
|
+
|
|
247
|
+
-- Number of times indexing this file failed. At config.BACKLOG_MAX_ATTEMPTS the file
|
|
248
|
+
-- is skipped until it changes. Failures caused by Ollama being unreachable do not count.
|
|
249
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
250
|
+
|
|
251
|
+
-- 'queued': indexed on the next run. 'parked': set aside because every step for its kind of
|
|
252
|
+
-- failure was tried; it is queued again when the file changes (see upsert_backlog).
|
|
253
|
+
status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'parked')),
|
|
254
|
+
|
|
255
|
+
-- Why a file was parked (e.g. 'cut_off', 'invalid_reply') and what would make it worth another try.
|
|
256
|
+
park_kind TEXT,
|
|
257
|
+
retry_when TEXT,
|
|
258
|
+
|
|
259
|
+
-- Why the most recent failure happened, shown in the indexing summary: the id of its message
|
|
260
|
+
-- (see pipeline/error_messages.py) and the values for the gaps in it (JSON). The wording is not stored.
|
|
261
|
+
error_id TEXT,
|
|
262
|
+
error_params TEXT,
|
|
263
|
+
|
|
264
|
+
-- The model and prompt versions (JSON) at the time the file was parked: when they change, a file parked for
|
|
265
|
+
-- its model's replies (retry_when = 'model_changed') is queued again.
|
|
266
|
+
park_versions TEXT,
|
|
267
|
+
|
|
268
|
+
queued_at DATETIME NOT NULL
|
|
269
|
+
);
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
-- ============================================================================
|
|
273
|
+
-- TABLE: failure_history
|
|
274
|
+
--
|
|
275
|
+
-- What: Every request whose reply had to be asked for again, with the exact reason and the
|
|
276
|
+
-- settings used, and (as kind 'resolved') the request that finally worked.
|
|
277
|
+
-- Why: Shows which steps put right which kind of failure, and what a parked file already went through.
|
|
278
|
+
-- Unlike error_logs it is never trimmed.
|
|
279
|
+
-- When: Written when an image's reply needed more than one request, whether or not it was finally indexed.
|
|
280
|
+
-- ============================================================================
|
|
281
|
+
CREATE TABLE IF NOT EXISTS failure_history (
|
|
282
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
283
|
+
file_path TEXT NOT NULL,
|
|
284
|
+
|
|
285
|
+
-- What was wrong with the reply: 'cut_off', 'invalid_reply', or 'resolved' for the request that worked.
|
|
286
|
+
kind TEXT NOT NULL,
|
|
287
|
+
|
|
288
|
+
-- Which step of the ladder for that kind made the request ('first try', 'changed sampling', ...).
|
|
289
|
+
step TEXT NOT NULL,
|
|
290
|
+
|
|
291
|
+
-- The options sent to Ollama (JSON), and what Ollama reported back.
|
|
292
|
+
options TEXT,
|
|
293
|
+
done_reason TEXT,
|
|
294
|
+
eval_count INTEGER,
|
|
295
|
+
prompt_eval_count INTEGER,
|
|
296
|
+
|
|
297
|
+
-- The problems found in the reply, and the reply itself (NULL for 'resolved').
|
|
298
|
+
detail TEXT,
|
|
299
|
+
raw_reply TEXT,
|
|
300
|
+
|
|
301
|
+
created_at DATETIME NOT NULL
|
|
302
|
+
);
|
|
303
|
+
|
|
304
|
+
CREATE INDEX IF NOT EXISTS idx_failure_history_file_path ON failure_history(file_path);
|
|
305
|
+
CREATE INDEX IF NOT EXISTS idx_failure_history_kind ON failure_history(kind);
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
-- ============================================================================
|
|
309
|
+
-- TABLE: text_embeddings
|
|
310
|
+
--
|
|
311
|
+
-- What: Stores high-dimensional vector embeddings generated from image descriptions.
|
|
312
|
+
-- Why: Enables semantic search by allowing vector similarity matches.
|
|
313
|
+
-- When: Populated when an image's description is indexed or updated.
|
|
314
|
+
-- ============================================================================
|
|
315
|
+
CREATE TABLE IF NOT EXISTS text_embeddings (
|
|
316
|
+
-- Unique identifier of the image this embedding belongs to.
|
|
317
|
+
-- References image_data(file_id) to link vector embeddings to image files.
|
|
318
|
+
file_id INTEGER PRIMARY KEY,
|
|
319
|
+
|
|
320
|
+
-- Serialized embedding vector: little-endian float32, embedding_dim values
|
|
321
|
+
-- (see model_settings). Every vector comes from the single locked model.
|
|
322
|
+
embedding BLOB NOT NULL,
|
|
323
|
+
|
|
324
|
+
-- Timestamp indicating when the embedding was generated.
|
|
325
|
+
-- Used for auditing and assessing cache/data freshness.
|
|
326
|
+
created_at DATETIME,
|
|
327
|
+
|
|
328
|
+
-- The model that made the vector (name, digest of its exact weights) and the vector's size.
|
|
329
|
+
embedding_model TEXT,
|
|
330
|
+
embedding_digest TEXT,
|
|
331
|
+
embedding_dim INTEGER,
|
|
332
|
+
|
|
333
|
+
-- Maintain database integrity by cascading deletions when an image is deleted.
|
|
334
|
+
FOREIGN KEY (file_id) REFERENCES image_data(file_id) ON DELETE CASCADE
|
|
335
|
+
);
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
-- ============================================================================
|
|
339
|
+
-- TABLE: error_logs
|
|
340
|
+
--
|
|
341
|
+
-- What: Tracks failures and unexpected errors encountered while indexing or searching.
|
|
342
|
+
-- Why: Provides a structured audit trail for debugging, monitoring, and retrying
|
|
343
|
+
-- failed operations without requiring log file parsing.
|
|
344
|
+
-- When: A row is inserted whenever the pipeline catches an error. Only the newest
|
|
345
|
+
-- config.ERROR_LOG_MAX_ROWS rows are kept.
|
|
346
|
+
-- ============================================================================
|
|
347
|
+
CREATE TABLE IF NOT EXISTS error_logs (
|
|
348
|
+
-- Auto-incrementing primary key uniquely identifying each error record.
|
|
349
|
+
-- Used to paginate, sort, and reference individual error entries.
|
|
350
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
351
|
+
|
|
352
|
+
-- The file_id of the image being processed when the error occurred, if it has an image_data row.
|
|
353
|
+
-- NULL for files that were never indexed successfully (see file_path) and for errors outside a file.
|
|
354
|
+
file_id INTEGER,
|
|
355
|
+
|
|
356
|
+
-- Absolute path to the image file being processed when the error occurred.
|
|
357
|
+
-- Stored separately from file_id so errors can be reported even when no
|
|
358
|
+
-- image_data row exists yet.
|
|
359
|
+
file_path TEXT,
|
|
360
|
+
|
|
361
|
+
-- The named stage in the application where the error was caught.
|
|
362
|
+
-- Valid values: 'pipeline' (indexing one image), 'scan', 'search',
|
|
363
|
+
-- 'query_understanding'.
|
|
364
|
+
-- Used to filter errors by stage and identify systemic bottlenecks.
|
|
365
|
+
stage TEXT NOT NULL,
|
|
366
|
+
|
|
367
|
+
-- The class or type name of the exception (e.g. 'FileNotFoundError', 'ValidationError').
|
|
368
|
+
-- Used to group and triage errors by category without parsing the message.
|
|
369
|
+
error_type TEXT NOT NULL,
|
|
370
|
+
|
|
371
|
+
-- Human-readable description of what went wrong.
|
|
372
|
+
-- Used for display in dashboards and log summaries without needing the stack trace.
|
|
373
|
+
error_message TEXT NOT NULL,
|
|
374
|
+
|
|
375
|
+
-- Full stack trace captured at the point of the exception.
|
|
376
|
+
-- Used for in-depth debugging when error_message alone is insufficient.
|
|
377
|
+
stack_trace TEXT,
|
|
378
|
+
|
|
379
|
+
-- Optional JSON blob containing additional contextual information relevant to the failure.
|
|
380
|
+
-- Examples: model name in use, timing data, partial payloads, retry count.
|
|
381
|
+
-- Kept as JSON to remain flexible without adding new schema columns for every context type.
|
|
382
|
+
metadata TEXT,
|
|
383
|
+
|
|
384
|
+
-- Timestamp (UTC) when this error was recorded.
|
|
385
|
+
-- Used for chronological filtering, rate analysis, and correlating errors with deployments.
|
|
386
|
+
created_at DATETIME NOT NULL,
|
|
387
|
+
|
|
388
|
+
-- If file_id is present, cascade deletions from image_data to keep error_logs consistent.
|
|
389
|
+
-- Errors for deleted images are removed automatically to prevent orphaned records.
|
|
390
|
+
FOREIGN KEY (file_id) REFERENCES image_data(file_id) ON DELETE CASCADE
|
|
391
|
+
);
|
|
392
|
+
|
|
393
|
+
-- Index on file_id to efficiently retrieve all errors associated with a specific image.
|
|
394
|
+
CREATE INDEX IF NOT EXISTS idx_error_logs_file_id ON error_logs(file_id);
|
|
395
|
+
|
|
396
|
+
-- Index on stage to filter and aggregate errors by stage.
|
|
397
|
+
CREATE INDEX IF NOT EXISTS idx_error_logs_stage ON error_logs(stage);
|
|
398
|
+
|
|
399
|
+
-- Index on created_at to support time-range queries and chronological browsing of errors.
|
|
400
|
+
CREATE INDEX IF NOT EXISTS idx_error_logs_created_at ON error_logs(created_at);
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
-- ============================================================================
|
|
404
|
+
-- TABLE: index_preferences
|
|
405
|
+
--
|
|
406
|
+
-- What: What the user chose about the index and about how Imagent behaves (a single row); changed in settings.
|
|
407
|
+
-- Why: keep_deleted is how many deleted pictures' analyses are kept (see deleted_analyses); 0 keeps none.
|
|
408
|
+
-- search_detail is what a search shows for each picture by default: 'short' (the one-line summary) or 'full' (the whole description).
|
|
409
|
+
-- When: keep_deleted is written at the end of setup; search_detail when the user changes it in settings. A NULL (or no row) means it was
|
|
410
|
+
-- not chosen: keep_deleted then keeps nothing, and search_detail uses the default in config.py.
|
|
411
|
+
-- ============================================================================
|
|
412
|
+
CREATE TABLE IF NOT EXISTS index_preferences (
|
|
413
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
414
|
+
keep_deleted INTEGER CHECK (keep_deleted IS NULL OR keep_deleted >= 0),
|
|
415
|
+
search_detail TEXT CHECK (search_detail IN ('short', 'full'))
|
|
416
|
+
);
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
-- ============================================================================
|
|
420
|
+
-- TABLE: deleted_analyses
|
|
421
|
+
--
|
|
422
|
+
-- What: The analysis of pictures whose file was deleted, one row per picture (by its pixel hash), newest deletions only.
|
|
423
|
+
-- Why: A picture that comes back later (copied, restored from a backup, moved into a folder added later) is recognised by its
|
|
424
|
+
-- pixels and gets this analysis again, so the vision model does not have to look at it a second time.
|
|
425
|
+
-- When: A row is added by a scan that finds an indexed image gone (the image_data row is deleted); at most
|
|
426
|
+
-- index_preferences.keep_deleted rows are kept, the oldest deletions first to go. A row is removed when it is used again.
|
|
427
|
+
-- Search never reads it. Only what an analysis is made of is kept: no path, no file hash, no EXIF, no GPS.
|
|
428
|
+
-- ============================================================================
|
|
429
|
+
CREATE TABLE IF NOT EXISTS deleted_analyses (
|
|
430
|
+
-- SHA-256 of the picture's pixels (see image_data.pixel_hash).
|
|
431
|
+
pixel_hash TEXT PRIMARY KEY,
|
|
432
|
+
|
|
433
|
+
-- The same columns as image_data, with the same meaning.
|
|
434
|
+
short_description TEXT,
|
|
435
|
+
description TEXT,
|
|
436
|
+
vlm_metadata_json TEXT NOT NULL,
|
|
437
|
+
metadata_version INTEGER NOT NULL,
|
|
438
|
+
vlm_model TEXT,
|
|
439
|
+
vlm_digest TEXT,
|
|
440
|
+
prompt_hash TEXT,
|
|
441
|
+
schema_hash TEXT,
|
|
442
|
+
search_text_version INTEGER,
|
|
443
|
+
ocr_version TEXT,
|
|
444
|
+
ollama_version TEXT,
|
|
445
|
+
app_version TEXT,
|
|
446
|
+
|
|
447
|
+
-- The same columns as text_embeddings.
|
|
448
|
+
embedding BLOB NOT NULL,
|
|
449
|
+
embedding_model TEXT,
|
|
450
|
+
embedding_digest TEXT,
|
|
451
|
+
embedding_dim INTEGER,
|
|
452
|
+
|
|
453
|
+
deleted_at DATETIME NOT NULL
|
|
454
|
+
);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# image_processing package
|
|
2
|
+
# Pillow cannot open HEIC/HEIF (iPhone photos) on its own. Registering the opener here makes it
|
|
3
|
+
# apply to every module of this package that calls Image.open.
|
|
4
|
+
from PIL import Image
|
|
5
|
+
from pillow_heif import register_heif_opener
|
|
6
|
+
|
|
7
|
+
register_heif_opener()
|
|
8
|
+
|
|
9
|
+
# Pillow refuses images above a fixed number of pixels, whatever the memory of the computer. How big an image may be
|
|
10
|
+
# is decided from the memory free at the time instead (image_processing/memory.py), so Pillow's own limit is switched off.
|
|
11
|
+
# Only when this computer will not say how much memory is free is that limit used, as Pillow itself applies it: an image of
|
|
12
|
+
# more than twice its default number of pixels is refused. It is read here, before it is switched off, not typed in.
|
|
13
|
+
PIXEL_LIMIT_WHEN_MEMORY_UNKNOWN = None if Image.MAX_IMAGE_PIXELS is None else 2 * Image.MAX_IMAGE_PIXELS
|
|
14
|
+
Image.MAX_IMAGE_PIXELS = None
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/convert.py — Make a PNG copy of a picture Pillow cannot open, with the tool the operating system has.
|
|
3
|
+
|
|
4
|
+
The tool is the operating system's own (os_specific/convert.py): macOS has ``sips``, Windows has its imaging components, and
|
|
5
|
+
Linux has none, so there nothing is converted. The copy is lossless, lives in a temporary folder and is deleted as soon as the picture
|
|
6
|
+
has been analysed (or the analysis failed). The original file is never touched.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import tempfile
|
|
15
|
+
from contextlib import contextmanager
|
|
16
|
+
from typing import Iterator
|
|
17
|
+
|
|
18
|
+
from imagent import config
|
|
19
|
+
from imagent.os_specific import system_name
|
|
20
|
+
from imagent.os_specific.convert import command as command_for
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ConversionFailed(Exception):
|
|
24
|
+
"""The picture could not be converted; the message says why, for the record."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@contextmanager
|
|
28
|
+
def converted_copy(path: str) -> Iterator[str]:
|
|
29
|
+
"""Give the path of a PNG copy of the picture at ``path``; the copy is deleted when the ``with`` block ends.
|
|
30
|
+
|
|
31
|
+
Raises ``ConversionFailed`` when this computer has no tool to convert with or the tool could not read the picture."""
|
|
32
|
+
folder = tempfile.mkdtemp(prefix="imagent-")
|
|
33
|
+
try:
|
|
34
|
+
target = os.path.join(folder, "converted.png")
|
|
35
|
+
prepared = command_for(os.path.abspath(path), target)
|
|
36
|
+
if prepared is None:
|
|
37
|
+
raise ConversionFailed(f"{system_name()} has no built-in tool that converts pictures")
|
|
38
|
+
command, extra_environment = prepared
|
|
39
|
+
try:
|
|
40
|
+
done = subprocess.run(command, capture_output=True, text=True, timeout=config.CONVERT_TIMEOUT,
|
|
41
|
+
env={**os.environ, **extra_environment})
|
|
42
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
43
|
+
raise ConversionFailed(f"{command[0]} could not be run ({type(exc).__name__}: {exc})") from exc
|
|
44
|
+
if done.returncode != 0 or not os.path.isfile(target) or os.path.getsize(target) == 0:
|
|
45
|
+
raise ConversionFailed(f"{command[0]} could not convert the picture: {(done.stderr or done.stdout).strip()[:300] or 'no output'}")
|
|
46
|
+
yield target
|
|
47
|
+
finally:
|
|
48
|
+
shutil.rmtree(folder, ignore_errors=True)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/features.py — Facts read straight from the pixels, not from the VLM.
|
|
3
|
+
|
|
4
|
+
Orientation and dominant colors are cheap to compute and more reliable than
|
|
5
|
+
asking a small model to guess them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import colorsys
|
|
11
|
+
|
|
12
|
+
from PIL import Image, ImageOps
|
|
13
|
+
|
|
14
|
+
from imagent.image_processing.preprocess import to_rgb
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
_COLOR_SAMPLE_SIZE = (160, 160)
|
|
18
|
+
_EXIF_ORIENTATION = 0x0112
|
|
19
|
+
_SIDEWAYS = (5, 6, 7, 8) # the orientations that turn the picture a quarter
|
|
20
|
+
_PALETTE_SIZE = 6
|
|
21
|
+
_MIN_COLOR_SHARE = 0.05 # a color must cover at least this fraction of the image to be listed
|
|
22
|
+
_MAX_COLORS = 5
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def extract_image_features(image_path: str) -> dict:
|
|
26
|
+
"""Return ``orientation`` ('landscape', 'portrait' or 'square') and ``dominant_colors``.
|
|
27
|
+
|
|
28
|
+
EXIF orientation is applied first, so a phone photo stored sideways is judged as displayed.
|
|
29
|
+
"""
|
|
30
|
+
with Image.open(image_path) as img:
|
|
31
|
+
width, height = img.size
|
|
32
|
+
if img.getexif().get(_EXIF_ORIENTATION, 1) in _SIDEWAYS:
|
|
33
|
+
width, height = height, width
|
|
34
|
+
ImageOps.exif_transpose(img, in_place=True) # turned where it is: a copy of the whole image is not made
|
|
35
|
+
img = to_rgb(img)
|
|
36
|
+
if abs(width - height) / max(width, height) < 0.05:
|
|
37
|
+
orientation = "square"
|
|
38
|
+
else:
|
|
39
|
+
orientation = "landscape" if width > height else "portrait"
|
|
40
|
+
return {"orientation": orientation, "dominant_colors": _dominant_colors(img)}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _dominant_colors(img: Image.Image) -> list[str]:
|
|
44
|
+
palette_image = img.resize(_COLOR_SAMPLE_SIZE).quantize(_PALETTE_SIZE, method=Image.MEDIANCUT)
|
|
45
|
+
palette = palette_image.getpalette()
|
|
46
|
+
share: dict[str, int] = {}
|
|
47
|
+
for count, index in palette_image.getcolors():
|
|
48
|
+
name = _color_name(palette[index * 3: index * 3 + 3])
|
|
49
|
+
share[name] = share.get(name, 0) + count
|
|
50
|
+
total = sum(share.values())
|
|
51
|
+
ranked = sorted(share.items(), key=lambda item: -item[1])
|
|
52
|
+
return [name for name, count in ranked if count / total >= _MIN_COLOR_SHARE][:_MAX_COLORS]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _color_name(rgb: list[int]) -> str:
|
|
56
|
+
hue, saturation, value = colorsys.rgb_to_hsv(*(channel / 255 for channel in rgb))
|
|
57
|
+
if value < 0.18:
|
|
58
|
+
return "black"
|
|
59
|
+
if saturation < 0.12:
|
|
60
|
+
if value > 0.85:
|
|
61
|
+
return "white"
|
|
62
|
+
return "light gray" if value > 0.6 else ("gray" if value > 0.35 else "dark gray")
|
|
63
|
+
degrees = hue * 360
|
|
64
|
+
if degrees < 15 or degrees >= 345:
|
|
65
|
+
base = "red" if saturation > 0.45 or value > 0.6 else "brown"
|
|
66
|
+
if saturation < 0.5 and value > 0.7:
|
|
67
|
+
base = "pink"
|
|
68
|
+
elif degrees < 40:
|
|
69
|
+
base = "orange" if value > 0.6 and saturation > 0.6 else "brown"
|
|
70
|
+
if saturation < 0.35 and value > 0.7:
|
|
71
|
+
base = "beige"
|
|
72
|
+
elif degrees < 70:
|
|
73
|
+
base = "yellow" if saturation > 0.4 else "beige"
|
|
74
|
+
elif degrees < 160:
|
|
75
|
+
base = "green"
|
|
76
|
+
elif degrees < 200:
|
|
77
|
+
base = "teal"
|
|
78
|
+
elif degrees < 255:
|
|
79
|
+
base = "blue"
|
|
80
|
+
elif degrees < 300:
|
|
81
|
+
base = "purple"
|
|
82
|
+
else:
|
|
83
|
+
base = "pink"
|
|
84
|
+
if base in ("blue", "green", "teal") and value > 0.8 and saturation < 0.55:
|
|
85
|
+
return f"light {base}"
|
|
86
|
+
if base in ("blue", "green") and value < 0.4:
|
|
87
|
+
return f"dark {base}"
|
|
88
|
+
return base
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/image_processing/hashing.py — Content hashes for change and move detection.
|
|
3
|
+
|
|
4
|
+
Always SHA-256 (stdlib): the stored hashes must be identical on every machine and install.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
|
|
9
|
+
from PIL import Image, ImageOps
|
|
10
|
+
|
|
11
|
+
# Read files in 64 KB chunks to keep memory usage bounded on large images.
|
|
12
|
+
_CHUNK_SIZE = 65_536
|
|
13
|
+
|
|
14
|
+
# The pixels are hashed in bands of about this many bytes, so no second copy of a whole picture is made.
|
|
15
|
+
_BAND_BYTES = 1_048_576
|
|
16
|
+
_PALETTE_MODES = {"P", "PA"} # their pixels are numbers into a palette: the colors are hashed, so a changed palette changes the hash
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def compute_hash(path: str) -> str:
|
|
20
|
+
"""Return the hex-encoded SHA-256 content hash of the file at *path*."""
|
|
21
|
+
hasher = hashlib.sha256()
|
|
22
|
+
|
|
23
|
+
with open(path, "rb") as fh:
|
|
24
|
+
while chunk := fh.read(_CHUNK_SIZE):
|
|
25
|
+
hasher.update(chunk)
|
|
26
|
+
|
|
27
|
+
return hasher.hexdigest()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def compute_pixel_hash(path: str) -> str:
|
|
31
|
+
"""Return the hex-encoded SHA-256 of the picture at *path* as it is looked at: its pixels after the EXIF orientation is applied.
|
|
32
|
+
|
|
33
|
+
Two files with the same pixel hash show the same picture to the vision model, whatever else their bytes hold (EXIF facts,
|
|
34
|
+
XMP, a color profile, the way the file was saved). Turning the picture by its orientation is part of it, because the model
|
|
35
|
+
sees the turned picture. Only the first frame of an animation counts, as it does in analysis. The caller makes sure the
|
|
36
|
+
picture fits in memory first (``image_processing.memory.check_image_size``).
|
|
37
|
+
|
|
38
|
+
Raises what Pillow raises for a file it cannot read."""
|
|
39
|
+
hasher = hashlib.sha256()
|
|
40
|
+
with Image.open(path) as img:
|
|
41
|
+
ImageOps.exif_transpose(img, in_place=True) # turned where it is: a copy of the whole image is not made
|
|
42
|
+
width, height = img.size
|
|
43
|
+
palette = img.mode in _PALETTE_MODES
|
|
44
|
+
hasher.update(f"{'RGBA' if palette else img.mode}:{width}x{height}".encode())
|
|
45
|
+
rows = max(_BAND_BYTES // (width * 4), 1)
|
|
46
|
+
for top in range(0, height, rows):
|
|
47
|
+
band = img.crop((0, top, width, min(top + rows, height)))
|
|
48
|
+
hasher.update((band.convert("RGBA") if palette else band).tobytes())
|
|
49
|
+
return hasher.hexdigest()
|