database.py
10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""SQLite feature store; old schemas require a separate rebuild directory."""
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
import sqlite3
import numpy as np
class DatabaseManager:
def __init__(self, db_path, *, wal=False):
self.db_path = str(db_path)
Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
with self.get_connection() as conn:
columns = {r['name'] for r in conn.execute('PRAGMA table_info(images)')}
required = {'id', 'eps_id', 'design_no', 'image_url', 'cnn_vector',
'orb_desc', 'orb_pts', 'feat_version', 'source_modified', 'updated_at'}
if columns and not required.issubset(columns):
raise RuntimeError('Old images schema: use a new SQLite file and rebuild')
conn.executescript("""
CREATE TABLE IF NOT EXISTS images(
id INTEGER PRIMARY KEY AUTOINCREMENT, eps_id INTEGER NOT NULL, design_no TEXT,
image_url TEXT NOT NULL, cnn_vector BLOB NOT NULL, orb_desc BLOB,
orb_pts BLOB, feat_version INTEGER NOT NULL,
source_modified TEXT, updated_at TEXT);
CREATE TABLE IF NOT EXISTS sync_state(
id INTEGER PRIMARY KEY CHECK(id=1), cursor_modified TEXT,
last_sync_at TEXT, last_reconcile_at TEXT);
INSERT OR IGNORE INTO sync_state(id) VALUES(1);
""")
# Existing design databases retain their IDs and features.
with conn:
conn.execute('BEGIN IMMEDIATE')
columns = {r['name'] for r in conn.execute('PRAGMA table_info(images)')}
for name, kind in [('path', 'TEXT'), ('mtime', 'REAL'), ('size', 'INTEGER'),
('sha1', 'TEXT'), ('frame_ms', 'INTEGER NOT NULL DEFAULT -1')]:
if name not in columns:
conn.execute(f'ALTER TABLE images ADD COLUMN {name} {kind}')
conn.execute('CREATE UNIQUE INDEX IF NOT EXISTS images_path_frame ON images(path, frame_ms)')
conn.execute('''CREATE TABLE IF NOT EXISTS damaged_files(
path TEXT PRIMARY KEY, mtime REAL, size INTEGER, sha1 TEXT,
error_type TEXT, updated_at TEXT)''')
if wal and conn.execute('PRAGMA journal_mode=WAL').fetchone()[0] != 'wal':
raise RuntimeError('File source requires SQLite WAL mode')
@contextmanager
def get_connection(self):
conn = sqlite3.connect(self.db_path, timeout=30)
conn.row_factory = sqlite3.Row
try:
with conn:
yield conn
finally:
conn.close()
@staticmethod
def _decode(row):
result = dict(row)
for key, dtype, shape in [('cnn_vector', np.float32, (-1,)),
('orb_pts', np.float32, (-1, 2)),
('orb_desc', np.uint8, (-1, 32))]:
blob = result[key]
result[key] = np.frombuffer(blob, dtype=dtype).reshape(shape) if blob else None
return result
def all_features(self):
with self.get_connection() as conn:
return [self._decode(row) for row in conn.execute('SELECT * FROM images')]
def iter_index_rows(self):
"""Stream just the columns used by recall; never read ORB blobs at startup."""
with self.get_connection() as conn:
for row in conn.execute('SELECT id, eps_id, cnn_vector, feat_version FROM images'):
yield dict(row, cnn_vector=np.frombuffer(row['cnn_vector'], dtype=np.float32))
def file_index_snapshot(self, index, minimum_capacity, video_enabled=False):
with self.get_connection() as conn:
conn.execute('BEGIN')
count, design_count = conn.execute('SELECT COUNT(*), COUNT(*) - COUNT(path) FROM images').fetchone()
if design_count:
raise ValueError('Filesystem source requires a separate SQLite file')
where = '' if video_enabled else ' WHERE frame_ms=-1'
if where:
count = conn.execute('SELECT COUNT(*) FROM images' + where).fetchone()[0]
rows = conn.execute('SELECT id, eps_id, cnn_vector, feat_version FROM images' + where)
index.bulk_load_fixed(rows, count, minimum_capacity)
def require_design_source(self):
with self.get_connection() as conn:
if conn.execute('SELECT 1 FROM images WHERE path IS NOT NULL LIMIT 1').fetchone():
raise ValueError('Design source requires a separate SQLite file')
def file_metadata(self):
with self.get_connection() as conn:
return {row['path']: dict(row) for row in conn.execute('''
SELECT path, mtime, size, sha1 FROM images WHERE path IS NOT NULL GROUP BY path''')}
def damaged_metadata(self):
with self.get_connection() as conn:
return {row['path']: (row['mtime'], row['size']) for row in conn.execute(
'SELECT path, mtime, size FROM damaged_files')}
def search_rows(self, ids, columns):
# Stay within the SQLite bind limit on all supported runtimes.
with self.get_connection() as conn:
conn.execute('BEGIN')
result = {}
for start in range(0, len(ids), 500):
batch = ids[start:start + 500]
marks = ','.join('?' for _ in batch)
rows = conn.execute(f'SELECT {columns} FROM images WHERE id IN ({marks})', batch)
result.update((row['id'], dict(row)) for row in rows)
return result
def file_search_metadata(self, ids):
return self.search_rows(ids, 'id, eps_id, feat_version, image_url, path, mtime, size, frame_ms')
def file_search_orb(self, ids):
return self.search_rows(ids, 'id, eps_id, feat_version, orb_pts, orb_desc')
@staticmethod
def decode_orb(row):
return {'orb_pts': np.frombuffer(row['orb_pts'], np.float32).reshape(-1, 2) if row['orb_pts'] else None,
'orb_desc': np.frombuffer(row['orb_desc'], np.uint8).reshape(-1, 32) if row['orb_desc'] else None}
def max_feat_version(self):
with self.get_connection() as conn:
return conn.execute('SELECT COALESCE(MAX(feat_version), 0) FROM images').fetchone()[0]
def health_stats(self):
"""One metadata-only snapshot for the operator health endpoint."""
with self.get_connection() as conn:
return dict(conn.execute('SELECT last_sync_at, last_reconcile_at, '
'(SELECT COUNT(*) FROM images) AS total_images '
'FROM sync_state WHERE id=1').fetchone())
def get_features(self, ids):
if not ids:
return {}
with self.get_connection() as conn:
rows = conn.execute('SELECT * FROM images WHERE id IN (' +
','.join('?' for _ in ids) + ')', list(ids)).fetchall()
return {row['id']: self._decode(row) for row in rows}
def metadata(self):
with self.get_connection() as conn:
return {r['id']: dict(r) for r in conn.execute(
'SELECT id, eps_id, design_no, image_url FROM images')}
def upsert(self, design_id, eps_id, design_no, image_url, features, version, modified):
with self.get_connection() as conn:
conn.execute("""INSERT INTO images(id, eps_id, design_no, image_url, cnn_vector,
orb_desc, orb_pts, feat_version, source_modified, updated_at) VALUES(?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET eps_id=excluded.eps_id,
design_no=excluded.design_no, image_url=excluded.image_url,
cnn_vector=excluded.cnn_vector, orb_desc=excluded.orb_desc,
orb_pts=excluded.orb_pts, feat_version=excluded.feat_version,
source_modified=excluded.source_modified, updated_at=excluded.updated_at""",
(int(design_id), int(eps_id), design_no, image_url,
*self.feature_blobs(features), version,
str(modified) if modified is not None else None, datetime.now().isoformat()))
@staticmethod
def feature_blobs(features):
return tuple(None if features.get(key) is None else np.asarray(features[key], dtype=dtype).tobytes()
for key, dtype in [('cnn_vector', np.float32), ('orb_desc', np.uint8),
('orb_kp', np.float32)])
@staticmethod
def insert_file(conn, path, image_url, mtime, size, sha1, frame_ms, blobs, version):
return conn.execute('''INSERT INTO images(eps_id, image_url, cnn_vector, orb_desc, orb_pts,
feat_version, updated_at, path, mtime, size, sha1, frame_ms)
VALUES(2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(image_url, *blobs, version, datetime.now().isoformat(), path, mtime, size,
sha1, frame_ms)).lastrowid
@staticmethod
def record_damage(conn, path, mtime, size, sha1, error_type, updated_at=None):
conn.execute('''INSERT INTO damaged_files VALUES(?, ?, ?, ?, ?, ?)
ON CONFLICT(path) DO UPDATE SET mtime=excluded.mtime, size=excluded.size,
sha1=excluded.sha1, error_type=excluded.error_type, updated_at=excluded.updated_at''',
(path, mtime, size, sha1, error_type, updated_at or datetime.now().isoformat()))
def update_metadata(self, design_id, eps_id, design_no):
with self.get_connection() as conn:
conn.execute('UPDATE images SET eps_id=?, design_no=? WHERE id=?',
(eps_id, design_no, design_id))
def remove(self, design_id):
with self.get_connection() as conn:
conn.execute('DELETE FROM images WHERE id=?', (design_id,))
def state(self):
with self.get_connection() as conn:
return dict(conn.execute('SELECT * FROM sync_state WHERE id=1').fetchone())
def set_state(self, **values):
if not values.keys() <= {'cursor_modified', 'last_sync_at', 'last_reconcile_at'}:
raise ValueError('Invalid state field')
with self.get_connection() as conn:
conn.execute('UPDATE sync_state SET ' + ','.join(k + '=?' for k in values) +
' WHERE id=1', list(values.values()))