database.py
5.62 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
"""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):
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, 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);
""")
@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 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):
def blob(key, dtype):
value = features.get(key)
return None if value is None else np.asarray(value, dtype=dtype).tobytes()
with self.get_connection() as conn:
conn.execute("""INSERT INTO images 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,
blob('cnn_vector', np.float32), blob('orb_desc', np.uint8),
blob('orb_kp', np.float32), version,
str(modified) if modified is not None else None, 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()))