-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.py
More file actions
422 lines (348 loc) · 14.5 KB
/
database.py
File metadata and controls
422 lines (348 loc) · 14.5 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import sqlite3
import numpy as np
import json
from typing import List, Tuple, Optional
class FaceDatabase:
"""Database manager for storing face embeddings and names."""
def __init__(self, db_path: str = "faces.db"):
self.db_path = db_path
self.init_database()
def init_database(self):
"""Initialize the database with the faces table."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS faces (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
embedding TEXT NOT NULL,
list_type TEXT DEFAULT 'none',
photo_path TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Add list_type column if it doesn't exist (for existing databases)
try:
cursor.execute('ALTER TABLE faces ADD COLUMN list_type TEXT DEFAULT "none"')
except sqlite3.OperationalError:
pass # Column already exists
# Add photo_path column if it doesn't exist
try:
cursor.execute('ALTER TABLE faces ADD COLUMN photo_path TEXT')
except sqlite3.OperationalError:
pass # Column already exists
# Create notifications table
cursor.execute('''
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
screenshot_path TEXT NOT NULL,
face_encoding TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status TEXT DEFAULT 'pending'
)
''')
# Create settings table for email config
cursor.execute('''
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)
''')
conn.commit()
conn.close()
def add_face(self, name: str, embedding: np.ndarray, list_type: str = 'none', photo_path: str = None) -> bool:
"""
Add a face embedding with a name to the database.
Args:
name: Name associated with the face
embedding: 128-dimensional face embedding vector
list_type: 'whitelist', 'blacklist', or 'none' (default)
photo_path: Path to the photo file (optional)
Returns:
True if successful, False otherwise
"""
try:
# Convert numpy array to JSON string
embedding_json = json.dumps(embedding.tolist())
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO faces (name, embedding, list_type, photo_path)
VALUES (?, ?, ?, ?)
''', (name, embedding_json, list_type, photo_path))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error adding face: {e}")
return False
def add_face_azure(self, name: str, person_id: str, list_type: str = 'none', photo_path: str = None) -> bool:
"""
Add a face using Azure person ID (instead of local embedding).
Args:
name: Name associated with the face
person_id: Azure Face API person ID
list_type: 'whitelist', 'blacklist', or 'none' (default)
photo_path: Path to the photo file (optional)
Returns:
True if successful, False otherwise
"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Store person_id in embedding field (as JSON string for compatibility)
cursor.execute('''
INSERT INTO faces (name, embedding, list_type, photo_path)
VALUES (?, ?, ?, ?)
''', (name, json.dumps({'azure_person_id': person_id}), list_type, photo_path))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error adding Azure face: {e}")
return False
def get_all_faces(self) -> List[Tuple[int, str, np.ndarray, str, str]]:
"""
Retrieve all face embeddings from the database.
Returns:
List of tuples (id, name, embedding, list_type, photo_path)
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT id, name, embedding, COALESCE(list_type, "none"), photo_path FROM faces')
rows = cursor.fetchall()
faces = []
for row in rows:
face_id, name, embedding_json, list_type, photo_path = row
embedding = np.array(json.loads(embedding_json))
faces.append((face_id, name, embedding, list_type, photo_path))
conn.close()
return faces
def get_faces_by_list_type(self, list_type: str) -> List[Tuple[int, str, np.ndarray, str]]:
"""
Get faces by list type (whitelist, blacklist, or none).
Args:
list_type: 'whitelist', 'blacklist', or 'none'
Returns:
List of tuples (id, name, embedding, photo_path)
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT id, name, embedding, photo_path FROM faces WHERE COALESCE(list_type, "none") = ?', (list_type,))
rows = cursor.fetchall()
faces = []
for row in rows:
face_id, name, embedding_json, photo_path = row
embedding = np.array(json.loads(embedding_json))
faces.append((face_id, name, embedding, photo_path))
conn.close()
return faces
def set_list_type(self, name: str, list_type: str) -> bool:
"""
Set the list type for a face (whitelist, blacklist, or none).
Args:
name: Name of the face
list_type: 'whitelist', 'blacklist', or 'none'
Returns:
True if successful, False otherwise
"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('UPDATE faces SET list_type = ? WHERE name = ?', (list_type, name))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error setting list type: {e}")
return False
def find_match(self, query_embedding: np.ndarray, threshold: float = 0.6,
use_whitelist: bool = False, use_blacklist: bool = False) -> Optional[Tuple[str, float]]:
"""
Find the best matching face in the database.
Args:
query_embedding: Face embedding to match
threshold: Similarity threshold (lower is more similar, 0.6 is default)
use_whitelist: If True, only search in whitelist
use_blacklist: If True, exclude blacklist from search
Returns:
Tuple of (name, distance) if match found, None otherwise
"""
if use_whitelist:
all_faces = [(f[0], f[1], f[2]) for f in self.get_all_faces() if f[3] == 'whitelist']
else:
all_faces = self.get_all_faces()
if not all_faces:
return None
# Filter out blacklist if needed
if use_blacklist:
blacklist_names = {f[1] for f in self.get_faces_by_list_type('blacklist')}
all_faces = [(f[0], f[1], f[2]) for f in all_faces if f[1] not in blacklist_names]
best_match = None
best_distance = float('inf')
for face_id, name, stored_embedding in all_faces:
# Calculate Euclidean distance (face_recognition uses this)
distance = np.linalg.norm(query_embedding - stored_embedding)
if distance < best_distance:
best_distance = distance
best_match = (name, distance)
# Check if best match is within threshold
if best_match and best_match[1] <= threshold:
return best_match
return None
def delete_face(self, name: str) -> bool:
"""
Delete all faces with a given name.
Args:
name: Name of the face to delete
Returns:
True if successful, False otherwise
"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('DELETE FROM faces WHERE name = ?', (name,))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error deleting face: {e}")
return False
def clear_all_faces(self) -> bool:
"""
Delete all faces from the database.
Returns:
True if successful, False otherwise
"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('DELETE FROM faces')
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error clearing database: {e}")
return False
def add_notification(self, screenshot_path: str, face_encoding: np.ndarray = None) -> int:
"""
Add a notification for a detected unknown face.
Args:
screenshot_path: Path to the screenshot
face_encoding: Face encoding (optional)
Returns:
Notification ID
"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
encoding_json = None
if face_encoding is not None:
encoding_json = json.dumps(face_encoding.tolist())
cursor.execute('''
INSERT INTO notifications (screenshot_path, face_encoding)
VALUES (?, ?)
''', (screenshot_path, encoding_json))
notification_id = cursor.lastrowid
conn.commit()
conn.close()
return notification_id
except Exception as e:
print(f"Error adding notification: {e}")
return None
def get_notifications(self) -> List[Tuple[int, str, str, str, str]]:
"""
Get all notifications.
Returns:
List of tuples (id, screenshot_path, face_encoding, created_at, status)
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT id, screenshot_path, face_encoding, created_at, status FROM notifications ORDER BY created_at DESC')
rows = cursor.fetchall()
conn.close()
return rows
def update_notification_status(self, notification_id: int, status: str) -> bool:
"""Update notification status."""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('UPDATE notifications SET status = ? WHERE id = ?', (status, notification_id))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error updating notification: {e}")
return False
def clear_all_notifications(self) -> int:
"""Clear all notifications from the database. Returns number of rows deleted."""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('DELETE FROM notifications')
rows_deleted = cursor.rowcount
conn.commit()
conn.close()
return rows_deleted
except Exception as e:
print(f"Error clearing notifications: {e}")
return 0
def get_notification_screenshot_paths(self) -> List[str]:
"""Get all notification screenshot paths."""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT screenshot_path FROM notifications')
paths = [row[0] for row in cursor.fetchall()]
conn.close()
return paths
except Exception as e:
print(f"Error getting notification paths: {e}")
return []
def delete_notification(self, notification_id: int) -> bool:
"""Delete a single notification by ID."""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('DELETE FROM notifications WHERE id = ?', (notification_id,))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error deleting notification: {e}")
return False
def get_notification_by_id(self, notification_id: int) -> Optional[Tuple]:
"""Get a notification by ID."""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT id, screenshot_path, face_encoding, created_at, status FROM notifications WHERE id = ?', (notification_id,))
row = cursor.fetchone()
conn.close()
return row
except Exception as e:
print(f"Error getting notification: {e}")
return None
def get_setting(self, key: str) -> Optional[str]:
"""Get a setting value."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT value FROM settings WHERE key = ?', (key,))
row = cursor.fetchone()
conn.close()
return row[0] if row else None
def set_setting(self, key: str, value: str) -> bool:
"""Set a setting value."""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO settings (key, value)
VALUES (?, ?)
''', (key, value))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error setting setting: {e}")
return False