Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
327 lines (285 loc) · 11.6 KB
/
Copy pathdatabase.py
File metadata and controls
327 lines (285 loc) · 11.6 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
"""
CursiveDecoder Database & Caching Layer.
Handles database schemas, encryption on read/write, access control, and response caching.
"""
import sqlite3
import hashlib
import json
import datetime
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
import config
def init_databases():
"""Initializes the main document database and the OCR cache database."""
# 1. Initialize Main DB
main_conn = sqlite3.connect(config.DB_PATH)
main_cursor = main_conn.cursor()
# Create documents table with encrypted text fields stored as TEXT (Fernet strings)
main_cursor.execute("""
CREATE TABLE IF NOT EXISTS documents (
id TEXT PRIMARY KEY,
collection_id TEXT NOT NULL,
image_path TEXT NOT NULL,
metadata_enc TEXT,
raw_transcript_enc TEXT,
confidence_data_enc TEXT,
corrected_transcript_enc TEXT,
summary_enc TEXT,
tags_enc TEXT,
review_needed INTEGER DEFAULT 0,
flagged_terms_enc TEXT,
created_at TEXT,
updated_at TEXT
)
""")
# Create collections_access table for PIN-based access control
main_cursor.execute("""
CREATE TABLE IF NOT EXISTS collections_access (
collection_id TEXT PRIMARY KEY,
pin_hash TEXT NOT NULL,
role TEXT DEFAULT 'member'
)
""")
main_conn.commit()
main_conn.close()
# 2. Initialize Cache DB
cache_conn = sqlite3.connect(config.CACHE_PATH)
cache_cursor = cache_conn.cursor()
# OCR Cache stores API response JSON keyed by image hash.
# Note: Credentials are NOT stored in the cache.
cache_cursor.execute("""
CREATE TABLE IF NOT EXISTS ocr_cache (
image_hash TEXT PRIMARY KEY,
response_json TEXT NOT NULL,
created_at TEXT NOT NULL
)
""")
cache_conn.commit()
cache_conn.close()
print("[INFO] Database tables initialized successfully.")
# --- Access Control Helpers ---
def hash_pin(pin: str) -> str:
"""Hashes a PIN using SHA-256 for basic authentication."""
return hashlib.sha256(pin.encode('utf-8')).hexdigest()
def register_collection(collection_id: str, pin: str, role: str = 'member') -> bool:
"""Registers a collection and protects it with a PIN."""
conn = sqlite3.connect(config.DB_PATH)
cursor = conn.cursor()
pin_hash = hash_pin(pin)
try:
cursor.execute(
"INSERT OR REPLACE INTO collections_access (collection_id, pin_hash, role) VALUES (?, ?, ?)",
(collection_id, pin_hash, role)
)
conn.commit()
return True
except Exception as e:
print(f"[ERROR] Failed to register collection: {e}")
return False
finally:
conn.close()
def verify_collection_access(collection_id: str, pin: Optional[str]) -> bool:
"""
Checks if collection requires a PIN and verifies it.
If the collection is not registered, we allow access but warn (default behavior for demo).
"""
conn = sqlite3.connect(config.DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT pin_hash FROM collections_access WHERE collection_id = ?", (collection_id,))
row = cursor.fetchone()
conn.close()
# If the collection doesn't have access control configured, we grant access.
if not row:
return True
# If PIN is required but none provided: deny.
if not pin:
return False
stored_hash = row[0]
return hash_pin(pin) == stored_hash
# --- OCR Response Cache Helpers ---
def compute_image_hash(image_bytes: bytes) -> str:
"""Computes SHA-256 hash of image bytes for cache keys."""
return hashlib.sha256(image_bytes).hexdigest()
def get_cached_response(image_hash: str) -> Optional[Dict[str, Any]]:
"""Retrieves cached OCR response if available."""
conn = sqlite3.connect(config.CACHE_PATH)
cursor = conn.cursor()
cursor.execute("SELECT response_json FROM ocr_cache WHERE image_hash = ?", (image_hash,))
row = cursor.fetchone()
conn.close()
if row:
print(f"[INFO] Response cache HIT for image hash: {image_hash[:10]}...")
return json.loads(row[0])
return None
def save_cached_response(image_hash: str, response_dict: Dict[str, Any]):
"""Saves OCR API response to cache."""
conn = sqlite3.connect(config.CACHE_PATH)
cursor = conn.cursor()
now_str = datetime.datetime.now().isoformat()
try:
# Scrub credentials or GCP metadata from response before saving (Security requirement)
scrubbed_dict = _scrub_response_metadata(response_dict)
cursor.execute(
"INSERT OR REPLACE INTO ocr_cache (image_hash, response_json, created_at) VALUES (?, ?, ?)",
(image_hash, json.dumps(scrubbed_dict), now_str)
)
conn.commit()
print(f"[INFO] Response cached for image hash: {image_hash[:10]}...")
except Exception as e:
print(f"[ERROR] Failed to save response to cache: {e}")
finally:
conn.close()
def _scrub_response_metadata(response_dict: Dict[str, Any]) -> Dict[str, Any]:
"""Helper to remove any sensitive API keys or transaction tokens from the response."""
# Google Cloud Vision responses usually don't contain key strings, but let's scrub context headers if any.
cleaned = response_dict.copy()
if 'context' in cleaned:
cleaned.pop('context')
return cleaned
# --- Document Database CRUD Operations ---
def save_document(
doc_id: str,
collection_id: str,
image_path: str,
metadata: Dict[str, Any],
raw_transcript: str = "",
confidence_data: List[Dict[str, Any]] = None,
corrected_transcript: str = "",
summary: str = "",
tags: List[str] = None,
review_needed: bool = False,
flagged_terms: List[Dict[str, Any]] = None
) -> bool:
"""Saves or updates a document, encrypting all sensitive fields before write."""
conn = sqlite3.connect(config.DB_PATH)
cursor = conn.cursor()
# Serialize JSON structures
meta_str = json.dumps(metadata)
conf_str = json.dumps(confidence_data or [])
tags_str = json.dumps(tags or [])
flagged_str = json.dumps(flagged_terms or [])
# Encrypt sensitive fields
meta_enc = config.encrypt_value(meta_str)
raw_enc = config.encrypt_value(raw_transcript)
conf_enc = config.encrypt_value(conf_str)
corr_enc = config.encrypt_value(corrected_transcript)
sum_enc = config.encrypt_value(summary)
tags_enc = config.encrypt_value(tags_str)
flagged_enc = config.encrypt_value(flagged_str)
now_str = datetime.datetime.now().isoformat()
try:
# Check if exists
cursor.execute("SELECT created_at FROM documents WHERE id = ?", (doc_id,))
row = cursor.fetchone()
if row:
# Update
cursor.execute("""
UPDATE documents SET
collection_id = ?, image_path = ?, metadata_enc = ?, raw_transcript_enc = ?,
confidence_data_enc = ?, corrected_transcript_enc = ?, summary_enc = ?,
tags_enc = ?, review_needed = ?, flagged_terms_enc = ?, updated_at = ?
WHERE id = ?
""", (
collection_id, image_path, meta_enc, raw_enc,
conf_enc, corr_enc, sum_enc, tags_enc,
1 if review_needed else 0, flagged_enc, now_str, doc_id
))
else:
# Insert
cursor.execute("""
INSERT INTO documents (
id, collection_id, image_path, metadata_enc, raw_transcript_enc,
confidence_data_enc, corrected_transcript_enc, summary_enc,
tags_enc, review_needed, flagged_terms_enc, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
doc_id, collection_id, image_path, meta_enc, raw_enc,
conf_enc, corr_enc, sum_enc, tags_enc,
1 if review_needed else 0, flagged_enc, now_str, now_str
))
conn.commit()
return True
except Exception as e:
print(f"[ERROR] Failed to save document: {e}")
return False
finally:
conn.close()
def get_document(doc_id: str, pin: Optional[str] = None) -> Optional[Dict[str, Any]]:
"""Retrieves and decrypts a document. Verifies collection access control first."""
conn = sqlite3.connect(config.DB_PATH)
cursor = conn.cursor()
cursor.execute("""
SELECT
id, collection_id, image_path, metadata_enc, raw_transcript_enc,
confidence_data_enc, corrected_transcript_enc, summary_enc,
tags_enc, review_needed, flagged_terms_enc, created_at, updated_at
FROM documents WHERE id = ?
""", (doc_id,))
row = cursor.fetchone()
conn.close()
if not row:
return None
collection_id = row[1]
# Access Control Enforcement
if not verify_collection_access(collection_id, pin):
raise PermissionError(f"Access Denied: Collection '{collection_id}' requires a valid PIN.")
# Decrypt and build result
try:
metadata = json.loads(config.decrypt_value(row[3]))
raw_transcript = config.decrypt_value(row[4])
confidence_data = json.loads(config.decrypt_value(row[5]))
corrected_transcript = config.decrypt_value(row[6])
summary = config.decrypt_value(row[7])
tags = json.loads(config.decrypt_value(row[8]))
review_needed = bool(row[9])
flagged_terms = json.loads(config.decrypt_value(row[10]))
return {
"id": row[0],
"collection_id": collection_id,
"image_path": row[2],
"metadata": metadata,
"raw_transcript": raw_transcript,
"confidence_data": confidence_data,
"corrected_transcript": corrected_transcript,
"summary": summary,
"tags": tags,
"review_needed": review_needed,
"flagged_terms": flagged_terms,
"created_at": row[11],
"updated_at": row[12]
}
except Exception as e:
print(f"[ERROR] Error decrypting document data: {e}")
return None
def search_documents(query: str, collection_id: str, pin: Optional[str] = None) -> List[Dict[str, Any]]:
"""
Searches documents in a collection. Decrypts records and filters matching entries.
(Note: Since fields are encrypted, we decrypt in memory to match the query.
For high volume this would be slow, but for a local hackathon prototype, it ensures full security).
"""
if not verify_collection_access(collection_id, pin):
raise PermissionError(f"Access Denied: Collection '{collection_id}' requires a valid PIN.")
conn = sqlite3.connect(config.DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT id FROM documents WHERE collection_id = ?", (collection_id,))
rows = cursor.fetchall()
conn.close()
results = []
query_lower = query.lower()
for row in rows:
doc = get_document(row[0], pin)
if doc:
# Check for matches in text fields
in_raw = query_lower in doc["raw_transcript"].lower()
in_corr = query_lower in doc["corrected_transcript"].lower()
in_sum = query_lower in doc["summary"].lower()
in_tags = any(query_lower in t.lower() for t in doc["tags"])
# Check metadata
in_meta = False
for k, v in doc["metadata"].items():
if isinstance(v, str) and query_lower in v.lower():
in_meta = True
break
if in_raw or in_corr or in_sum or in_tags or in_meta:
results.append(doc)
return results