-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.py
More file actions
893 lines (737 loc) · 29.8 KB
/
storage.py
File metadata and controls
893 lines (737 loc) · 29.8 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
"""Storage layer - S3 uploads and SQLite metadata."""
from __future__ import annotations
import os
import json
import sqlite3
import boto3
from datetime import datetime
from pathlib import Path
from typing import Optional, List, Dict, Any
from contextlib import contextmanager
import config
# === SQLite Metadata ===
def get_db_path() -> Path:
"""Get path to metadata DB."""
db_dir = Path(config.DATA_DIR)
db_dir.mkdir(parents=True, exist_ok=True)
return db_dir / "images.db"
def init_db() -> None:
"""Initialize the metadata database."""
db_path = get_db_path()
conn = sqlite3.connect(db_path)
# Image refs table - unified reference to images in S3
conn.execute("""
CREATE TABLE IF NOT EXISTS image_refs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
s3_path TEXT NOT NULL UNIQUE,
image_hash TEXT,
width INTEGER,
height INTEGER,
content_type TEXT DEFAULT 'image/jpeg',
created_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS images (
id TEXT PRIMARY KEY,
source TEXT NOT NULL,
source_id TEXT,
category TEXT NOT NULL,
query TEXT,
-- Original image info
original_url TEXT,
photographer TEXT,
photographer_url TEXT,
alt_text TEXT,
caption TEXT, -- Original caption/description from source
original_width INTEGER,
original_height INTEGER,
-- Pipeline status
status TEXT DEFAULT 'raw', -- raw, processed, validated, rejected, generated
downloaded_at TEXT,
processed_at TEXT,
validated_at TEXT,
-- Validation results
valid BOOLEAN,
validation_result TEXT, -- JSON blob
rejection_reason TEXT,
-- Extra metadata
extra TEXT, -- JSON blob for source-specific data
-- Reference to image_refs table (links to S3 path and hash)
image_ref_id INTEGER REFERENCES image_refs(id),
-- Group for train/test split (0, 1, 2, etc.)
"group" INTEGER DEFAULT 0
)
""")
# Table for multiple generated versions per base image
conn.execute("""
CREATE TABLE IF NOT EXISTS generated_images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
base_image_id TEXT NOT NULL,
generator TEXT NOT NULL,
model TEXT NOT NULL,
prompt TEXT,
created_at TEXT NOT NULL,
image_ref_id INTEGER REFERENCES image_refs(id),
FOREIGN KEY (base_image_id) REFERENCES images(id),
UNIQUE(base_image_id, generator, model)
)
""")
# Table for AI detection results
conn.execute("""
CREATE TABLE IF NOT EXISTS detection_results (
id INTEGER PRIMARY KEY AUTOINCREMENT,
image_ref_id INTEGER REFERENCES image_refs(id) NOT NULL,
detector TEXT NOT NULL,
model TEXT,
ai_score REAL NOT NULL,
raw_response TEXT, -- JSON blob
detected_at TEXT NOT NULL,
UNIQUE(image_ref_id, detector)
)
""")
# Table for image prompts (generated via Gemini image understanding)
conn.execute("""
CREATE TABLE IF NOT EXISTS image_prompts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
image_id TEXT NOT NULL,
prompt TEXT NOT NULL,
model TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (image_id) REFERENCES images(id),
UNIQUE(image_id, model)
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_category ON images(category)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_source ON images(source)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_status ON images(status)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_gen_base ON generated_images(base_image_id)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_gen_generator ON generated_images(generator, model)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_det_detector ON detection_results(detector)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_det_ref ON detection_results(image_ref_id)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_prompt_image ON image_prompts(image_id)")
conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_image_refs_hash ON image_refs(image_hash) WHERE image_hash IS NOT NULL AND image_hash != 'MISSING'")
conn.execute("CREATE INDEX IF NOT EXISTS idx_image_refs_s3 ON image_refs(s3_path)")
# Migrations for existing databases
migrations = [
("images", "caption", "ALTER TABLE images ADD COLUMN caption TEXT"),
("images", "group", "ALTER TABLE images ADD COLUMN \"group\" INTEGER DEFAULT 0"),
("images", "image_ref_id", "ALTER TABLE images ADD COLUMN image_ref_id INTEGER REFERENCES image_refs(id)"),
("generated_images", "image_ref_id", "ALTER TABLE generated_images ADD COLUMN image_ref_id INTEGER REFERENCES image_refs(id)"),
("detection_results", "image_ref_id", "ALTER TABLE detection_results ADD COLUMN image_ref_id INTEGER REFERENCES image_refs(id)"),
("detection_results", "metadata", "ALTER TABLE detection_results ADD COLUMN metadata TEXT"),
]
for table, column, sql in migrations:
try:
conn.execute(sql)
except sqlite3.OperationalError:
pass # Column already exists
conn.commit()
conn.close()
@contextmanager
def get_db():
"""Context manager for database connection."""
init_db()
conn = sqlite3.connect(get_db_path())
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
finally:
conn.close()
def insert_image(image_data: Dict[str, Any]) -> None:
"""Insert or update an image record.
If s3_processed_path is provided, creates an image_ref and links it.
"""
s3_path = image_data.get("s3_processed_path")
image_hash = image_data.get("image_hash")
width = image_data.get("width")
height = image_data.get("height")
# Create image_ref if we have an S3 path
image_ref_id = None
if s3_path:
image_ref_id = insert_image_ref(
s3_path=s3_path,
image_hash=image_hash,
width=width,
height=height,
content_type="image/jpeg",
)
with get_db() as conn:
conn.execute("""
INSERT OR REPLACE INTO images (
id, source, source_id, category, query,
original_url, photographer, photographer_url, alt_text, caption,
original_width, original_height,
status, downloaded_at, extra, image_ref_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
image_data["id"],
image_data["source"],
image_data.get("source_id"),
image_data["category"],
image_data.get("query"),
image_data.get("original_url"),
image_data.get("photographer"),
image_data.get("photographer_url"),
image_data.get("alt"),
image_data.get("caption"),
width,
height,
image_data.get("status", "raw"),
image_data.get("downloaded_at", datetime.now().isoformat()),
json.dumps(image_data.get("extra", {})),
image_ref_id,
))
def update_image_status(image_id: str, status: str, **kwargs) -> None:
"""Update image status and optional fields."""
with get_db() as conn:
updates = ["status = ?"]
values = [status]
for key, value in kwargs.items():
if key == "validation_result":
value = json.dumps(value)
updates.append(f"{key} = ?")
values.append(value)
values.append(image_id)
conn.execute(
f"UPDATE images SET {', '.join(updates)} WHERE id = ?",
values
)
def get_images(
source: str = None,
category: str = None,
status: str = None,
with_s3_path: bool = False,
) -> List[Dict]:
"""Query images with optional filters.
Args:
source: Filter by source (e.g., 'amazon_reviews', 'pixabay')
category: Filter by category
status: Filter by status
with_s3_path: If True, join with image_refs to include s3_path as s3_processed_path
"""
with get_db() as conn:
if with_s3_path:
query = """
SELECT i.*, r.s3_path as s3_processed_path
FROM images i
LEFT JOIN image_refs r ON i.image_ref_id = r.id
WHERE 1=1
"""
else:
query = "SELECT * FROM images WHERE 1=1"
params = []
if source:
query += " AND i.source = ?" if with_s3_path else " AND source = ?"
params.append(source)
if category:
query += " AND i.category = ?" if with_s3_path else " AND category = ?"
params.append(category)
if status:
query += " AND i.status = ?" if with_s3_path else " AND status = ?"
params.append(status)
query += " ORDER BY i.downloaded_at DESC" if with_s3_path else " ORDER BY downloaded_at DESC"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def get_image(image_id: str) -> Optional[Dict]:
"""Get a single image by ID, including s3_path from image_refs."""
with get_db() as conn:
row = conn.execute(
"""SELECT i.*, r.s3_path as s3_processed_path, r.image_hash, r.width, r.height
FROM images i
LEFT JOIN image_refs r ON i.image_ref_id = r.id
WHERE i.id = ?""",
(image_id,)
).fetchone()
return dict(row) if row else None
def get_image_by_hash(image_hash: str) -> Optional[Dict]:
"""Get an image by its hash (for deduplication).
Looks up the hash in image_refs and returns the linked image.
"""
with get_db() as conn:
row = conn.execute(
"""SELECT i.*, r.s3_path as s3_processed_path, r.image_hash
FROM images i
JOIN image_refs r ON i.image_ref_id = r.id
WHERE r.image_hash = ?""",
(image_hash,)
).fetchone()
return dict(row) if row else None
def export_to_json(output_path: str = None) -> str:
"""Export all images to JSON for merging."""
images = get_images()
output_path = output_path or "images_export.json"
with open(output_path, "w") as f:
json.dump(images, f, indent=2)
return output_path
def import_from_json(input_path: str) -> int:
"""Import images from JSON export."""
with open(input_path) as f:
images = json.load(f)
count = 0
for img in images:
insert_image(img)
count += 1
return count
def get_stats() -> Dict[str, int]:
"""Get counts by status."""
with get_db() as conn:
rows = conn.execute("""
SELECT status, COUNT(*) as count
FROM images
GROUP BY status
""").fetchall()
return {row["status"]: row["count"] for row in rows}
# === Image Refs ===
def normalize_s3_path(s3_path: str) -> str:
"""Normalize S3 path to consistent format: s3://bucket/key"""
if s3_path.startswith("s3://"):
return s3_path
key = s3_path.lstrip("/")
if key.startswith("data/"):
key = key[5:]
return f"s3://{config.S3_BUCKET}/{key}"
def insert_image_ref(
s3_path: str,
image_hash: str = None,
width: int = None,
height: int = None,
content_type: str = "image/jpeg",
) -> int:
"""Insert an image reference. Returns the id."""
s3_path = normalize_s3_path(s3_path)
with get_db() as conn:
try:
cursor = conn.execute(
"""INSERT INTO image_refs (s3_path, image_hash, width, height, content_type, created_at)
VALUES (?, ?, ?, ?, ?, ?)""",
(s3_path, image_hash, width, height, content_type, datetime.now().isoformat())
)
return cursor.lastrowid
except sqlite3.IntegrityError:
# Already exists, return existing id
row = conn.execute("SELECT id FROM image_refs WHERE s3_path = ?", (s3_path,)).fetchone()
return row["id"] if row else None
def get_image_ref(ref_id: int) -> Optional[Dict]:
"""Get an image reference by id."""
with get_db() as conn:
row = conn.execute("SELECT * FROM image_refs WHERE id = ?", (ref_id,)).fetchone()
return dict(row) if row else None
def get_image_ref_by_s3_path(s3_path: str) -> Optional[Dict]:
"""Get an image reference by S3 path."""
s3_path = normalize_s3_path(s3_path)
with get_db() as conn:
row = conn.execute("SELECT * FROM image_refs WHERE s3_path = ?", (s3_path,)).fetchone()
return dict(row) if row else None
def update_image_ref(ref_id: int, **kwargs) -> None:
"""Update fields on an image reference."""
if not kwargs:
return
with get_db() as conn:
updates = []
values = []
for key, value in kwargs.items():
updates.append(f"{key} = ?")
values.append(value)
values.append(ref_id)
conn.execute(f"UPDATE image_refs SET {', '.join(updates)} WHERE id = ?", values)
# === Group Assignment ===
def set_group(image_id: str, group: int) -> None:
"""Set the group for a base image (0, 1, 2, etc.)."""
with get_db() as conn:
conn.execute('UPDATE images SET "group" = ? WHERE id = ?', (group, image_id))
def get_images_by_group(group: int, category: str = None) -> List[Dict]:
"""Get images in a specific group."""
with get_db() as conn:
query = 'SELECT * FROM images WHERE "group" = ?'
params = [group]
if category:
query += " AND category = ?"
params.append(category)
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
# === S3 Uploads ===
_s3_client = None
def get_s3_client():
"""Get or create S3 client using default AWS credential chain."""
global _s3_client
if _s3_client is None:
# Use default credential chain (env vars, ~/.aws/credentials, IAM role, etc.)
_s3_client = boto3.client("s3", region_name=config.S3_REGION)
return _s3_client
def upload_to_s3(local_path: str, s3_key: str) -> str:
"""Upload file to S3, return full S3 path."""
client = get_s3_client()
bucket = config.S3_BUCKET
client.upload_file(local_path, bucket, s3_key)
return f"s3://{bucket}/{s3_key}"
def download_from_s3(s3_key: str, local_path: str) -> None:
"""Download file from S3."""
client = get_s3_client()
bucket = config.S3_BUCKET
Path(local_path).parent.mkdir(parents=True, exist_ok=True)
client.download_file(bucket, s3_key, local_path)
def s3_key_for_processed(category: str, source: str, image_id: str, ext: str = ".jpg") -> str:
"""Generate S3 key for processed image."""
return f"processed/{category}/{source}/{image_id}{ext}"
def s3_key_for_generated(category: str, method: str, base_id: str, variant: str, ext: str = ".jpg") -> str:
"""Generate S3 key for generated image."""
return f"generated/{category}/{method}/{base_id}_{variant}{ext}"
def get_image_by_id(image_id: str) -> Optional[Dict]:
"""Get a single image by ID."""
return get_image(image_id)
def get_validated_images(category: str = None, s3_only: bool = True) -> List[Dict]:
"""Get all validated images (valid=1), optionally filtered by category.
Args:
category: Filter by category
s3_only: Only return images with image_ref_id set (default True)
Returns images joined with their image_ref for s3_path access.
"""
with get_db() as conn:
query = """
SELECT i.*, r.s3_path as s3_processed_path, r.image_hash
FROM images i
LEFT JOIN image_refs r ON i.image_ref_id = r.id
WHERE i.valid = 1
"""
params = []
if category:
query += " AND i.category = ?"
params.append(category)
if s3_only:
query += " AND i.image_ref_id IS NOT NULL"
query += " ORDER BY i.downloaded_at"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def update_image(image_id: str, **kwargs) -> None:
"""Update specific fields on an image record."""
if not kwargs:
return
with get_db() as conn:
updates = []
values = []
for key, value in kwargs.items():
updates.append(f"{key} = ?")
values.append(value)
values.append(image_id)
conn.execute(
f"UPDATE images SET {', '.join(updates)} WHERE id = ?",
values
)
def insert_generated_image(
base_image_id: str,
generator: str,
model: str,
s3_path: str,
prompt: str = None,
image_hash: str = None,
) -> bool:
"""Insert a generated image record. Returns True if inserted, False if already exists.
Also creates an image_ref entry for the generated image.
"""
s3_path_normalized = normalize_s3_path(s3_path)
now = datetime.now().isoformat()
with get_db() as conn:
try:
# Create image_ref entry first
cursor = conn.execute(
"""INSERT INTO image_refs (s3_path, image_hash, content_type, created_at)
VALUES (?, ?, 'image/png', ?)""",
(s3_path_normalized, image_hash, now)
)
ref_id = cursor.lastrowid
except sqlite3.IntegrityError:
# Image ref already exists, get its id
row = conn.execute("SELECT id FROM image_refs WHERE s3_path = ?", (s3_path_normalized,)).fetchone()
ref_id = row["id"] if row else None
try:
conn.execute(
"""INSERT INTO generated_images (base_image_id, generator, model, prompt, created_at, image_ref_id)
VALUES (?, ?, ?, ?, ?, ?)""",
(base_image_id, generator, model, prompt, now, ref_id)
)
return True
except sqlite3.IntegrityError:
# Already exists (UNIQUE constraint)
return False
def get_generated_images(base_image_id: str = None, generator: str = None, model: str = None) -> List[Dict]:
"""Get generated images with optional filters.
Returns generated images joined with their image_ref for s3_path access.
"""
with get_db() as conn:
query = """
SELECT g.*, r.s3_path
FROM generated_images g
LEFT JOIN image_refs r ON g.image_ref_id = r.id
WHERE 1=1
"""
params = []
if base_image_id:
query += " AND g.base_image_id = ?"
params.append(base_image_id)
if generator:
query += " AND g.generator = ?"
params.append(generator)
if model:
query += " AND g.model = ?"
params.append(model)
query += " ORDER BY g.created_at DESC"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def has_generated_version(base_image_id: str, generator: str, model: str) -> bool:
"""Check if a base image already has a generated version for this generator/model."""
with get_db() as conn:
row = conn.execute(
"SELECT 1 FROM generated_images WHERE base_image_id = ? AND generator = ? AND model = ?",
(base_image_id, generator, model)
).fetchone()
return row is not None
def get_images_without_generation(generator: str, model: str, category = None, s3_only: bool = True, group: int = None) -> List[Dict]:
"""Get validated images that don't have a generated version for this generator/model.
Args:
category: Single category string or list of categories
Returns images joined with their image_ref for s3_path access.
"""
with get_db() as conn:
query = """
SELECT i.*, r.s3_path as s3_processed_path, r.image_hash
FROM images i
LEFT JOIN image_refs r ON i.image_ref_id = r.id
LEFT JOIN generated_images g ON i.id = g.base_image_id AND g.generator = ? AND g.model = ?
WHERE i.valid = 1 AND g.id IS NULL
"""
params = [generator, model]
if category:
if isinstance(category, list):
placeholders = ",".join("?" * len(category))
query += f" AND i.category IN ({placeholders})"
params.extend(category)
else:
query += " AND i.category = ?"
params.append(category)
if s3_only:
query += " AND i.image_ref_id IS NOT NULL"
if group is not None:
query += ' AND i."group" = ?'
params.append(group)
query += " ORDER BY i.downloaded_at"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def insert_detection_result(
image_ref_id: int,
detector: str,
ai_score: float,
raw_response: dict = None,
model: str = None,
metadata: dict = None,
) -> bool:
"""Insert a detection result. Returns True if inserted, False if already exists.
Args:
image_ref_id: The image reference ID (required)
detector: Name of the detector (e.g., 'hive', 'sightengine')
ai_score: AI probability score (0-1)
raw_response: Raw API response dict
model: Optional model name used by the detector
metadata: Optional metadata dict (e.g., rescale_factor)
"""
if image_ref_id is None:
raise ValueError("image_ref_id is required")
with get_db() as conn:
try:
conn.execute(
"""INSERT INTO detection_results (image_ref_id, detector, model, ai_score, raw_response, metadata, detected_at)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(image_ref_id, detector, model, ai_score,
json.dumps(raw_response) if raw_response else None,
json.dumps(metadata) if metadata else None,
datetime.now().isoformat())
)
return True
except sqlite3.IntegrityError:
# Already exists (UNIQUE constraint on image_ref_id, detector)
return False
def get_detection_results(
image_ref_id: int = None,
detector: str = None,
) -> List[Dict]:
"""Get detection results with optional filters."""
with get_db() as conn:
query = "SELECT * FROM detection_results WHERE 1=1"
params = []
if image_ref_id:
query += " AND image_ref_id = ?"
params.append(image_ref_id)
if detector:
query += " AND detector = ?"
params.append(detector)
query += " ORDER BY detected_at DESC"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def get_detection_results_by_ref(image_ref_id: int, detector: str = None) -> List[Dict]:
"""Get detection results for an image reference (preferred method)."""
with get_db() as conn:
query = "SELECT * FROM detection_results WHERE image_ref_id = ?"
params = [image_ref_id]
if detector:
query += " AND detector = ?"
params.append(detector)
query += " ORDER BY detected_at DESC"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def has_detection_result(image_ref_id: int, detector: str) -> bool:
"""Check if an image_ref already has a detection result for this detector."""
with get_db() as conn:
row = conn.execute(
"SELECT 1 FROM detection_results WHERE image_ref_id = ? AND detector = ?",
(image_ref_id, detector)
).fetchone()
return row is not None
# Alias for backward compatibility
has_detection_result_by_ref = has_detection_result
def get_images_without_detection(
detector: str,
image_type: str = "generated",
category: str = None,
model: str = None,
random_order: bool = False,
group: int = None,
) -> List[Dict]:
"""Get images that don't have a detection result for this detector.
For image_type='generated', returns generated_images records with s3_path from image_refs.
For image_type='base', returns validated base images with s3_processed_path from image_refs.
Uses image_ref_id for efficient joining.
"""
with get_db() as conn:
if image_type == "generated":
# Use image_ref_id for clean joining, include s3_path from image_refs
query = """
SELECT g.*, i.category, r.s3_path
FROM generated_images g
JOIN images i ON g.base_image_id = i.id
JOIN image_refs r ON g.image_ref_id = r.id
LEFT JOIN detection_results d ON
g.image_ref_id = d.image_ref_id AND
d.detector = ?
WHERE d.id IS NULL AND g.image_ref_id IS NOT NULL
"""
params = [detector]
else:
# For base images, include s3_processed_path from image_refs
query = """
SELECT i.*, r.s3_path as s3_processed_path, r.image_hash
FROM images i
JOIN image_refs r ON i.image_ref_id = r.id
LEFT JOIN detection_results d ON i.image_ref_id = d.image_ref_id AND d.detector = ?
WHERE i.valid = 1 AND d.id IS NULL AND i.image_ref_id IS NOT NULL
"""
params = [detector]
if category:
query += " AND i.category = ?"
params.append(category)
if model and image_type == "generated":
query += " AND g.model = ?"
params.append(model)
if group is not None:
query += ' AND i."group" = ?'
params.append(group)
if random_order:
query += " ORDER BY RANDOM()"
else:
query += " ORDER BY g.created_at" if image_type == "generated" else " ORDER BY i.downloaded_at"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def insert_image_prompt(
image_id: str,
prompt: str,
model: str = "gemini-3-pro-preview",
) -> bool:
"""Insert an image prompt. Returns True if inserted, False if already exists."""
with get_db() as conn:
try:
conn.execute(
"""INSERT INTO image_prompts (image_id, prompt, model, created_at)
VALUES (?, ?, ?, ?)""",
(image_id, prompt, model, datetime.now().isoformat())
)
return True
except sqlite3.IntegrityError:
return False
def get_image_prompt(image_id: str, model: str = None) -> Optional[Dict]:
"""Get prompt for an image, optionally filtered by model."""
with get_db() as conn:
if model:
row = conn.execute(
"SELECT * FROM image_prompts WHERE image_id = ? AND model = ?",
(image_id, model)
).fetchone()
else:
row = conn.execute(
"SELECT * FROM image_prompts WHERE image_id = ? ORDER BY created_at DESC",
(image_id,)
).fetchone()
return dict(row) if row else None
def get_images_without_prompt(model: str = "gemini-3-pro-preview", category: str = None, group: int = None) -> List[Dict]:
"""Get validated images that don't have a prompt generated for this model.
Returns images joined with their image_ref for s3_path access.
"""
with get_db() as conn:
query = """
SELECT i.*, r.s3_path as s3_processed_path, r.image_hash
FROM images i
LEFT JOIN image_refs r ON i.image_ref_id = r.id
LEFT JOIN image_prompts p ON i.id = p.image_id AND p.model = ?
WHERE i.valid = 1 AND p.id IS NULL AND i.image_ref_id IS NOT NULL
"""
params = [model]
if category:
query += " AND i.category = ?"
params.append(category)
if group is not None:
query += " AND i.\"group\" = ?"
params.append(group)
query += " ORDER BY i.downloaded_at"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
def get_images_with_prompt(model: str = "gemini-3-pro-preview", category: str = None, group: int = None) -> List[Dict]:
"""Get validated images that have a prompt generated for this model.
Returns images joined with their image_ref for s3_path access.
"""
with get_db() as conn:
query = """
SELECT i.*, r.s3_path as s3_processed_path, r.image_hash, p.prompt
FROM images i
LEFT JOIN image_refs r ON i.image_ref_id = r.id
JOIN image_prompts p ON i.id = p.image_id AND p.model = ?
WHERE i.valid = 1 AND i.image_ref_id IS NOT NULL
"""
params = [model]
if category:
query += " AND i.category = ?"
params.append(category)
if group is not None:
query += ' AND i."group" = ?'
params.append(group)
query += " ORDER BY i.downloaded_at"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
if __name__ == "__main__":
# Quick test
import sys
if len(sys.argv) < 2:
print("Usage:")
print(" python storage.py stats")
print(" python storage.py export")
print(" python storage.py list [category] [status]")
sys.exit(1)
cmd = sys.argv[1]
if cmd == "stats":
print(get_stats())
elif cmd == "export":
path = export_to_json()
print(f"Exported to {path}")
elif cmd == "list":
category = sys.argv[2] if len(sys.argv) > 2 else None
status = sys.argv[3] if len(sys.argv) > 3 else None
for img in get_images(category, status)[:20]:
print(f"{img['id']}: {img['status']}")