-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_database.py
More file actions
2376 lines (2085 loc) · 111 KB
/
image_database.py
File metadata and controls
2376 lines (2085 loc) · 111 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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Searchable Image Database using SigLIP 2 and SQLite-vec
This script provides two modes:
1. Scan mode: Process images from a directory and store embeddings
2. Search mode: Search for similar images using text or image queries
NOTE: This code was generated with AI assistance.
"""
import argparse
import os
import sqlite3
import sys
import time
from pathlib import Path
from typing import List, Tuple, Optional, Dict
import hashlib
import json
import re
from collections import defaultdict
# ============================================================================
# Configuration Loading - Reads from config.json in project root
# ============================================================================
def load_config() -> Dict[str, str]:
"""
Load configuration from config.json.
Lookup order:
1) Next to this script (./config.json)
2) One directory up (../config.json) so you can keep a private config outside the publishable folder.
"""
script_dir = Path(__file__).parent.absolute()
candidates = [
script_dir / "config.json",
script_dir.parent / "config.json",
]
for config_path in candidates:
if not config_path.exists():
continue
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
return config
except Exception as e:
print(f"Warning: Could not load config.json at {config_path}: {e}")
print("Using default configuration.")
# Default configuration if config.json doesn't exist
return {
"database_dir": "",
"model_cache_dir": "models",
"results_dir": "results",
"thumbnails_dir": "thumbnails"
}
def resolve_path(config_path: str, base_dir: Path) -> str:
"""Resolve a path from config - use as-is if absolute, otherwise join with base directory."""
if not config_path:
return ""
path = Path(config_path)
# If path is already absolute, use it as-is
if path.is_absolute():
return str(path)
# Otherwise, join with base directory (parent of code folder for outputs)
return str(base_dir / path)
def resolve_db_dir(config_dir: str, base_dir: Path) -> str:
"""Resolve a database directory from config; if empty, fall back to parent of database_path or base_dir."""
if config_dir:
return resolve_path(config_dir, base_dir)
# Back-compat: infer from database_path if present
db_path = _CONFIG.get("database_path", "")
if db_path:
resolved = resolve_path(db_path, base_dir)
try:
return str(Path(resolved).parent)
except Exception:
pass
return str(base_dir)
def list_db_files(db_dir: str) -> List[str]:
"""List .db files in db_dir (non-recursive)."""
try:
p = Path(db_dir)
if not p.exists() or not p.is_dir():
return []
return sorted([f.name for f in p.iterdir() if f.is_file() and f.suffix.lower() == ".db"])
except Exception:
return []
def resolve_db_path(args_db: Optional[str], args_db_name: Optional[str], db_dir: str) -> str:
"""
Resolve a DB path.
- If args_db is provided, use it (absolute or relative).
- Else if args_db_name is provided, resolve under db_dir.
- Else raise ValueError.
"""
if args_db:
return str(Path(args_db))
if args_db_name:
name = args_db_name
if not name.lower().endswith(".db"):
name += ".db"
return str(Path(db_dir) / name)
raise ValueError("No database specified")
# Load configuration
_CONFIG = load_config()
# For outputs (results, etc.), use parent directory. For absolute paths in config, they'll be used as-is.
_OUTPUT_BASE = Path(__file__).parent.absolute().parent
# Configuration variables (paths relative to output base, or absolute if specified)
DEFAULT_DB_DIR = resolve_db_dir(_CONFIG.get("database_dir", ""), _OUTPUT_BASE)
DEFAULT_DB_PATH = str(Path(DEFAULT_DB_DIR) / "image_database.db")
DEFAULT_MODEL_CACHE_DIR = resolve_path(_CONFIG.get("model_cache_dir", "models"), _OUTPUT_BASE)
DEFAULT_RESULTS_DIR = resolve_path(_CONFIG.get("results_dir", "results"), _OUTPUT_BASE)
DEFAULT_THUMBNAILS_DIR = resolve_path(_CONFIG.get("thumbnails_dir", "thumbnails"), _OUTPUT_BASE)
# ============================================================================
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModel, SiglipProcessor, SiglipModel
from tqdm import tqdm
import numpy as np
import sqlite_vec
# PDF support - use PyMuPDF (fitz) which doesn't require poppler
try:
import fitz # PyMuPDF
PDF_SUPPORT = True
except ImportError:
PDF_SUPPORT = False
print("Warning: PyMuPDF not available. PDF support disabled. Install with: pip install PyMuPDF")
print("Python libraries loaded successfully.", flush=True)
# Increase PIL image size limit to handle very large images (default is ~89MP, we'll allow up to 500MP)
Image.MAX_IMAGE_PIXELS = 500_000_000 # 500 megapixels
class ImageDatabase:
"""Manages the image database with SigLIP 2 embeddings and SQLite-vec."""
def __init__(self, db_path: str = None, model_cache_dir: str = None):
print("="*60, flush=True)
print("Initializing Image Database", flush=True)
print("="*60, flush=True)
# Default paths
if db_path is None:
db_path = DEFAULT_DB_PATH
if model_cache_dir is None:
model_cache_dir = DEFAULT_MODEL_CACHE_DIR
self.db_path = db_path
self.model_cache_dir = model_cache_dir
print(f"Database path: {self.db_path}")
print(f"Model cache directory: {self.model_cache_dir}")
# Create directories if they don't exist
print("Creating directories...")
os.makedirs(os.path.dirname(os.path.abspath(self.db_path)), exist_ok=True)
if model_cache_dir:
os.makedirs(model_cache_dir, exist_ok=True)
print(f" [OK] Created model cache directory: {model_cache_dir}")
# Check device
print("\nChecking compute device...")
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.dtype = torch.float16 if self.device.type == "cuda" else torch.float32
if self.device.type == "cuda":
print(f" [OK] CUDA available: {torch.cuda.get_device_name(0)}")
print(f" [OK] CUDA memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
else:
print(f" [OK] Using CPU (CUDA not available)")
print(f" [OK] Data type: {self.dtype}")
# Initialize model
print(f"\nLoading SigLIP 2 model...")
print(f" Model: google/siglip2-so400m-patch14-224")
print(f" Device: {self.device}")
print(f" Precision: {self.dtype}")
# Try to load from local directory first, then fall back to HuggingFace
local_model_path = os.path.join(model_cache_dir, "google--siglip2-so400m-patch14-224") if model_cache_dir else None
model_name = "google/siglip2-so400m-patch14-224"
if local_model_path and os.path.exists(local_model_path):
print(f" Loading from local cache: {local_model_path}")
# Try explicit Siglip classes first to avoid Auto class confusion
try:
print(" Loading processor...")
self.processor = SiglipProcessor.from_pretrained(local_model_path)
print(" [OK] Processor loaded")
print(" Loading model...")
self.model = SiglipModel.from_pretrained(local_model_path).to(self.device).to(self.dtype)
print(" [OK] Model loaded")
except Exception as e:
print(f" Error with explicit classes, trying Auto: {e}")
print(" Loading processor (Auto)...")
self.processor = AutoProcessor.from_pretrained(local_model_path)
print(" Loading model (Auto)...")
self.model = AutoModel.from_pretrained(local_model_path).to(self.device).to(self.dtype)
else:
# Use default cache if model_cache_dir is None, otherwise use custom
cache_kwargs = {}
if model_cache_dir:
cache_kwargs['cache_dir'] = model_cache_dir
print(f" Model cache directory: {model_cache_dir}")
# Try to load from HuggingFace
try:
print(" Downloading/loading processor from HuggingFace...")
self.processor = AutoProcessor.from_pretrained(model_name, **cache_kwargs)
print(" [OK] Processor loaded")
print(" Downloading/loading model from HuggingFace (this may take a while)...")
self.model = AutoModel.from_pretrained(model_name, **cache_kwargs).to(self.device).to(self.dtype)
print(" [OK] Model loaded")
except Exception as e:
print(f" [X] Error loading model: {e}")
raise
print(" Setting model to evaluation mode...")
self.model.eval()
print(" [OK] Model ready")
# Expected embedding dimension for SO400M
self.embedding_dim = 1152
print(f" Embedding dimension: {self.embedding_dim}")
# Initialize database
print("\nInitializing database...")
self._init_database()
print("="*60)
print("Initialization complete!")
print("="*60 + "\n")
def _init_database(self):
"""Initialize SQLite database with sqlite-vec extension."""
print(f" Connecting to database: {self.db_path}")
conn = sqlite3.connect(self.db_path, timeout=30.0)
print(" [OK] Database connection established")
# Enable WAL mode for better concurrent access (reads can happen during writes)
print(" Enabling WAL mode for concurrent access...")
conn.execute("PRAGMA journal_mode=WAL")
print(" [OK] WAL mode enabled")
# Enable extension loading (required for sqlite-vec)
print(" Enabling extension loading...")
conn.enable_load_extension(True)
print(" [OK] Extension loading enabled")
# Load sqlite-vec extension
print(" Loading sqlite-vec extension...")
try:
sqlite_vec.load(conn)
print(" [OK] sqlite-vec extension loaded")
except Exception as e:
print(f" [X] ERROR: Could not load sqlite-vec extension: {e}")
print(" Please ensure sqlite-vec is installed: pip install sqlite-vec")
sys.exit(1)
cursor = conn.cursor()
# Create metadata table
print(" Creating images metadata table...")
cursor.execute("""
CREATE TABLE IF NOT EXISTS images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_path TEXT UNIQUE NOT NULL,
last_modified REAL NOT NULL,
file_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
print(" [OK] Images table ready")
# Create vec0 virtual table for embeddings
# Only create if it doesn't exist (don't drop existing data!)
print(f" Creating vec0 virtual table (embedding dimension: {self.embedding_dim})...")
try:
cursor.execute(f"""
CREATE VIRTUAL TABLE IF NOT EXISTS vec0 USING vec0(
embedding float[{self.embedding_dim}]
)
""")
print(" [OK] vec0 virtual table ready")
except sqlite3.OperationalError as e:
if "no such module: vec0" in str(e).lower() or "no such module" in str(e).lower():
print(" [X] ERROR: sqlite-vec extension is not available!")
print(" Please install sqlite-vec and ensure it's accessible.")
sys.exit(1)
# If table already exists, that's fine
if "already exists" not in str(e).lower():
raise
print(" [OK] vec0 virtual table already exists")
# Create mapping table
print(" Creating image_embeddings mapping table...")
cursor.execute("""
CREATE TABLE IF NOT EXISTS image_embeddings (
rowid INTEGER PRIMARY KEY,
image_id INTEGER,
FOREIGN KEY (image_id) REFERENCES images(id)
)
""")
print(" [OK] Mapping table ready")
# Create binary_embeddings table for binary embeddings (for fast approximate search)
print(f" Creating binary_embeddings table (binary embedding dimension: {self.embedding_dim})...")
try:
cursor.execute("""
CREATE TABLE IF NOT EXISTS binary_embeddings (
rowid INTEGER PRIMARY KEY AUTOINCREMENT,
image_id INTEGER UNIQUE NOT NULL,
embedding BLOB NOT NULL,
FOREIGN KEY (image_id) REFERENCES images(id)
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_binary_embeddings_image_id
ON binary_embeddings(image_id)
""")
print(" [OK] binary_embeddings table ready")
except Exception as e:
print(f" [WARNING] Could not create binary_embeddings: {e}")
# Check existing image count
cursor.execute("SELECT COUNT(*) FROM images")
existing_count = cursor.fetchone()[0]
if existing_count > 0:
print(f" Database contains {existing_count:,} existing images")
conn.commit()
conn.close()
print(f" [OK] Database initialized successfully")
def _get_file_hash(self, file_path: str) -> str:
"""Calculate SHA256 hash of file."""
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
sha256.update(chunk)
return sha256.hexdigest()
def _needs_thumbnail(self, file_path: str) -> bool:
"""Check if file needs a thumbnail (non-browser-supported formats)."""
file_ext = Path(file_path).suffix.lower()
return file_ext in {'.pdf', '.tif', '.tiff', '.bmp'}
def _get_thumbnail_path(self, file_path: str) -> str:
"""Get thumbnail path for a file."""
file_hash = self._get_file_hash(file_path)
file_ext = Path(file_path).suffix.lower()
# Use hash to avoid path issues and ensure uniqueness
thumbnail_filename = f"{file_hash}.jpg"
thumbnail_dir = Path(DEFAULT_THUMBNAILS_DIR)
thumbnail_dir.mkdir(parents=True, exist_ok=True)
return str(thumbnail_dir / thumbnail_filename)
def _create_thumbnail(self, file_path: str, max_size: Tuple[int, int] = (400, 400)) -> Optional[str]:
"""Create thumbnail for a file. Returns thumbnail path if successful, None otherwise."""
try:
thumbnail_path = self._get_thumbnail_path(file_path)
# Skip if thumbnail already exists
if os.path.exists(thumbnail_path):
return thumbnail_path
# Load image
image = self._load_image(file_path)
if image is None:
return None
# Create thumbnail
image.thumbnail(max_size, Image.Resampling.LANCZOS)
# Save as JPEG
image.save(thumbnail_path, "JPEG", quality=85)
return thumbnail_path
except Exception as e:
self._safe_print_path("Error creating thumbnail for ", file_path, e)
return None
def _safe_print_path(self, message: str, file_path: str, error: Exception = None) -> None:
"""Safely print a message with a file path that may contain Unicode characters."""
try:
if error:
print(f"{message}{file_path}: {error}", flush=True)
else:
print(f"{message}{file_path}", flush=True)
except UnicodeEncodeError:
# Fallback: encode path as ASCII with error handling
safe_path = file_path.encode('ascii', 'replace').decode('ascii')
if error:
print(f"{message}{safe_path}: {error}", flush=True)
else:
print(f"{message}{safe_path}", flush=True)
def _load_image(self, image_path: str) -> Optional[Image.Image]:
"""Load image from file, handling PDFs and regular images."""
try:
file_ext = Path(image_path).suffix.lower()
if file_ext == '.pdf' and PDF_SUPPORT:
# Convert first page of PDF to image using PyMuPDF
try:
import fitz # PyMuPDF
doc = fitz.open(image_path)
if len(doc) == 0:
doc.close()
return None
# Get first page
page = doc[0]
# Render to image at 150 DPI (similar to pdf2image default)
mat = fitz.Matrix(150/72, 150/72) # 72 is default DPI
pix = page.get_pixmap(matrix=mat)
# Convert to PIL Image
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
doc.close()
return img
except Exception as pdf_error:
# PDF conversion failed
self._safe_print_path("Error converting PDF ", image_path, pdf_error)
return None
elif file_ext == '.pdf' and not PDF_SUPPORT:
# PDF support not available
self._safe_print_path("PDF support not available for ", image_path, None)
return None
else:
return Image.open(image_path).convert("RGB")
except Exception as e:
self._safe_print_path("Error loading ", image_path, e)
return None
def _get_image_embedding(self, image_path: str) -> Optional[np.ndarray]:
"""Extract embedding from an image file."""
try:
image = self._load_image(image_path)
if image is None:
return None
inputs = self.processor(images=image, return_tensors="pt").to(self.device)
# Convert inputs to match model dtype
inputs = {k: v.to(self.dtype) if v.dtype.is_floating_point else v for k, v in inputs.items()}
with torch.no_grad():
outputs = self.model.get_image_features(**inputs)
# Normalize for cosine similarity
embedding = torch.nn.functional.normalize(outputs, p=2, dim=1)
embedding = embedding.cpu().numpy().astype(np.float32).flatten()
return embedding
except Exception as e:
self._safe_print_path("Error processing ", image_path, e)
return None
def _get_image_embeddings_batch(self, image_paths: List[str]) -> List[Optional[np.ndarray]]:
"""Extract embeddings from multiple images in a batch (much faster)."""
images = []
valid_paths = []
# Load all images
for image_path in image_paths:
try:
img = self._load_image(image_path)
if img is not None:
images.append(img)
valid_paths.append(image_path)
except Exception as e:
self._safe_print_path("Error loading ", image_path, e)
continue
if not images:
return [None] * len(image_paths)
try:
# Process all images in one batch
inputs = self.processor(images=images, return_tensors="pt", padding=True).to(self.device)
# Convert inputs to match model dtype
inputs = {k: v.to(self.dtype) if v.dtype.is_floating_point else v for k, v in inputs.items()}
with torch.no_grad():
outputs = self.model.get_image_features(**inputs)
# Normalize for cosine similarity
embeddings = torch.nn.functional.normalize(outputs, p=2, dim=1)
embeddings = embeddings.cpu().numpy().astype(np.float32)
# Map back to original paths (handle failed loads)
result = [None] * len(image_paths)
valid_idx = 0
for i, path in enumerate(image_paths):
if path in valid_paths:
result[i] = embeddings[valid_idx].flatten()
valid_idx += 1
return result
except Exception as e:
print(f"Error processing batch: {e}")
return [None] * len(image_paths)
def _get_text_embedding(self, text: str) -> np.ndarray:
"""Extract embedding from text.
CRITICAL: SigLIP 2 requires:
1. Lowercase text (model was trained only on lowercase)
2. Padding to exactly 64 tokens (max_length=64)
3. Using get_text_features from SiglipModel to get projected vector
"""
# 1. Lowercase is MANDATORY for SigLIP 2
text = text.lower()
# 2. Add the official prompt template
prompt = f"this is a photo of {text}"
# 3. Use processor with padding="max_length" and max_length=64 (strict requirement)
inputs = self.processor(
text=[prompt],
return_tensors="pt",
padding="max_length",
max_length=64
).to(self.device)
# Convert inputs to match model dtype
inputs = {k: v.to(self.dtype) if v.dtype.is_floating_point else v for k, v in inputs.items()}
with torch.no_grad():
# Use get_text_features to get the PROJECTED vector (aligned with images)
text_features = self.model.get_text_features(**inputs)
# 4. L2 Normalize
embedding = text_features.cpu().numpy()[0]
embedding = embedding / (np.linalg.norm(embedding) + 1e-12)
embedding = embedding.astype(np.float32)
return embedding
def _apply_negative_embedding(self, embedding: np.ndarray, negative_emb: np.ndarray,
negative_weight: float, embedding1: np.ndarray,
embedding2: Optional[np.ndarray], weights: Tuple[float, float]) -> np.ndarray:
"""
Apply negative embedding subtraction and re-normalize. Returns normalized embedding.
Math: embedding = embedding - negative_weight * negative_emb, then normalize.
For multiple negatives, this would be: embedding - w1*neg1 - w2*neg2 - ..., then normalize.
"""
# Subtract negative embedding: move away from negative concept
embedding = embedding - negative_weight * negative_emb
# Re-normalize
norm = np.linalg.norm(embedding)
if norm > 0:
embedding = embedding / norm
else:
print("Warning: Embedding became zero after negative subtraction, using original")
# Restore original embedding
if embedding2 is None:
embedding = embedding1
else:
w1, w2 = weights[0] / (weights[0] + weights[1]), weights[1] / (weights[0] + weights[1])
embedding = w1 * embedding1 + w2 * embedding2
norm = np.linalg.norm(embedding)
if norm > 0:
embedding = embedding / norm
return embedding
def _apply_multiple_negative_embeddings(self, embedding: np.ndarray,
negative_embs: List[np.ndarray],
negative_weights: List[float],
embedding1: np.ndarray,
embedding2: Optional[np.ndarray],
weights: Tuple[float, float]) -> np.ndarray:
"""
Apply multiple negative embeddings with individual weights.
Math: embedding = embedding - sum(weight_i * negative_emb_i), then normalize.
This moves the embedding away from all negative concepts simultaneously.
"""
# Subtract all negative embeddings
for neg_emb, neg_weight in zip(negative_embs, negative_weights):
embedding = embedding - neg_weight * neg_emb
# Re-normalize
norm = np.linalg.norm(embedding)
if norm > 0:
embedding = embedding / norm
else:
print("Warning: Embedding became zero after negative subtraction, using original")
# Restore original embedding
if embedding2 is None:
embedding = embedding1
else:
w1, w2 = weights[0] / (weights[0] + weights[1]), weights[1] / (weights[0] + weights[1])
embedding = w1 * embedding1 + w2 * embedding2
norm = np.linalg.norm(embedding)
if norm > 0:
embedding = embedding / norm
return embedding
def _sample_folder_sequences(self, files: List[Path]) -> List[Path]:
"""
Sample likely frame sequences in a folder to avoid indexing thousands of near-identical frames.
Heuristic:
- Only consider sampling for large folders
- Only sample when the folder name or the dominant filename prefix looks like a frame/render sequence
- Avoid sampling common photo-camera prefixes (e.g. IMG_####, DSC_####)
Returns the list of files to process (after sampling).
"""
if len(files) <= 150:
return files # No sampling needed for small folders
if not files:
return files
folder_name = files[0].parent.name.lower()
folder_sequence_keywords = (
"frame", "frames", "render", "renders", "sequence", "seq", "anim", "animation", "motion", "video"
)
folder_looks_like_sequence = any(k in folder_name for k in folder_sequence_keywords)
# Extract numbers from filenames to detect sequences
numbered_files: List[Tuple[int, Path, str]] = []
for f in files:
stem = f.stem
# Try to extract trailing number (e.g., "frame_0001" -> 1, "render_042" -> 42)
match = re.search(r'^(.*?)(\d+)$', stem)
if match:
prefix = (match.group(1) or "").lower()
frame_num = int(match.group(2))
numbered_files.append((frame_num, f, prefix))
# Only sample if we found many numbered files and it looks like a frame/render sequence
if len(numbered_files) > 150:
# Identify dominant prefix among numbered files
prefix_counts: Dict[str, int] = {}
for _, _, pfx in numbered_files:
prefix_counts[pfx] = prefix_counts.get(pfx, 0) + 1
dominant_prefix, dominant_count = max(prefix_counts.items(), key=lambda kv: kv[1])
dominant_frac = dominant_count / max(1, len(numbered_files))
# Avoid sampling common camera/photo filename prefixes
pfx_stripped = dominant_prefix.strip().strip("_- ")
photo_prefixes = {
"img", "dsc", "pict", "photo", "pxl", "mvimg", "dji", "gopr", "gopro", "scan"
}
dominant_is_photoish = (
pfx_stripped in photo_prefixes
or dominant_prefix.startswith(("img_", "dsc_", "pxl_", "mvimg_", "dji_", "gopr_"))
)
prefix_sequence_keywords = ("frame", "render", "shot", "output", "seq", "sequence", "anim", "animation")
prefix_looks_like_sequence = any(k in dominant_prefix for k in prefix_sequence_keywords)
should_sample = (
dominant_frac >= 0.8
and (folder_looks_like_sequence or prefix_looks_like_sequence)
and not dominant_is_photoish
)
if not should_sample:
return files
numbered_files.sort(key=lambda x: x[0]) # Sort by frame number
# Keep only every 100th frame (1, 101, 201, 301, ...)
frames_to_keep = set()
for i in range(0, len(numbered_files), 100):
frames_to_keep.add(numbered_files[i][1])
# Return only the files to keep (numbered files that are sampled + non-numbered files)
result = []
numbered_set = {f for _, f, _ in numbered_files}
for f in files:
if f in numbered_set:
if f in frames_to_keep:
result.append(f)
else:
# Non-numbered files are always kept
result.append(f)
return result
# No sampling needed
return files
def _batch_check_processed(self, cursor, file_metadata: List[Tuple[str, float]]) -> set:
"""Batch check which images are already processed. Returns set of processed file paths."""
if not file_metadata:
return set()
# SQLite has a limit of ~999 variables, so chunk into batches of 400 (200 pairs)
processed = set()
chunk_size = 400 # 200 file_path + last_modified pairs
for i in range(0, len(file_metadata), chunk_size):
chunk = file_metadata[i:i + chunk_size]
placeholders = ','.join(['(?, ?)'] * len(chunk))
values = [item for pair in chunk for item in pair]
# Check if image exists AND has an embedding (either full or binary)
# Check for full embeddings first, then binary embeddings
cursor.execute(f"""
SELECT i.file_path
FROM images i
WHERE (i.file_path, i.last_modified) IN (VALUES {placeholders})
AND (
EXISTS (SELECT 1 FROM image_embeddings ie WHERE ie.image_id = i.id)
OR EXISTS (SELECT 1 FROM binary_embeddings be WHERE be.image_id = i.id)
)
""", values)
processed.update(row[0] for row in cursor.fetchall())
return processed
def scan_directory(self, root_dir: str, batch_size: int = 75, inference_batch_size: int = 16, profile: bool = False, limit: int = None, exclude_paths: List[str] = None, save_full_embeddings: bool = True):
"""
Scan directory and process images.
Automatically samples large sequences: if a folder has >100 numbered frames, only every 100th frame is indexed.
Args:
root_dir: Root directory to scan
batch_size: Number of images to process before committing to DB (default: 75)
inference_batch_size: Number of images to process in parallel for model inference (default: 16)
profile: If True, print timing information for each step
limit: Limit number of images to process (for testing, None = no limit)
exclude_paths: List of directory paths to exclude from scanning
save_full_embeddings: If True, save full embeddings to vec0 (default: True). Set to False for binary-only mode.
"""
print("="*60)
print("Starting Directory Scan")
print("="*60)
print(f"Root directory: {root_dir}")
print(f"Database: {self.db_path}")
print(f"Batch size (DB commits): {batch_size}")
print(f"Inference batch size: {inference_batch_size}")
if save_full_embeddings:
print(f"Embedding mode: Full embeddings (vec0) + Binary embeddings")
else:
print(f"Embedding mode: Binary embeddings only (space-efficient mode)")
if limit:
print(f"Limit: {limit} images (testing mode)")
print("="*60 + "\n")
root_path = Path(root_dir)
if not root_path.exists():
print(f"[X] Error: Directory {root_dir} does not exist")
return
# Normalize exclude paths to absolute paths for comparison
exclude_abs_paths = []
if exclude_paths:
for excl_path in exclude_paths:
excl_abs = os.path.abspath(excl_path)
exclude_abs_paths.append(excl_abs)
print(f"Excluding {len(exclude_paths)} directory path(s):")
for excl_path in exclude_paths:
print(f" - {excl_path}")
# Supported image extensions (including PDFs)
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp', '.tiff', '.tif'}
if PDF_SUPPORT:
image_extensions.add('.pdf')
print(f"Supported image formats: {', '.join(sorted(image_extensions))}")
# First pass: count total files
print("\n[Step 1/4] Counting image files...", flush=True)
print(" Using fast directory traversal (os.walk)...", flush=True)
# Use set to deduplicate (Windows is case-insensitive, so *.jpg and *.JPG find same files)
# Convert extensions to lowercase for case-insensitive matching
image_extensions_lower = {ext.lower() for ext in image_extensions}
image_files_set = set()
excluded_count = 0
file_count = 0
last_report = 0
report_interval = 50000 # Report every 50k files
# Use os.walk() which is much faster than rglob() on Windows
# Traverse directory tree once and filter by extension
root_str = str(root_path.absolute())
for root, dirs, files in os.walk(root_str):
# Check if current directory or any parent should be excluded
root_abs = os.path.abspath(root)
root_abs_norm = root_abs.lower() # Case-insensitive comparison on Windows
should_skip = False
if exclude_abs_paths:
for excl_abs in exclude_abs_paths:
excl_abs_norm = excl_abs.lower()
# Check if current directory is excluded, or is a subdirectory of excluded path
if root_abs_norm == excl_abs_norm or root_abs_norm.startswith(excl_abs_norm + os.sep):
# Skip this directory and all subdirectories
dirs[:] = [] # Clear dirs list to prevent descending
should_skip = True
excluded_count += 1
break
if should_skip:
continue
for file in files:
# Skip macOS resource fork files (._filename)
if file.startswith('._'):
continue
# Get file extension (case-insensitive)
file_ext = os.path.splitext(file)[1].lower()
if file_ext in image_extensions_lower:
# Build full path
full_path = os.path.join(root, file)
# Use absolute path for deduplication
abs_path = os.path.abspath(full_path)
image_files_set.add(abs_path)
file_count = len(image_files_set)
if file_count - last_report >= report_interval:
print(f" Found {file_count:,} unique image files so far...", flush=True)
last_report = file_count
total_found = len(image_files_set)
if excluded_count > 0:
print(f" Excluded {excluded_count:,} directories", flush=True)
print(f" Found {total_found:,} total image files", flush=True)
image_files = [Path(p) for p in image_files_set] # Convert back to list of Path objects
# Group files by parent directory - we'll process folders one at a time
files_by_dir = {}
for img_file in image_files:
parent = img_file.parent
if parent not in files_by_dir:
files_by_dir[parent] = []
files_by_dir[parent].append(img_file)
total_dirs = len(files_by_dir)
print(f" Grouped into {total_dirs:,} directories", flush=True)
if total_dirs == 0:
print("\n[X] No image files found!")
return
print("\n[Step 2/4] Connecting to database...", flush=True)
conn = sqlite3.connect(self.db_path, timeout=30.0) # Increase timeout for locked database
# Enable WAL mode for better concurrent access (allows reads during writes)
conn.execute("PRAGMA journal_mode=WAL")
# Ensure extension is loaded for this connection
conn.enable_load_extension(True)
try:
sqlite_vec.load(conn)
except:
pass # Already loaded or not needed
cursor = conn.cursor()
processed = 0
skipped = 0
errors = 0
db_batch = []
inference_batch = []
inference_metadata = []
# Profiling timers
timers = defaultdict(float)
timer_counts = defaultdict(int)
try:
# Process folders one at a time (enables folder-level resume)
print("\n[Step 3/4] Processing images...", flush=True)
# Estimate total files for progress bar (will be updated as we sample)
estimated_total = total_found
total_processed_estimate = 0
# Sort folders for consistent processing order
sorted_folders = sorted(files_by_dir.items(), key=lambda x: str(x[0]))
total_folders = len(sorted_folders)
print(f" Processing {total_folders:,} folders...", flush=True)
with tqdm(total=estimated_total, desc="Processing images", unit="img", unit_scale=True) as pbar:
folder_num = 0
sampled_folders = 0
total_files_removed = 0
for parent_dir, folder_files in sorted_folders:
try:
folder_num += 1
# Apply sequence sampling to this folder
files_to_process = self._sample_folder_sequences(folder_files)
if len(files_to_process) < len(folder_files):
# Sequence sampling was applied
removed = len(folder_files) - len(files_to_process)
total_files_removed += removed
sampled_folders += 1
# Update progress bar total to exclude sampled files
pbar.total = max(pbar.total - removed, pbar.n)
# Check which files in this folder are already processed
folder_metadata = []
for img_path in files_to_process:
file_path = str(img_path.absolute())
last_modified = os.path.getmtime(file_path)
folder_metadata.append((file_path, last_modified))
# Batch check for this folder
check_start = time.time()
processed_files = self._batch_check_processed(cursor, folder_metadata)
timers['check_db'] += time.time() - check_start
timer_counts['check_db'] += 1
# Collect files to process from this folder
folder_to_process = []
for file_path, last_modified in folder_metadata:
if file_path not in processed_files:
folder_to_process.append((file_path, last_modified))
else:
skipped += 1
pbar.update(1) # Update progress for skipped files
# Apply limit if specified (for testing)
if limit is not None:
remaining_limit = limit - total_processed_estimate
if remaining_limit <= 0:
break # Hit the limit
if len(folder_to_process) > remaining_limit:
folder_to_process = folder_to_process[:remaining_limit]
# Process files from this folder
for file_path, last_modified in folder_to_process:
inference_batch.append(file_path)
inference_metadata.append((file_path, last_modified))
total_processed_estimate += 1
# Check limit during processing
# (if limit reached, current batch will be processed below)
# Process batch when full
if len(inference_batch) >= inference_batch_size:
# Get embeddings in batch
embed_start = time.time()
embeddings = self._get_image_embeddings_batch(inference_batch)
timers['inference'] += time.time() - embed_start
timer_counts['inference'] += len(inference_batch)
# Hash files (can be parallelized but keeping simple for now)
hash_start = time.time()
for i, (file_path, last_modified) in enumerate(inference_metadata):
if embeddings[i] is not None:
file_hash = self._get_file_hash(file_path)
db_batch.append((file_path, last_modified, file_hash, embeddings[i]))
else:
errors += 1
timers['hashing'] += time.time() - hash_start
timer_counts['hashing'] += len(inference_metadata)
# Commit to database
if len(db_batch) >= batch_size:
db_start = time.time()
self._commit_with_retry(cursor, conn, db_batch, save_full_embeddings)
timers['db_write'] += time.time() - db_start
timer_counts['db_write'] += len(db_batch)
processed += len(db_batch)
db_batch = []
pbar.update(len(inference_batch))
inference_batch = []
inference_metadata = []
# Check if we hit the limit
if limit is not None and total_processed_estimate >= limit:
break
# Check limit after processing folder
if limit is not None and total_processed_estimate >= limit:
break
except Exception as e:
# Log error but continue with next folder
try:
folder_str = str(parent_dir)[-80:]
except:
folder_str = "unknown"
print(f"\n [ERROR] Error processing folder {folder_num}/{total_folders}: {folder_str}", flush=True)
print(f" Error: {e}", flush=True)
import traceback
traceback.print_exc()
errors += len(folder_files) # Count all files in folder as errors
pbar.update(len(folder_files)) # Update progress bar
continue # Continue with next folder
# Process remaining inference batch
if inference_batch: