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/operations.py
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/db/operations.py — Low-level SQL helpers for model_settings, scan_roots, image_data, backlog,
|
|
3
|
+
text_embeddings, error_logs and failure_history.
|
|
4
|
+
|
|
5
|
+
All functions accept an open ``sqlite3.Connection`` and operate on a single row
|
|
6
|
+
(or, where named so, on a list of rows).
|
|
7
|
+
Transaction management (BEGIN / COMMIT / ROLLBACK) is the caller's responsibility.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import sqlite3
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from typing import Iterator, NamedTuple
|
|
16
|
+
|
|
17
|
+
from imagent import config
|
|
18
|
+
|
|
19
|
+
# The columns of image_data that say what produced a record (see db/schema.sql); a record without them has them empty.
|
|
20
|
+
VERSION_COLUMNS = ("vlm_digest", "prompt_hash", "schema_hash", "search_text_version", "ocr_version", "ollama_version", "app_version")
|
|
21
|
+
|
|
22
|
+
# Rows deleted per statement. SQLite limits the number of ``?`` in one statement
|
|
23
|
+
# (999 before version 3.32), so long lists are processed in chunks below that.
|
|
24
|
+
_CHUNK = 500
|
|
25
|
+
|
|
26
|
+
_BEFORE_EVERY_ID = -2 ** 63 # SQLite's smallest integer: batches are read by file_id, from the first one
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _now() -> str:
|
|
30
|
+
return datetime.now(timezone.utc).isoformat()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
# model_settings
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
def get_model_settings(conn: sqlite3.Connection) -> dict | None:
|
|
38
|
+
"""Return the locked model pair, or None when setup has not been completed."""
|
|
39
|
+
row = conn.execute(
|
|
40
|
+
"""
|
|
41
|
+
SELECT vlm_model, embedding_model, judge_model,
|
|
42
|
+
vlm_digest, embedding_digest, judge_digest, embedding_dim
|
|
43
|
+
FROM model_settings WHERE id = 1
|
|
44
|
+
"""
|
|
45
|
+
).fetchone()
|
|
46
|
+
return dict(row) if row else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def set_model_settings(conn: sqlite3.Connection, settings: dict) -> None:
|
|
50
|
+
"""Lock in the models. A plain INSERT: raises ``sqlite3.IntegrityError`` if they are already set."""
|
|
51
|
+
conn.execute(
|
|
52
|
+
"""
|
|
53
|
+
INSERT INTO model_settings
|
|
54
|
+
(id, vlm_model, embedding_model, judge_model,
|
|
55
|
+
vlm_digest, embedding_digest, judge_digest, embedding_dim, locked_at)
|
|
56
|
+
VALUES (1, :vlm_model, :embedding_model, :judge_model,
|
|
57
|
+
:vlm_digest, :embedding_digest, :judge_digest, :embedding_dim, :locked_at)
|
|
58
|
+
""",
|
|
59
|
+
{**settings, "locked_at": _now()},
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def get_device_settings(conn: sqlite3.Connection) -> dict | None:
|
|
64
|
+
"""Return what setup measured about this computer (see ``vlm.calibration``), or None when it has not been measured."""
|
|
65
|
+
row = conn.execute(
|
|
66
|
+
"SELECT num_ctx, use_mmap, image_long_edge, timeout_seconds, one_model_at_a_time, vlm_digest, measurements "
|
|
67
|
+
"FROM device_settings WHERE id = 1"
|
|
68
|
+
).fetchone()
|
|
69
|
+
if row is None:
|
|
70
|
+
return None
|
|
71
|
+
apart = row["one_model_at_a_time"]
|
|
72
|
+
return {**dict(row), "use_mmap": bool(row["use_mmap"]), "one_model_at_a_time": None if apart is None else bool(apart),
|
|
73
|
+
"measurements": json.loads(row["measurements"])}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def set_device_settings(conn: sqlite3.Connection, device: dict, vlm_digest: str | None) -> None:
|
|
77
|
+
"""Store what was measured, replacing the earlier measurement (the computer or the vision model may have changed)."""
|
|
78
|
+
conn.execute(
|
|
79
|
+
"""
|
|
80
|
+
INSERT OR REPLACE INTO device_settings
|
|
81
|
+
(id, num_ctx, use_mmap, image_long_edge, timeout_seconds, one_model_at_a_time, vlm_digest, measurements, app_version, calibrated_at)
|
|
82
|
+
VALUES (1, :num_ctx, :use_mmap, :image_long_edge, :timeout_seconds, :one_model_at_a_time, :vlm_digest, :measurements,
|
|
83
|
+
:app_version, :calibrated_at)
|
|
84
|
+
""",
|
|
85
|
+
{**device, "use_mmap": int(device["use_mmap"]), "vlm_digest": vlm_digest,
|
|
86
|
+
"one_model_at_a_time": None if device.get("one_model_at_a_time") is None else int(device["one_model_at_a_time"]),
|
|
87
|
+
"measurements": json.dumps(device["measurements"], sort_keys=True), "app_version": config.APP_VERSION,
|
|
88
|
+
"calibrated_at": _now()},
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ---------------------------------------------------------------------------
|
|
93
|
+
# scan_roots
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
def get_or_add_root(conn: sqlite3.Connection, path: str) -> int:
|
|
97
|
+
"""Return the root_id of a scanned folder, adding the folder if it is new. (A folder that is there is looked up first: with
|
|
98
|
+
AUTOINCREMENT, ``INSERT OR IGNORE`` of a folder that exists still uses up an id each time.)"""
|
|
99
|
+
row = conn.execute("SELECT root_id FROM scan_roots WHERE path = ?", (path,)).fetchone()
|
|
100
|
+
if row is None:
|
|
101
|
+
conn.execute("INSERT INTO scan_roots (path, added_at) VALUES (?, ?)", (path, _now()))
|
|
102
|
+
row = conn.execute("SELECT root_id FROM scan_roots WHERE path = ?", (path,)).fetchone()
|
|
103
|
+
return row["root_id"]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def list_roots(conn: sqlite3.Connection) -> list[dict]:
|
|
107
|
+
"""Return every scanned folder, the most recently scanned first."""
|
|
108
|
+
rows = conn.execute(
|
|
109
|
+
"SELECT root_id, path FROM scan_roots ORDER BY COALESCE(last_scanned_at, added_at) DESC"
|
|
110
|
+
).fetchall()
|
|
111
|
+
return [dict(row) for row in rows]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def mark_root_scanned(conn: sqlite3.Connection, root_id: int) -> None:
|
|
115
|
+
conn.execute("UPDATE scan_roots SET last_scanned_at = ? WHERE root_id = ?", (_now(), root_id))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------------------
|
|
119
|
+
# image_data
|
|
120
|
+
# ---------------------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
def lookup_by_path(conn: sqlite3.Connection, file_path: str) -> dict | None:
|
|
123
|
+
"""Return the stored record for a path, or None if the path is not indexed.
|
|
124
|
+
|
|
125
|
+
Used at the start of each indexing cycle to decide whether to skip,
|
|
126
|
+
update, or freshly index an image.
|
|
127
|
+
"""
|
|
128
|
+
row = conn.execute(
|
|
129
|
+
"SELECT file_id, file_path, hash, modified_at FROM image_data WHERE file_path = ?",
|
|
130
|
+
(file_path,),
|
|
131
|
+
).fetchone()
|
|
132
|
+
return dict(row) if row else None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class StoredImage(NamedTuple):
|
|
136
|
+
"""What a scan needs to know about an image that is indexed already."""
|
|
137
|
+
file_id: int
|
|
138
|
+
hash: str | None
|
|
139
|
+
modified_at: str | None
|
|
140
|
+
pixel_hash: str | None = None
|
|
141
|
+
width: int | None = None
|
|
142
|
+
height: int | None = None
|
|
143
|
+
file_size: int | None = None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
_STORED_COLUMNS = "file_id, hash, modified_at, pixel_hash, width, height, file_size"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def images_by_path(conn: sqlite3.Connection, root_id: int) -> dict[str, StoredImage]:
|
|
150
|
+
"""Every image stored under a root, by file path, for a scan to tell new, changed, moved and gone files apart.
|
|
151
|
+
|
|
152
|
+
Built row by row from the cursor: no list of all the rows is held beside the result, and each image is one small tuple."""
|
|
153
|
+
return {row[0]: StoredImage(*row[1:]) for row in conn.execute(
|
|
154
|
+
f"SELECT file_path, {_STORED_COLUMNS} FROM image_data WHERE root_id = ?", (root_id,))}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def images_outside_root(conn: sqlite3.Connection, root_id: int) -> Iterator[tuple[int, str, StoredImage]]:
|
|
158
|
+
"""Every image stored under the other folders, as ``(root_id, file_path, StoredImage)``, one row at a time: a scan looks
|
|
159
|
+
among them for the pictures that were moved into its folder."""
|
|
160
|
+
for row in conn.execute(f"SELECT root_id, file_path, {_STORED_COLUMNS} FROM image_data WHERE root_id != ?", (root_id,)):
|
|
161
|
+
yield row[0], row[1], StoredImage(*row[2:])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
_EXIF_FIELDS = ("taken_at", "camera_make", "camera_model", "gps_lat", "gps_lon")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def get_exif_fields(conn: sqlite3.Connection, file_id: int) -> dict:
|
|
168
|
+
"""The EXIF facts stored for an image (``taken_at``, ``camera_make``, ``camera_model``, ``gps_lat``, ``gps_lon``)."""
|
|
169
|
+
row = conn.execute(f"SELECT {', '.join(_EXIF_FIELDS)} FROM image_data WHERE file_id = ?", (file_id,)).fetchone()
|
|
170
|
+
return dict(row)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def upsert_image_data(conn: sqlite3.Connection, record: dict) -> int:
|
|
174
|
+
"""Insert a new image_data row or update every column of the existing one for that path.
|
|
175
|
+
|
|
176
|
+
``record`` must contain all column keys expected by the table except ``file_id``.
|
|
177
|
+
Returns the row's file_id (unchanged when the row already existed).
|
|
178
|
+
"""
|
|
179
|
+
conn.execute(
|
|
180
|
+
"""
|
|
181
|
+
INSERT INTO image_data (
|
|
182
|
+
root_id, file_path, hash, pixel_hash,
|
|
183
|
+
short_description, description, vlm_metadata_json,
|
|
184
|
+
width, height, file_size, mime_type,
|
|
185
|
+
created_at, modified_at, indexed_at,
|
|
186
|
+
processing_time_ms, metadata_version, vlm_model,
|
|
187
|
+
taken_at, camera_make, camera_model, gps_lat, gps_lon,
|
|
188
|
+
vlm_digest, prompt_hash, schema_hash, search_text_version, ocr_version, ollama_version, app_version
|
|
189
|
+
) VALUES (
|
|
190
|
+
:root_id, :file_path, :hash, :pixel_hash,
|
|
191
|
+
:short_description, :description, :vlm_metadata_json,
|
|
192
|
+
:width, :height, :file_size, :mime_type,
|
|
193
|
+
:created_at, :modified_at, :indexed_at,
|
|
194
|
+
:processing_time_ms, :metadata_version, :vlm_model,
|
|
195
|
+
:taken_at, :camera_make, :camera_model, :gps_lat, :gps_lon,
|
|
196
|
+
:vlm_digest, :prompt_hash, :schema_hash, :search_text_version, :ocr_version, :ollama_version, :app_version
|
|
197
|
+
)
|
|
198
|
+
ON CONFLICT(file_path) DO UPDATE SET
|
|
199
|
+
root_id = excluded.root_id,
|
|
200
|
+
hash = excluded.hash,
|
|
201
|
+
pixel_hash = excluded.pixel_hash,
|
|
202
|
+
short_description = excluded.short_description,
|
|
203
|
+
description = excluded.description,
|
|
204
|
+
vlm_metadata_json = excluded.vlm_metadata_json,
|
|
205
|
+
width = excluded.width,
|
|
206
|
+
height = excluded.height,
|
|
207
|
+
file_size = excluded.file_size,
|
|
208
|
+
mime_type = excluded.mime_type,
|
|
209
|
+
created_at = excluded.created_at,
|
|
210
|
+
modified_at = excluded.modified_at,
|
|
211
|
+
indexed_at = excluded.indexed_at,
|
|
212
|
+
processing_time_ms = excluded.processing_time_ms,
|
|
213
|
+
metadata_version = excluded.metadata_version,
|
|
214
|
+
vlm_model = excluded.vlm_model,
|
|
215
|
+
taken_at = excluded.taken_at,
|
|
216
|
+
camera_make = excluded.camera_make,
|
|
217
|
+
camera_model = excluded.camera_model,
|
|
218
|
+
gps_lat = excluded.gps_lat,
|
|
219
|
+
gps_lon = excluded.gps_lon,
|
|
220
|
+
vlm_digest = excluded.vlm_digest,
|
|
221
|
+
prompt_hash = excluded.prompt_hash,
|
|
222
|
+
schema_hash = excluded.schema_hash,
|
|
223
|
+
search_text_version = excluded.search_text_version,
|
|
224
|
+
ocr_version = excluded.ocr_version,
|
|
225
|
+
ollama_version = excluded.ollama_version,
|
|
226
|
+
app_version = excluded.app_version
|
|
227
|
+
""",
|
|
228
|
+
{**dict.fromkeys(VERSION_COLUMNS), **record},
|
|
229
|
+
)
|
|
230
|
+
return conn.execute(
|
|
231
|
+
"SELECT file_id FROM image_data WHERE file_path = ?", (record["file_path"],)
|
|
232
|
+
).fetchone()["file_id"]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
REUSED_COLUMNS = ("short_description", "description", "vlm_metadata_json", "metadata_version", "vlm_model", *VERSION_COLUMNS)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def find_analysis_by_pixels(conn: sqlite3.Connection, pixel_hash: str, file_path: str, wanted: dict) -> dict | None:
|
|
239
|
+
"""The analysis of another picture with the same pixels (same ``pixel_hash``), if it was made exactly the way a new one
|
|
240
|
+
would be now, so that it can be used again instead of analysing the picture a second time; None when there is none.
|
|
241
|
+
|
|
242
|
+
The indexed images are looked at first, then the analyses kept of deleted ones (``deleted_analyses``).
|
|
243
|
+
|
|
244
|
+
``wanted`` is what an analysis made now would be made with: ``vlm_model``, ``vlm_digest``, ``prompt_hash``, ``schema_hash``,
|
|
245
|
+
``search_text_version``, ``ocr_version``, ``metadata_version``, ``embedding_model``, ``embedding_digest`` and ``embedding_dim``.
|
|
246
|
+
A value that is None (not known) matches nothing. The image at ``file_path`` itself is not a candidate; of the others the one
|
|
247
|
+
indexed most recently is used. Returns the ``REUSED_COLUMNS`` of its row, with its ``embedding``, ``embedding_digest`` and
|
|
248
|
+
``embedding_dim``, and ``from_deleted``: whether it is a kept analysis of a deleted picture (``use_deleted_analysis`` then
|
|
249
|
+
takes it out of the table)."""
|
|
250
|
+
params = {**wanted, "pixel_hash": pixel_hash, "file_path": file_path}
|
|
251
|
+
row = conn.execute(
|
|
252
|
+
f"""
|
|
253
|
+
SELECT {', '.join('i.' + column for column in REUSED_COLUMNS)}, e.embedding, e.embedding_digest, e.embedding_dim, 0 AS from_deleted
|
|
254
|
+
FROM image_data i JOIN text_embeddings e ON e.file_id = i.file_id
|
|
255
|
+
WHERE i.pixel_hash = :pixel_hash AND i.file_path != :file_path
|
|
256
|
+
AND i.vlm_model = :vlm_model AND i.vlm_digest = :vlm_digest AND i.prompt_hash = :prompt_hash
|
|
257
|
+
AND i.schema_hash = :schema_hash AND i.search_text_version = :search_text_version AND i.ocr_version = :ocr_version
|
|
258
|
+
AND i.metadata_version = :metadata_version
|
|
259
|
+
AND e.embedding_model = :embedding_model AND e.embedding_digest = :embedding_digest AND e.embedding_dim = :embedding_dim
|
|
260
|
+
ORDER BY i.indexed_at DESC LIMIT 1
|
|
261
|
+
""",
|
|
262
|
+
params,
|
|
263
|
+
).fetchone()
|
|
264
|
+
if row is None:
|
|
265
|
+
row = conn.execute(
|
|
266
|
+
f"""
|
|
267
|
+
SELECT {', '.join(REUSED_COLUMNS)}, embedding, embedding_digest, embedding_dim, 1 AS from_deleted
|
|
268
|
+
FROM deleted_analyses
|
|
269
|
+
WHERE pixel_hash = :pixel_hash
|
|
270
|
+
AND vlm_model = :vlm_model AND vlm_digest = :vlm_digest AND prompt_hash = :prompt_hash
|
|
271
|
+
AND schema_hash = :schema_hash AND search_text_version = :search_text_version AND ocr_version = :ocr_version
|
|
272
|
+
AND metadata_version = :metadata_version
|
|
273
|
+
AND embedding_model = :embedding_model AND embedding_digest = :embedding_digest AND embedding_dim = :embedding_dim
|
|
274
|
+
""",
|
|
275
|
+
params,
|
|
276
|
+
).fetchone()
|
|
277
|
+
return dict(row) if row else None
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# ---------------------------------------------------------------------------
|
|
281
|
+
# deleted_analyses, index_preferences (the user's settings)
|
|
282
|
+
# ---------------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
def _get_preference(conn: sqlite3.Connection, column: str):
|
|
285
|
+
"""One column of the preferences row (``column`` is always one of the names below, never typed by the user); None when it was not chosen."""
|
|
286
|
+
row = conn.execute(f"SELECT {column} FROM index_preferences WHERE id = 1").fetchone()
|
|
287
|
+
return None if row is None else row[column]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _set_preference(conn: sqlite3.Connection, column: str, value) -> None:
|
|
291
|
+
conn.execute(f"INSERT INTO index_preferences (id, {column}) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET {column} = excluded.{column}", (value,))
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def get_keep_deleted(conn: sqlite3.Connection) -> int | None:
|
|
295
|
+
"""How many deleted pictures' analyses the user chose to keep (0: none), or None when the question was not answered yet."""
|
|
296
|
+
return _get_preference(conn, "keep_deleted")
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def set_keep_deleted(conn: sqlite3.Connection, keep: int) -> None:
|
|
300
|
+
"""Store how many deleted pictures' analyses to keep, and forget the oldest ones beyond it."""
|
|
301
|
+
_set_preference(conn, "keep_deleted", keep)
|
|
302
|
+
_prune_deleted_analyses(conn, keep)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def get_search_detail(conn: sqlite3.Connection) -> str | None:
|
|
306
|
+
"""What a search shows for each picture by default, ``"short"`` or ``"full"``, or None when the user never chose."""
|
|
307
|
+
return _get_preference(conn, "search_detail")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def set_search_detail(conn: sqlite3.Connection, detail: str) -> None:
|
|
311
|
+
_set_preference(conn, "search_detail", detail)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _prune_deleted_analyses(conn: sqlite3.Connection, keep: int) -> None:
|
|
315
|
+
conn.execute(
|
|
316
|
+
"DELETE FROM deleted_analyses WHERE pixel_hash NOT IN "
|
|
317
|
+
"(SELECT pixel_hash FROM deleted_analyses ORDER BY deleted_at DESC, rowid DESC LIMIT ?)",
|
|
318
|
+
(keep,),
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _without_copy_that_stays(conn: sqlite3.Connection, file_ids: list[int]) -> list[int]:
|
|
323
|
+
"""The ``file_ids`` whose picture (pixel hash) is not indexed under any other image that stays: the analysis of a picture that is
|
|
324
|
+
still indexed elsewhere is not a deleted picture's, and is still in use."""
|
|
325
|
+
deleting = set(file_ids)
|
|
326
|
+
hashes: dict[int, str] = {}
|
|
327
|
+
for start in range(0, len(file_ids), _CHUNK):
|
|
328
|
+
chunk = file_ids[start:start + _CHUNK]
|
|
329
|
+
rows = conn.execute(f"SELECT file_id, pixel_hash FROM image_data WHERE pixel_hash IS NOT NULL AND file_id IN ({', '.join('?' for _ in chunk)})", chunk)
|
|
330
|
+
hashes.update({row[0]: row[1] for row in rows})
|
|
331
|
+
staying: set[str] = set()
|
|
332
|
+
distinct = sorted(set(hashes.values()))
|
|
333
|
+
for start in range(0, len(distinct), _CHUNK):
|
|
334
|
+
chunk = distinct[start:start + _CHUNK]
|
|
335
|
+
rows = conn.execute(f"SELECT file_id, pixel_hash FROM image_data WHERE pixel_hash IN ({', '.join('?' for _ in chunk)})", chunk)
|
|
336
|
+
staying.update(row[1] for row in rows if row[0] not in deleting)
|
|
337
|
+
return [file_id for file_id, pixel_hash in hashes.items() if pixel_hash not in staying]
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def keep_analyses_of(conn: sqlite3.Connection, file_ids: list[int], keep: int | None) -> None:
|
|
341
|
+
"""Keep the analysis of the images ``file_ids`` (about to be deleted) in ``deleted_analyses``, the newest ``keep`` deletions
|
|
342
|
+
in all. Nothing is kept when ``keep`` is None (not chosen yet) or 0, and an image without a pixel hash is not kept: it could
|
|
343
|
+
not be found again. Nor is the analysis of a picture that another image, not among ``file_ids``, still has: it is in use.
|
|
344
|
+
Call it before ``delete_images``, in the same transaction."""
|
|
345
|
+
if not keep:
|
|
346
|
+
return
|
|
347
|
+
file_ids = _without_copy_that_stays(conn, file_ids)
|
|
348
|
+
now = _now()
|
|
349
|
+
columns = ", ".join(REUSED_COLUMNS)
|
|
350
|
+
for start in range(0, len(file_ids), _CHUNK):
|
|
351
|
+
chunk = file_ids[start:start + _CHUNK]
|
|
352
|
+
conn.execute(
|
|
353
|
+
f"""
|
|
354
|
+
INSERT OR REPLACE INTO deleted_analyses
|
|
355
|
+
(pixel_hash, {columns}, embedding, embedding_model, embedding_digest, embedding_dim, deleted_at)
|
|
356
|
+
SELECT i.pixel_hash, {', '.join('i.' + column for column in REUSED_COLUMNS)},
|
|
357
|
+
e.embedding, e.embedding_model, e.embedding_digest, e.embedding_dim, ?
|
|
358
|
+
FROM image_data i JOIN text_embeddings e ON e.file_id = i.file_id
|
|
359
|
+
WHERE i.pixel_hash IS NOT NULL AND i.file_id IN ({", ".join("?" for _ in chunk)})
|
|
360
|
+
""",
|
|
361
|
+
[now, *chunk],
|
|
362
|
+
)
|
|
363
|
+
_prune_deleted_analyses(conn, keep)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def count_deleted_analyses(conn: sqlite3.Connection) -> int:
|
|
367
|
+
"""How many deleted pictures' analyses are kept."""
|
|
368
|
+
return conn.execute("SELECT COUNT(*) FROM deleted_analyses").fetchone()[0]
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def clear_deleted_analyses(conn: sqlite3.Connection) -> int:
|
|
372
|
+
"""Forget every kept analysis of a deleted picture (the user's choice of how many to keep is left as it is). Returns how many were forgotten."""
|
|
373
|
+
return conn.execute("DELETE FROM deleted_analyses").rowcount
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def use_deleted_analysis(conn: sqlite3.Connection, pixel_hash: str) -> None:
|
|
377
|
+
"""Take a kept analysis out of ``deleted_analyses``: its picture is indexed again, so it is no longer a deleted one."""
|
|
378
|
+
conn.execute("DELETE FROM deleted_analyses WHERE pixel_hash = ?", (pixel_hash,))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def update_image_location(conn: sqlite3.Connection, file_id: int, root_id: int, file_path: str, modified_at: str) -> None:
|
|
382
|
+
"""Point an already-indexed image at its new path, under ``root_id`` (a move or rename of the same picture)."""
|
|
383
|
+
conn.execute(
|
|
384
|
+
"UPDATE image_data SET root_id = ?, file_path = ?, modified_at = ? WHERE file_id = ?",
|
|
385
|
+
(root_id, file_path, modified_at, file_id),
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def refresh_image_file(conn: sqlite3.Connection, file_id: int, file_hash: str, details: dict) -> None:
|
|
390
|
+
"""Bring what is stored about the file in line with the file, for a picture that did not change: its bytes hash, size,
|
|
391
|
+
timestamps and EXIF facts. ``details`` is what ``extract_file_metadata`` returns. Nothing about the analysis is touched."""
|
|
392
|
+
conn.execute(
|
|
393
|
+
"""
|
|
394
|
+
UPDATE image_data SET hash = :hash, width = :width, height = :height, file_size = :file_size, mime_type = :mime_type,
|
|
395
|
+
created_at = :created_at, modified_at = :modified_at,
|
|
396
|
+
taken_at = :taken_at, camera_make = :camera_make, camera_model = :camera_model, gps_lat = :gps_lat, gps_lon = :gps_lon
|
|
397
|
+
WHERE file_id = :file_id
|
|
398
|
+
""",
|
|
399
|
+
{**details, "hash": file_hash, "file_id": file_id},
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def update_image_modified_at(conn: sqlite3.Connection, file_id: int, modified_at: str) -> None:
|
|
404
|
+
"""Update the stored modification timestamp of an image whose content did not change."""
|
|
405
|
+
conn.execute(
|
|
406
|
+
"UPDATE image_data SET modified_at = ? WHERE file_id = ?",
|
|
407
|
+
(modified_at, file_id),
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def count_images(conn: sqlite3.Connection) -> int:
|
|
412
|
+
"""How many images are indexed, in every scanned folder."""
|
|
413
|
+
return conn.execute("SELECT COUNT(*) AS n FROM image_data").fetchone()["n"]
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def delete_images(conn: sqlite3.Connection, file_ids: list[int]) -> int:
|
|
417
|
+
"""Delete image_data rows by file_id (embeddings and error logs follow); returns the count."""
|
|
418
|
+
deleted = 0
|
|
419
|
+
for start in range(0, len(file_ids), _CHUNK):
|
|
420
|
+
chunk = file_ids[start:start + _CHUNK]
|
|
421
|
+
placeholders = ", ".join("?" for _ in chunk)
|
|
422
|
+
deleted += conn.execute(f"DELETE FROM image_data WHERE file_id IN ({placeholders})", chunk).rowcount
|
|
423
|
+
return deleted
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def root_stats(conn: sqlite3.Connection, root_id: int) -> dict:
|
|
427
|
+
"""What the index holds for one scanned folder: ``images`` indexed, their ``bytes`` on disk, the ``analysis_ms`` spent
|
|
428
|
+
analysing them, and the files ``queued`` to be indexed."""
|
|
429
|
+
row = conn.execute(
|
|
430
|
+
"SELECT COUNT(*) AS images, COALESCE(SUM(file_size), 0) AS bytes, COALESCE(SUM(processing_time_ms), 0) AS analysis_ms "
|
|
431
|
+
"FROM image_data WHERE root_id = ?", (root_id,)).fetchone()
|
|
432
|
+
queued = conn.execute("SELECT COUNT(*) FROM backlog WHERE root_id = ?", (root_id,)).fetchone()[0]
|
|
433
|
+
return {**dict(row), "queued": queued}
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def count_keepable_analyses(conn: sqlite3.Connection, root_ids: list[int]) -> int:
|
|
437
|
+
"""How many different pictures of the folders ``root_ids`` ``keep_analyses_of`` could keep (those with a pixel hash and an embedding,
|
|
438
|
+
that no image outside these folders has too)."""
|
|
439
|
+
marks = ", ".join("?" for _ in root_ids)
|
|
440
|
+
return conn.execute(
|
|
441
|
+
f"SELECT COUNT(DISTINCT i.pixel_hash) FROM image_data i JOIN text_embeddings e ON e.file_id = i.file_id "
|
|
442
|
+
f"WHERE i.pixel_hash IS NOT NULL AND i.root_id IN ({marks}) "
|
|
443
|
+
f"AND NOT EXISTS (SELECT 1 FROM image_data o WHERE o.pixel_hash = i.pixel_hash AND o.root_id NOT IN ({marks}))",
|
|
444
|
+
[*root_ids, *root_ids]).fetchone()[0]
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def image_ids_in_roots(conn: sqlite3.Connection, root_ids: list[int]) -> list[int]:
|
|
448
|
+
"""The file_id of every indexed image of the folders ``root_ids``."""
|
|
449
|
+
marks = ", ".join("?" for _ in root_ids)
|
|
450
|
+
return [row[0] for row in conn.execute(f"SELECT file_id FROM image_data WHERE root_id IN ({marks})", root_ids)]
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def delete_roots(conn: sqlite3.Connection, root_ids: list[int]) -> int:
|
|
454
|
+
"""Remove the folders ``root_ids`` from the scanned folders; their images (with embeddings and error logs) and queued files go with them.
|
|
455
|
+
Returns how many folders were removed. To keep the analyses of the images, call ``keep_analyses_of`` first, in the same transaction."""
|
|
456
|
+
marks = ", ".join("?" for _ in root_ids)
|
|
457
|
+
return conn.execute(f"DELETE FROM scan_roots WHERE root_id IN ({marks})", root_ids).rowcount
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
# ---------------------------------------------------------------------------
|
|
461
|
+
# backlog
|
|
462
|
+
# ---------------------------------------------------------------------------
|
|
463
|
+
|
|
464
|
+
def _dump_params(params: dict | None) -> str | None:
|
|
465
|
+
return json.dumps(params, sort_keys=True) if params else None
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _with_error_params(row: sqlite3.Row) -> dict:
|
|
469
|
+
"""``row`` as a dict whose ``error_params`` is the dict that was stored (empty when there were none)."""
|
|
470
|
+
item = dict(row)
|
|
471
|
+
item["error_params"] = json.loads(item["error_params"]) if item["error_params"] else {}
|
|
472
|
+
return item
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def upsert_backlog(conn: sqlite3.Connection, file_path: str, root_id: int, modified_at: str) -> None:
|
|
476
|
+
"""Queue a file for indexing. If the file changed since it was last queued, its failures are forgotten (a parked file is queued again)."""
|
|
477
|
+
conn.execute(
|
|
478
|
+
"""
|
|
479
|
+
INSERT INTO backlog (file_path, root_id, modified_at, queued_at)
|
|
480
|
+
VALUES (?, ?, ?, ?)
|
|
481
|
+
ON CONFLICT(file_path) DO UPDATE SET
|
|
482
|
+
root_id = excluded.root_id,
|
|
483
|
+
attempts = CASE WHEN backlog.modified_at != excluded.modified_at THEN 0 ELSE backlog.attempts END,
|
|
484
|
+
status = CASE WHEN backlog.modified_at != excluded.modified_at THEN 'queued' ELSE backlog.status END,
|
|
485
|
+
park_kind = CASE WHEN backlog.modified_at != excluded.modified_at THEN NULL ELSE backlog.park_kind END,
|
|
486
|
+
retry_when = CASE WHEN backlog.modified_at != excluded.modified_at THEN NULL ELSE backlog.retry_when END,
|
|
487
|
+
error_id = CASE WHEN backlog.modified_at != excluded.modified_at THEN NULL ELSE backlog.error_id END,
|
|
488
|
+
error_params = CASE WHEN backlog.modified_at != excluded.modified_at THEN NULL ELSE backlog.error_params END,
|
|
489
|
+
modified_at = excluded.modified_at
|
|
490
|
+
""",
|
|
491
|
+
(file_path, root_id, modified_at, _now()),
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def get_backlog(conn: sqlite3.Connection, max_attempts: int) -> list[dict]:
|
|
496
|
+
"""Return the queued backlog rows (file_path, root_id and the modified_at the scan saw) that have failed fewer than ``max_attempts`` times (parked files are not queued)."""
|
|
497
|
+
rows = conn.execute(
|
|
498
|
+
"SELECT file_path, root_id, modified_at FROM backlog WHERE status = 'queued' AND attempts < ? ORDER BY file_path",
|
|
499
|
+
(max_attempts,),
|
|
500
|
+
).fetchall()
|
|
501
|
+
return [dict(row) for row in rows]
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def get_exhausted_backlog(conn: sqlite3.Connection, max_attempts: int) -> list[dict]:
|
|
505
|
+
"""Return the backlog rows that could not be indexed, with their last error (``error_id`` and its ``error_params`` as a dict): parked, failed ``max_attempts`` times,
|
|
506
|
+
or left queued for the next run after every try for their kind of failure (``park_kind`` says which, see ``record_backlog_failure``)."""
|
|
507
|
+
rows = conn.execute(
|
|
508
|
+
"SELECT file_path, error_id, error_params, park_kind FROM backlog "
|
|
509
|
+
"WHERE status = 'parked' OR attempts >= ? OR park_kind IS NOT NULL ORDER BY file_path",
|
|
510
|
+
(max_attempts,),
|
|
511
|
+
).fetchall()
|
|
512
|
+
return [_with_error_params(row) for row in rows]
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def refund_backlog_attempts(conn: sqlite3.Connection, file_paths: list[str]) -> None:
|
|
516
|
+
"""Give back the attempt each of these files lost, because the failure turned out not to be theirs (a drive that went away)."""
|
|
517
|
+
for start in range(0, len(file_paths), _CHUNK):
|
|
518
|
+
chunk = file_paths[start:start + _CHUNK]
|
|
519
|
+
placeholders = ", ".join("?" for _ in chunk)
|
|
520
|
+
conn.execute(f"UPDATE backlog SET attempts = MAX(attempts - 1, 0) WHERE file_path IN ({placeholders})", chunk)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def park_backlog(conn: sqlite3.Connection, file_path: str, kind: str, error_id: str, retry_when: str,
|
|
524
|
+
versions: dict | None = None, params: dict | None = None) -> None:
|
|
525
|
+
"""Set a file aside because every step for its kind of failure was tried.
|
|
526
|
+
|
|
527
|
+
``error_id`` and ``params`` say why (see ``pipeline/error_messages.py``); only these are stored, not the wording.
|
|
528
|
+
|
|
529
|
+
``retry_when`` says what would make another try worthwhile ('model_changed': a different model or prompt, judged
|
|
530
|
+
by ``versions``, the versions at the time; 'file_changed'; 'on_request'). The file is queued again when it changes
|
|
531
|
+
(``upsert_backlog``), when its versions change (``requeue_changed_parked``) or on request (``requeue_parked``).
|
|
532
|
+
"""
|
|
533
|
+
conn.execute(
|
|
534
|
+
"UPDATE backlog SET status = 'parked', park_kind = ?, error_id = ?, error_params = ?, retry_when = ?, park_versions = ? "
|
|
535
|
+
"WHERE file_path = ?",
|
|
536
|
+
(kind, error_id, _dump_params(params), retry_when, json.dumps(versions, sort_keys=True) if versions else None, file_path),
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def requeue_changed_parked(conn: sqlite3.Connection, versions: dict) -> int:
|
|
541
|
+
"""Queue again the files parked because of the model's replies, if the versions they were parked with are not ``versions`` any more."""
|
|
542
|
+
now = json.dumps(versions, sort_keys=True)
|
|
543
|
+
rows = conn.execute(
|
|
544
|
+
"SELECT file_path FROM backlog WHERE status = 'parked' AND retry_when = 'model_changed' "
|
|
545
|
+
"AND COALESCE(park_versions, '') != ?", (now,)).fetchall()
|
|
546
|
+
return requeue_parked(conn, paths=[row["file_path"] for row in rows])
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def list_parked(conn: sqlite3.Connection) -> list[dict]:
|
|
550
|
+
"""Every parked file with the kind of failure and the error (``error_id`` and its ``error_params`` as a dict)."""
|
|
551
|
+
rows = conn.execute(
|
|
552
|
+
"SELECT file_path, park_kind, error_id, error_params, retry_when FROM backlog WHERE status = 'parked' ORDER BY park_kind, file_path"
|
|
553
|
+
).fetchall()
|
|
554
|
+
return [_with_error_params(row) for row in rows]
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def requeue_parked(conn: sqlite3.Connection, kind: str | None = None, paths: list[str] | None = None) -> int:
|
|
558
|
+
"""Queue parked files again with a clean slate: all of them, those of one ``kind``, or the given ``paths``. Returns how many."""
|
|
559
|
+
where, params = "status = 'parked'", []
|
|
560
|
+
if kind is not None:
|
|
561
|
+
where += " AND park_kind = ?"
|
|
562
|
+
params.append(kind)
|
|
563
|
+
sql = ("UPDATE backlog SET status = 'queued', attempts = 0, park_kind = NULL, retry_when = NULL, "
|
|
564
|
+
"park_versions = NULL, error_id = NULL, error_params = NULL WHERE ")
|
|
565
|
+
if paths is None:
|
|
566
|
+
return conn.execute(sql + where, params).rowcount
|
|
567
|
+
requeued = 0
|
|
568
|
+
for start in range(0, len(paths), _CHUNK): # SQLite allows only so many ? in one statement
|
|
569
|
+
chunk = paths[start:start + _CHUNK]
|
|
570
|
+
placeholders = ", ".join("?" for _ in chunk)
|
|
571
|
+
requeued += conn.execute(f"{sql}{where} AND file_path IN ({placeholders})", [*params, *chunk]).rowcount
|
|
572
|
+
return requeued
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def add_failure_history(conn: sqlite3.Connection, file_path: str, attempts: list[dict]) -> None:
|
|
576
|
+
"""Record the requests made for one image, if any of them had a reply that had to be asked for again.
|
|
577
|
+
|
|
578
|
+
``attempts`` is the record kept by ``vlm.analyzer``. A request that worked after others failed is stored as 'resolved'.
|
|
579
|
+
"""
|
|
580
|
+
if not any(attempt["kind"] for attempt in attempts):
|
|
581
|
+
return
|
|
582
|
+
conn.executemany(
|
|
583
|
+
"""
|
|
584
|
+
INSERT INTO failure_history
|
|
585
|
+
(file_path, kind, step, options, done_reason, eval_count, prompt_eval_count, detail, raw_reply, created_at)
|
|
586
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
587
|
+
""",
|
|
588
|
+
[
|
|
589
|
+
(file_path, attempt["kind"] or "resolved", attempt["step"], json.dumps(attempt["options"]), attempt["done_reason"],
|
|
590
|
+
attempt["eval_count"], attempt["prompt_eval_count"], attempt["detail"] or None, attempt["raw_reply"], _now())
|
|
591
|
+
for attempt in attempts
|
|
592
|
+
],
|
|
593
|
+
)
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def get_backlog_paths_for_root(conn: sqlite3.Connection, root_id: int) -> list[str]:
|
|
597
|
+
rows = conn.execute("SELECT file_path FROM backlog WHERE root_id = ?", (root_id,)).fetchall()
|
|
598
|
+
return [row["file_path"] for row in rows]
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def delete_backlog(conn: sqlite3.Connection, file_path: str) -> None:
|
|
602
|
+
"""Remove a backlog row once it has been processed (or no longer needs indexing)."""
|
|
603
|
+
conn.execute("DELETE FROM backlog WHERE file_path = ?", (file_path,))
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def delete_backlog_paths(conn: sqlite3.Connection, file_paths: list[str]) -> None:
|
|
607
|
+
for start in range(0, len(file_paths), _CHUNK):
|
|
608
|
+
chunk = file_paths[start:start + _CHUNK]
|
|
609
|
+
placeholders = ", ".join("?" for _ in chunk)
|
|
610
|
+
conn.execute(f"DELETE FROM backlog WHERE file_path IN ({placeholders})", chunk)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def record_backlog_failure(conn: sqlite3.Connection, file_path: str, error_id: str, count_attempt: bool,
|
|
614
|
+
kind: str | None = None, params: dict | None = None) -> None:
|
|
615
|
+
"""Remember why indexing a file failed, as an ``error_id`` and the ``params`` for its message; ``count_attempt`` is False when the file is not to blame.
|
|
616
|
+
|
|
617
|
+
``kind`` is given when every try for the failure was made and the file stays queued for the next run all the same
|
|
618
|
+
(the machine was to blame, not the file): it is what lets the user be told that the file could not be indexed."""
|
|
619
|
+
conn.execute(
|
|
620
|
+
"UPDATE backlog SET attempts = attempts + ?, error_id = ?, error_params = ?, park_kind = ? WHERE file_path = ?",
|
|
621
|
+
(1 if count_attempt else 0, error_id, _dump_params(params), kind, file_path),
|
|
622
|
+
)
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
# ---------------------------------------------------------------------------
|
|
626
|
+
# text_embeddings
|
|
627
|
+
# ---------------------------------------------------------------------------
|
|
628
|
+
|
|
629
|
+
def upsert_text_embedding(conn: sqlite3.Connection, file_id: int, embedding_bytes: bytes,
|
|
630
|
+
model: str | None = None, digest: str | None = None, dim: int | None = None) -> None:
|
|
631
|
+
"""Insert or update the serialised embedding for an image, with the model that made it (name, digest) and its size.
|
|
632
|
+
|
|
633
|
+
``embedding_bytes`` should be a packed array of little-endian float32
|
|
634
|
+
(see ``pipeline.serialisation.serialize_embedding``).
|
|
635
|
+
"""
|
|
636
|
+
conn.execute(
|
|
637
|
+
"""
|
|
638
|
+
INSERT INTO text_embeddings (file_id, embedding, created_at, embedding_model, embedding_digest, embedding_dim)
|
|
639
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
640
|
+
ON CONFLICT(file_id) DO UPDATE SET
|
|
641
|
+
embedding = excluded.embedding,
|
|
642
|
+
created_at = excluded.created_at,
|
|
643
|
+
embedding_model = excluded.embedding_model,
|
|
644
|
+
embedding_digest = excluded.embedding_digest,
|
|
645
|
+
embedding_dim = excluded.embedding_dim
|
|
646
|
+
""",
|
|
647
|
+
(file_id, embedding_bytes, _now(), model, digest, dim),
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def count_embeddings(conn: sqlite3.Connection) -> int:
|
|
652
|
+
return conn.execute("SELECT COUNT(*) AS n FROM text_embeddings").fetchone()["n"]
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def iter_embedding_batches(conn: sqlite3.Connection, size: int) -> Iterator[list[sqlite3.Row]]:
|
|
656
|
+
"""Every stored (file_id, embedding blob) row, ``size`` rows at a time, in file_id order.
|
|
657
|
+
|
|
658
|
+
Only one batch is in memory at a time, however many images are indexed."""
|
|
659
|
+
last = _BEFORE_EVERY_ID
|
|
660
|
+
while True:
|
|
661
|
+
rows = conn.execute("SELECT file_id, embedding FROM text_embeddings WHERE file_id > ? ORDER BY file_id LIMIT ?", (last, size)).fetchall()
|
|
662
|
+
if not rows:
|
|
663
|
+
return
|
|
664
|
+
yield rows
|
|
665
|
+
last = rows[-1]["file_id"]
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def get_image_summary(conn: sqlite3.Connection, file_id: int) -> dict | None:
|
|
669
|
+
"""Return display/reconstruction fields for a single image.
|
|
670
|
+
|
|
671
|
+
Used by search to present results: its descriptions, the file's properties and EXIF facts, and the folder it was found under.
|
|
672
|
+
"""
|
|
673
|
+
row = conn.execute(
|
|
674
|
+
"""
|
|
675
|
+
SELECT i.file_id, i.file_path, i.short_description, i.description, i.vlm_metadata_json,
|
|
676
|
+
i.width, i.height, i.file_size, i.mime_type, i.taken_at, i.modified_at,
|
|
677
|
+
i.camera_make, i.camera_model, i.gps_lat, i.gps_lon, i.pixel_hash, r.path AS root_path
|
|
678
|
+
FROM image_data i JOIN scan_roots r ON r.root_id = i.root_id
|
|
679
|
+
WHERE i.file_id = ?
|
|
680
|
+
""",
|
|
681
|
+
(file_id,),
|
|
682
|
+
).fetchone()
|
|
683
|
+
return dict(row) if row else None
|