-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathhuman_filter_unique.py
More file actions
1436 lines (1125 loc) · 53.5 KB
/
human_filter_unique.py
File metadata and controls
1436 lines (1125 loc) · 53.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
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
import argparse
import os
import cv2
import numpy as np
from pathlib import Path
from tqdm import tqdm
import json
import pickle
import gc
def parse_args():
desc = """Detect humans in images and find the most unique images from a dataset.
This tool uses a two-pass detection system:
1. YOLO11 for fast initial human detection
2. Moondream2 VLM as fallback for edge cases (artistic/stylized humans)
Use --keep to specify which images to keep:
- "humans" (default): Keep images WITH humans, discard images without
- "no_humans": Keep images WITHOUT humans, discard images with humans
Additional filters:
- --exclude_text: Remove images containing text (uses EasyOCR)
After filtering, it finds the most unique images using embeddings:
- CLIP: Semantic similarity (what's in the image)
- DINOv2: Semantic features from self-supervised learning
- LPIPS: Perceptual similarity (low-level visual differences)
- Hybrid: CLIP + LPIPS combined (recommended for video frames)
Selection uses Farthest Point Sampling for diversity.
"""
parser = argparse.ArgumentParser(description=desc, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-i', '--input_folder', type=str,
default='./input/',
help='Directory path to the inputs folder. (default: %(default)s)')
parser.add_argument('-o', '--output_folder', type=str,
default='./output/',
help='Directory path to the outputs folder. (default: %(default)s)')
parser.add_argument('--verbose', action='store_true',
help='Print progress to console.')
parser.add_argument('--file_extension', type=str,
default='png',
help='Output file extension ["png","jpg"] (default: %(default)s)')
# Mode selection
parser.add_argument('--mode', type=str,
default='full',
choices=['full', 'human_filter', 'unique_only'],
help='Processing mode: "full" (filter + unique), "human_filter" (filter only), "unique_only" (skip filtering). (default: %(default)s)')
# Human detection options
parser.add_argument('--human_detector', type=str,
default='hybrid',
choices=['yolo', 'moondream', 'hybrid'],
help='Human detection method: "yolo" (fast), "moondream" (VLM), "hybrid" (YOLO + Moondream fallback). (default: %(default)s)')
parser.add_argument('--yolo_model', type=str,
default='yolo11n.pt',
help='YOLO model to use. Options: yolo11n.pt, yolo11s.pt, yolo11m.pt, yolo11l.pt, yolo11x.pt (default: %(default)s)')
parser.add_argument('--yolo_confidence', type=float,
default=0.25,
help='YOLO confidence threshold for person detection. (default: %(default)s)')
parser.add_argument('--yolo_batch_size', type=int,
default=8,
help='Batch size for YOLO detection. Lower values use less memory. (default: %(default)s)')
parser.add_argument('--moondream_model', type=str,
default='moondream-2b-int8',
help='Moondream model variant. Options: moondream-2b-int8, moondream-2b-fp16 (default: %(default)s)')
# Hybrid detector confidence zones
parser.add_argument('--hybrid_high_threshold', type=float,
default=0.5,
help='YOLO confidence above this = definitely human, skip Moondream. (default: %(default)s)')
parser.add_argument('--hybrid_low_threshold', type=float,
default=0.1,
help='YOLO confidence below this = definitely no human, skip Moondream. (default: %(default)s)')
# Text detection options
parser.add_argument('--exclude_text', action='store_true',
help='Exclude images containing text.')
parser.add_argument('--text_detector', type=str,
default='east',
choices=['east', 'easyocr', 'paddleocr', 'moondream'],
help='Text detection method: "east" (fast, OpenCV built-in), "easyocr", "paddleocr" (fast), or "moondream" (VLM). (default: %(default)s)')
parser.add_argument('--text_confidence', type=float,
default=0.5,
help='Confidence threshold for text detection. (default: %(default)s)')
parser.add_argument('--min_text_area', type=float,
default=0.001,
help='Minimum text bounding box area as fraction of image (0.0-1.0). Helps ignore tiny text. (default: %(default)s)')
# Embedding options
parser.add_argument('--embedder', type=str,
default='clip',
choices=['clip', 'dinov2', 'lpips', 'hybrid'],
help='Embedding model for uniqueness: "clip" (semantic), "dinov2" (semantic), "lpips" (perceptual), or "hybrid" (CLIP+LPIPS combined). (default: %(default)s)')
parser.add_argument('--clip_weight', type=float,
default=0.5,
help='Weight for CLIP in hybrid mode (0.0-1.0). Higher = more semantic, lower = more perceptual. (default: %(default)s)')
parser.add_argument('--num_unique', type=int,
default=100,
help='Number of unique images to select. (default: %(default)s)')
parser.add_argument('--selection_method', type=str,
default='fps',
choices=['fps', 'kmedoids'],
help='Uniqueness selection: "fps" (Farthest Point Sampling) or "kmedoids". (default: %(default)s)')
# Performance options
parser.add_argument('--device', type=str,
default='auto',
choices=['auto', 'cuda', 'mps', 'cpu'],
help='Device for inference. "auto" detects best available. (default: %(default)s)')
parser.add_argument('--batch_size', type=int,
default=32,
help='Batch size for embedding extraction. (default: %(default)s)')
# Caching options
parser.add_argument('--cache_detections', action='store_true',
help='Cache human/text detection results to disk for reuse on subsequent runs.')
parser.add_argument('--cache_embeddings', action='store_true',
help='Cache embeddings to disk for reuse.')
parser.add_argument('--cache_dir', type=str,
default='./.detection_cache/',
help='Directory for detection and embedding cache. (default: %(default)s)')
parser.add_argument('--clear_cache', action='store_true',
help='Clear detection cache before running (start fresh).')
# Filtering direction
parser.add_argument('--keep', type=str,
default='humans',
choices=['humans', 'no_humans'],
help='Which images to keep: "humans" (keep images with humans) or "no_humans" (keep images without humans). (default: %(default)s)')
parser.add_argument('--save_discarded', action='store_true',
help='Also save discarded images to a separate folder.')
args = parser.parse_args()
return args
def get_device(device_arg):
"""Detect and return the best available device."""
import torch
if device_arg == 'auto':
if torch.cuda.is_available():
return 'cuda'
elif torch.backends.mps.is_available():
return 'mps'
else:
return 'cpu'
return device_arg
def clear_memory(verbose=False):
"""Clear memory and GPU cache between processing phases."""
import torch
if verbose:
print("Clearing memory...")
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
elif torch.backends.mps.is_available():
torch.mps.empty_cache()
class YOLODetector:
"""YOLO-based human detector using ultralytics."""
def __init__(self, model_name='yolo11n.pt', confidence=0.25, device='cpu', verbose=False):
from ultralytics import YOLO
self.model = YOLO(model_name)
self.confidence = confidence
self.device = device
self.verbose = verbose
# Person class is 0 in COCO
self.person_class = 0
def detect_human(self, image_path):
"""Returns True if a human is detected in the image."""
results = self.model(image_path, conf=self.confidence, device=self.device, verbose=False)
for result in results:
if result.boxes is not None:
classes = result.boxes.cls.cpu().numpy()
if self.person_class in classes:
if self.verbose:
print(f"\t[YOLO] Human detected in {os.path.basename(image_path)}")
return True
return False
def detect_human_with_confidence(self, image_path, min_conf=0.01):
"""Returns max confidence score for person detection (0.0 if no person found)."""
results = self.model(image_path, conf=min_conf, device=self.device, verbose=False)
max_conf = 0.0
for result in results:
if result.boxes is not None:
classes = result.boxes.cls.cpu().numpy()
confidences = result.boxes.conf.cpu().numpy()
for cls, conf in zip(classes, confidences):
if cls == self.person_class and conf > max_conf:
max_conf = float(conf)
return max_conf
def detect_batch(self, image_paths, batch_size=16, show_progress=True):
"""Batch detection for multiple images. Returns dict of {path: has_human}."""
results_dict = {}
# Process in small batches to avoid MPS memory issues
iterator = range(0, len(image_paths), batch_size)
if show_progress:
iterator = tqdm(iterator, desc="YOLO detection", total=(len(image_paths) + batch_size - 1) // batch_size)
for i in iterator:
batch_paths = image_paths[i:i+batch_size]
results = self.model(batch_paths, conf=self.confidence, device=self.device, verbose=False)
for result, path in zip(results, batch_paths):
has_human = False
if result.boxes is not None:
classes = result.boxes.cls.cpu().numpy()
if self.person_class in classes:
has_human = True
if self.verbose:
print(f"\t[YOLO] Human detected in {os.path.basename(path)}")
results_dict[path] = has_human
# Clear MPS cache between batches
if self.device == 'mps':
import torch
torch.mps.empty_cache()
return results_dict
def detect_batch_with_confidence(self, image_paths, batch_size=16, min_conf=0.01, show_progress=True):
"""Batch detection returning confidence scores. Returns dict of {path: max_confidence}."""
results_dict = {}
iterator = range(0, len(image_paths), batch_size)
if show_progress:
iterator = tqdm(iterator, desc="YOLO detection", total=(len(image_paths) + batch_size - 1) // batch_size)
for i in iterator:
batch_paths = image_paths[i:i+batch_size]
results = self.model(batch_paths, conf=min_conf, device=self.device, verbose=False)
for result, path in zip(results, batch_paths):
max_conf = 0.0
if result.boxes is not None:
classes = result.boxes.cls.cpu().numpy()
confidences = result.boxes.conf.cpu().numpy()
for cls, conf in zip(classes, confidences):
if cls == self.person_class and conf > max_conf:
max_conf = float(conf)
results_dict[path] = max_conf
# Clear MPS cache between batches
if self.device == 'mps':
import torch
torch.mps.empty_cache()
return results_dict
class MoondreamDetector:
"""Moondream2 VLM-based human detector using transformers."""
def __init__(self, model_name='moondream-2b-int8', device='cpu', verbose=False):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
self.device = device
self.verbose = verbose
self.prompt = "Is there a human, person, or human body visible in this image? Answer only 'yes' or 'no'."
if verbose:
print("Loading Moondream2 model from HuggingFace...")
# Use the HuggingFace transformers version
model_id = "vikhyatk/moondream2"
self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
self.model = AutoModelForCausalLM.from_pretrained(
model_id,
trust_remote_code=True,
torch_dtype=torch.float16 if device != 'cpu' else torch.float32,
device_map={"": device} if device != 'cpu' else None
)
if device == 'cpu':
self.model = self.model.to(device)
self.model.eval()
def detect_human(self, image_path):
"""Returns True if a human is detected in the image."""
from PIL import Image
image = Image.open(image_path).convert('RGB')
enc_image = self.model.encode_image(image)
answer = self.model.answer_question(enc_image, self.prompt, self.tokenizer).strip().lower()
has_human = answer.startswith('yes')
if self.verbose and has_human:
print(f"\t[Moondream] Human detected in {os.path.basename(image_path)}: {answer}")
return has_human
class HybridDetector:
"""Two-pass detector: YOLO first, Moondream for uncertain cases only.
Uses confidence zones:
- High confidence (>=high_threshold): Definitely human
- Uncertain (between low and high): Ask Moondream
- Low confidence (<low_threshold): Definitely no human, skip Moondream
"""
def __init__(self, yolo_model='yolo11n.pt', yolo_confidence=0.25,
moondream_model='moondream-2b-int8', device='cpu', verbose=False,
high_threshold=0.5, low_threshold=0.1):
self.yolo = YOLODetector(yolo_model, yolo_confidence, device, verbose)
self.moondream = None # Lazy load
self.moondream_model = moondream_model
self.device = device
self.verbose = verbose
self._moondream_loaded = False
self.high_threshold = high_threshold # Above this = definitely human
self.low_threshold = low_threshold # Below this = definitely no human
def _ensure_moondream(self):
if not self._moondream_loaded:
if self.verbose:
print("Loading Moondream2 model for fallback detection...")
self.moondream = MoondreamDetector(self.moondream_model, self.device, self.verbose)
self._moondream_loaded = True
def detect_human(self, image_path):
"""Two-pass detection with confidence zones."""
# Get YOLO confidence
conf = self.yolo.detect_human_with_confidence(image_path, min_conf=0.01)
if conf >= self.high_threshold:
if self.verbose:
print(f"\t[YOLO] High confidence ({conf:.2f}) human in {os.path.basename(image_path)}")
return True
elif conf < self.low_threshold:
if self.verbose:
print(f"\t[YOLO] Low confidence ({conf:.2f}), skipping Moondream for {os.path.basename(image_path)}")
return False
else:
# Uncertain zone - ask Moondream
if self.verbose:
print(f"\t[YOLO] Uncertain ({conf:.2f}), checking with Moondream...")
self._ensure_moondream()
return self.moondream.detect_human(image_path)
def detect_batch(self, image_paths, batch_size=16, show_progress=True):
"""Batch detection with confidence zones."""
results = {}
# First pass: YOLO with confidence scores
if self.verbose:
print("Pass 1: YOLO detection with confidence scores...")
yolo_conf = self.yolo.detect_batch_with_confidence(
image_paths, batch_size=batch_size, min_conf=0.01, show_progress=show_progress
)
# Categorize by confidence zones
high_conf = [] # Definitely human
uncertain = [] # Need Moondream
low_conf = [] # Definitely no human
for path, conf in yolo_conf.items():
if conf >= self.high_threshold:
high_conf.append(path)
results[path] = True
elif conf < self.low_threshold:
low_conf.append(path)
results[path] = False
else:
uncertain.append(path)
if self.verbose:
print(f"\nConfidence zones:")
print(f" High (>={self.high_threshold}): {len(high_conf)} images → human")
print(f" Uncertain ({self.low_threshold}-{self.high_threshold}): {len(uncertain)} images → ask Moondream")
print(f" Low (<{self.low_threshold}): {len(low_conf)} images → no human")
# Second pass: Moondream only on uncertain cases
if uncertain:
if self.verbose:
print(f"\nPass 2: Moondream on {len(uncertain)} uncertain images...")
self._ensure_moondream()
iterator = tqdm(uncertain, desc="Moondream check") if show_progress else uncertain
for path in iterator:
results[path] = self.moondream.detect_human(path)
return results
class EASTTextDetector:
"""OpenCV EAST text detector - fast, no additional dependencies."""
def __init__(self, confidence=0.5, min_text_area=0.001, device='cpu', verbose=False):
self.confidence = confidence
self.min_text_area = min_text_area
self.verbose = verbose
self.model_path = None
self.net = None
def _ensure_model(self):
"""Download and load EAST model if not already loaded."""
if self.net is not None:
return
import urllib.request
# EAST model path
model_dir = Path.home() / '.cache' / 'east_text_detection'
model_dir.mkdir(parents=True, exist_ok=True)
self.model_path = model_dir / 'frozen_east_text_detection.pb'
# Download if not exists
if not self.model_path.exists():
if self.verbose:
print("Downloading EAST text detection model...")
url = "https://raw.githubusercontent.com/oyyd/frozen_east_text_detection.pb/master/frozen_east_text_detection.pb"
urllib.request.urlretrieve(url, self.model_path)
if self.verbose:
print("Loading EAST model...")
self.net = cv2.dnn.readNet(str(self.model_path))
def detect_text(self, image_path):
"""Returns True if text is detected in the image."""
self._ensure_model()
img = cv2.imread(image_path)
if img is None:
return False
orig_h, orig_w = img.shape[:2]
img_area = orig_h * orig_w
# EAST requires dimensions to be multiples of 32
new_w = (orig_w // 32) * 32
new_h = (orig_h // 32) * 32
new_w = max(new_w, 32)
new_h = max(new_h, 32)
ratio_w = orig_w / float(new_w)
ratio_h = orig_h / float(new_h)
# Resize and create blob
resized = cv2.resize(img, (new_w, new_h))
blob = cv2.dnn.blobFromImage(resized, 1.0, (new_w, new_h),
(123.68, 116.78, 103.94), swapRB=True, crop=False)
# Run detection
self.net.setInput(blob)
(scores, geometry) = self.net.forward(['feature_fusion/Conv_7/Sigmoid', 'feature_fusion/concat_3'])
# Decode predictions
rows, cols = scores.shape[2:4]
rects = []
confidences = []
for y in range(rows):
scores_data = scores[0, 0, y]
x0_data = geometry[0, 0, y]
x1_data = geometry[0, 1, y]
x2_data = geometry[0, 2, y]
x3_data = geometry[0, 3, y]
angles_data = geometry[0, 4, y]
for x in range(cols):
if scores_data[x] < self.confidence:
continue
offset_x = x * 4.0
offset_y = y * 4.0
angle = angles_data[x]
cos = np.cos(angle)
sin = np.sin(angle)
h = x0_data[x] + x2_data[x]
w = x1_data[x] + x3_data[x]
# Calculate bounding box area
bbox_area = (w * ratio_w) * (h * ratio_h)
area_fraction = bbox_area / img_area
if area_fraction >= self.min_text_area:
if self.verbose:
print(f"\t[EAST] Text detected in {os.path.basename(image_path)} (conf: {scores_data[x]:.2f}, area: {area_fraction:.4f})")
return True
return False
def detect_batch(self, image_paths, show_progress=True):
"""Batch detection for multiple images."""
results = {}
iterator = tqdm(image_paths, desc="EAST text detection") if show_progress else image_paths
for path in iterator:
results[path] = self.detect_text(path)
return results
class PaddleOCRTextDetector:
"""PaddleOCR-based text detector - faster than EasyOCR."""
def __init__(self, confidence=0.5, min_text_area=0.001, device='cpu', verbose=False):
from paddleocr import PaddleOCR
self.confidence = confidence
self.min_text_area = min_text_area
self.verbose = verbose
# Initialize PaddleOCR (detection only mode for speed)
# GPU is auto-detected based on paddlepaddle-gpu installation
if verbose:
print("Loading PaddleOCR...")
self.ocr = PaddleOCR(use_angle_cls=False, lang='en')
def detect_text(self, image_path):
"""Returns True if text is detected in the image."""
img = cv2.imread(image_path)
if img is None:
return False
img_area = img.shape[0] * img.shape[1]
# Run detection
result = self.ocr.ocr(image_path, cls=False, rec=False)
if result is None or len(result) == 0 or result[0] is None:
return False
for detection in result[0]:
bbox = detection
# bbox is [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
x_coords = [p[0] for p in bbox]
y_coords = [p[1] for p in bbox]
bbox_width = max(x_coords) - min(x_coords)
bbox_height = max(y_coords) - min(y_coords)
bbox_area = bbox_width * bbox_height
area_fraction = bbox_area / img_area
if area_fraction >= self.min_text_area:
if self.verbose:
print(f"\t[PaddleOCR] Text detected in {os.path.basename(image_path)} (area: {area_fraction:.4f})")
return True
return False
def detect_batch(self, image_paths, show_progress=True):
"""Batch detection for multiple images."""
results = {}
iterator = tqdm(image_paths, desc="PaddleOCR text detection") if show_progress else image_paths
for path in iterator:
results[path] = self.detect_text(path)
return results
class EasyOCRTextDetector:
"""EasyOCR-based text detector."""
def __init__(self, confidence=0.5, min_text_area=0.001, device='cpu', verbose=False):
import easyocr
self.confidence = confidence
self.min_text_area = min_text_area
self.verbose = verbose
# Use GPU only for CUDA (MPS can be unstable with EasyOCR)
gpu = device == 'cuda'
if verbose:
print(f"Loading EasyOCR (GPU: {gpu})...")
self.reader = easyocr.Reader(['en'], gpu=gpu, verbose=False)
def detect_text(self, image_path):
"""Returns True if text is detected in the image."""
import cv2
img = cv2.imread(image_path)
if img is None:
return False
img_area = img.shape[0] * img.shape[1]
# Detect text
results = self.reader.readtext(image_path)
for (bbox, text, confidence) in results:
if confidence < self.confidence:
continue
# Calculate bounding box area
# bbox is [[x1,y1], [x2,y1], [x2,y2], [x1,y2]]
x_coords = [p[0] for p in bbox]
y_coords = [p[1] for p in bbox]
bbox_width = max(x_coords) - min(x_coords)
bbox_height = max(y_coords) - min(y_coords)
bbox_area = bbox_width * bbox_height
area_fraction = bbox_area / img_area
if area_fraction >= self.min_text_area:
if self.verbose:
print(f"\t[EasyOCR] Text detected in {os.path.basename(image_path)}: '{text}' (conf: {confidence:.2f}, area: {area_fraction:.4f})")
return True
return False
def detect_batch(self, image_paths, show_progress=True):
"""Batch detection for multiple images."""
results = {}
iterator = tqdm(image_paths, desc="Text detection") if show_progress else image_paths
for path in iterator:
results[path] = self.detect_text(path)
return results
class MoondreamTextDetector:
"""Moondream2 VLM-based text detector using transformers."""
def __init__(self, model_name='moondream-2b-int8', device='cpu', verbose=False):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
self.device = device
self.verbose = verbose
self.prompt = "Is there any text, words, letters, or numbers visible in this image? Answer only 'yes' or 'no'."
if verbose:
print("Loading Moondream2 model from HuggingFace...")
# Use the HuggingFace transformers version
model_id = "vikhyatk/moondream2"
self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
self.model = AutoModelForCausalLM.from_pretrained(
model_id,
trust_remote_code=True,
torch_dtype=torch.float16 if device != 'cpu' else torch.float32,
device_map={"": device} if device != 'cpu' else None
)
if device == 'cpu':
self.model = self.model.to(device)
self.model.eval()
def detect_text(self, image_path):
"""Returns True if text is detected in the image."""
from PIL import Image
image = Image.open(image_path).convert('RGB')
enc_image = self.model.encode_image(image)
answer = self.model.answer_question(enc_image, self.prompt, self.tokenizer).strip().lower()
has_text = answer.startswith('yes')
if self.verbose and has_text:
print(f"\t[Moondream] Text detected in {os.path.basename(image_path)}: {answer}")
return has_text
def detect_batch(self, image_paths, show_progress=True):
"""Batch detection for multiple images."""
results = {}
iterator = tqdm(image_paths, desc="Text detection (Moondream)") if show_progress else image_paths
for path in iterator:
results[path] = self.detect_text(path)
return results
class DetectionCache:
"""Cache for storing detection results (human detection, text detection)."""
def __init__(self, cache_dir, verbose=False):
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.human_cache_file = self.cache_dir / "human_detections.json"
self.text_cache_file = self.cache_dir / "text_detections.json"
self.verbose = verbose
self._human_cache = None
self._text_cache = None
def _load_cache(self, cache_file):
"""Load cache from disk."""
if cache_file.exists():
with open(cache_file, 'r') as f:
return json.load(f)
return {}
def _save_cache(self, cache_file, cache_data):
"""Save cache to disk."""
with open(cache_file, 'w') as f:
json.dump(cache_data, f, indent=2)
def _get_file_key(self, file_path):
"""Generate a cache key from file path and modification time."""
stat = os.stat(file_path)
# Use absolute path + mtime to detect file changes
return f"{os.path.abspath(file_path)}|{stat.st_mtime}"
def get_human_cache(self):
"""Get human detection cache, loading from disk if needed."""
if self._human_cache is None:
self._human_cache = self._load_cache(self.human_cache_file)
if self.verbose and self._human_cache:
print(f"Loaded {len(self._human_cache)} cached human detections")
return self._human_cache
def get_text_cache(self):
"""Get text detection cache, loading from disk if needed."""
if self._text_cache is None:
self._text_cache = self._load_cache(self.text_cache_file)
if self.verbose and self._text_cache:
print(f"Loaded {len(self._text_cache)} cached text detections")
return self._text_cache
def get_human_detection(self, file_path):
"""Get cached human detection result for a file."""
cache = self.get_human_cache()
key = self._get_file_key(file_path)
return cache.get(key)
def set_human_detection(self, file_path, has_human):
"""Cache human detection result for a file."""
cache = self.get_human_cache()
key = self._get_file_key(file_path)
cache[key] = {"path": file_path, "has_human": has_human}
def get_text_detection(self, file_path):
"""Get cached text detection result for a file."""
cache = self.get_text_cache()
key = self._get_file_key(file_path)
return cache.get(key)
def set_text_detection(self, file_path, has_text):
"""Cache text detection result for a file."""
cache = self.get_text_cache()
key = self._get_file_key(file_path)
cache[key] = {"path": file_path, "has_text": has_text}
def save_human_cache(self):
"""Save human detection cache to disk."""
if self._human_cache is not None:
self._save_cache(self.human_cache_file, self._human_cache)
if self.verbose:
print(f"Saved {len(self._human_cache)} human detections to cache")
def save_text_cache(self):
"""Save text detection cache to disk."""
if self._text_cache is not None:
self._save_cache(self.text_cache_file, self._text_cache)
if self.verbose:
print(f"Saved {len(self._text_cache)} text detections to cache")
def clear(self):
"""Clear all caches."""
if self.human_cache_file.exists():
os.remove(self.human_cache_file)
if self.text_cache_file.exists():
os.remove(self.text_cache_file)
self._human_cache = None
self._text_cache = None
def get_stats(self):
"""Get cache statistics."""
human_count = len(self.get_human_cache())
text_count = len(self.get_text_cache())
return {"human_detections": human_count, "text_detections": text_count}
class CLIPEmbedder:
"""CLIP-based image embedder."""
def __init__(self, device='cpu', verbose=False):
import torch
from transformers import CLIPProcessor, CLIPModel
self.device = device
self.verbose = verbose
if verbose:
print("Loading CLIP model...")
self.model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")
self.processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14")
self.model.to(device)
self.model.eval()
def embed(self, image_paths, batch_size=32, show_progress=True):
"""Extract embeddings for a list of images."""
import torch
from PIL import Image
embeddings = []
iterator = range(0, len(image_paths), batch_size)
if show_progress:
iterator = tqdm(iterator, desc="Extracting CLIP embeddings")
with torch.no_grad():
for i in iterator:
batch_paths = image_paths[i:i+batch_size]
images = [Image.open(p).convert('RGB') for p in batch_paths]
inputs = self.processor(images=images, return_tensors="pt", padding=True)
inputs = {k: v.to(self.device) for k, v in inputs.items()}
outputs = self.model.get_image_features(**inputs)
outputs = outputs / outputs.norm(dim=-1, keepdim=True)
embeddings.append(outputs.cpu().numpy())
return np.vstack(embeddings)
class DINOv2Embedder:
"""DINOv2-based image embedder."""
def __init__(self, device='cpu', verbose=False):
import torch
from transformers import AutoImageProcessor, AutoModel
self.device = device
self.verbose = verbose
if verbose:
print("Loading DINOv2 model...")
self.processor = AutoImageProcessor.from_pretrained("facebook/dinov2-large")
self.model = AutoModel.from_pretrained("facebook/dinov2-large")
self.model.to(device)
self.model.eval()
def embed(self, image_paths, batch_size=32, show_progress=True):
"""Extract embeddings for a list of images."""
import torch
from PIL import Image
embeddings = []
iterator = range(0, len(image_paths), batch_size)
if show_progress:
iterator = tqdm(iterator, desc="Extracting DINOv2 embeddings")
with torch.no_grad():
for i in iterator:
batch_paths = image_paths[i:i+batch_size]
images = [Image.open(p).convert('RGB') for p in batch_paths]
inputs = self.processor(images=images, return_tensors="pt", padding=True)
inputs = {k: v.to(self.device) for k, v in inputs.items()}
outputs = self.model(**inputs)
# Use CLS token
cls_embeddings = outputs.last_hidden_state[:, 0]
cls_embeddings = cls_embeddings / cls_embeddings.norm(dim=-1, keepdim=True)
embeddings.append(cls_embeddings.cpu().numpy())
return np.vstack(embeddings)
class LPIPSEmbedder:
"""LPIPS-based perceptual embedder using VGG features."""
def __init__(self, device='cpu', verbose=False):
import torch
import lpips
self.device = device
self.verbose = verbose
if verbose:
print("Loading LPIPS (VGG) model for perceptual features...")
# Use VGG network for perceptual features
self.model = lpips.LPIPS(net='vgg', verbose=False)
self.model.to(device)
self.model.eval()
def embed(self, image_paths, batch_size=16, show_progress=True):
"""Extract VGG perceptual features for a list of images."""
import torch
from PIL import Image
import torchvision.transforms as transforms
# LPIPS expects images in [-1, 1] range
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])
embeddings = []
iterator = range(0, len(image_paths), batch_size)
if show_progress:
iterator = tqdm(iterator, desc="Extracting LPIPS (VGG) features")
with torch.no_grad():
for i in iterator:
batch_paths = image_paths[i:i+batch_size]
images = []
for p in batch_paths:
img = Image.open(p).convert('RGB')
images.append(transform(img))
batch = torch.stack(images).to(self.device)
# Get intermediate VGG features from LPIPS
# We access the internal feature extraction
features = self.model.net.forward(batch)
# Concatenate features from different layers and flatten
# LPIPS uses 5 layers, we'll use all of them for rich representation
feat_list = []
for feat in features:
# Global average pool each feature map
pooled = torch.nn.functional.adaptive_avg_pool2d(feat, 1).flatten(1)
feat_list.append(pooled)
combined = torch.cat(feat_list, dim=1)
# Normalize
combined = combined / (combined.norm(dim=-1, keepdim=True) + 1e-8)
embeddings.append(combined.cpu().numpy())
# Clear MPS cache between batches
if self.device == 'mps':
torch.mps.empty_cache()
return np.vstack(embeddings)
class HybridCLIPLPIPSEmbedder:
"""Hybrid embedder combining CLIP (semantic) + LPIPS (perceptual) features."""
def __init__(self, device='cpu', verbose=False, clip_weight=0.5):
self.device = device
self.verbose = verbose
self.clip_weight = clip_weight # Weight for CLIP features (1-weight for LPIPS)
if verbose:
print(f"Loading hybrid embedder (CLIP weight: {clip_weight}, LPIPS weight: {1-clip_weight})...")
self.clip_embedder = CLIPEmbedder(device, verbose=False)
self.lpips_embedder = LPIPSEmbedder(device, verbose=False)
def embed(self, image_paths, batch_size=16, show_progress=True):
"""Extract combined CLIP + LPIPS embeddings."""
if self.verbose:
print("Extracting CLIP embeddings...")
clip_embeddings = self.clip_embedder.embed(image_paths, batch_size, show_progress)
# Clear memory between models
clear_memory(self.verbose)
if self.verbose:
print("Extracting LPIPS (VGG) embeddings...")
lpips_embeddings = self.lpips_embedder.embed(image_paths, batch_size, show_progress)
# Combine embeddings with weighting
# Both are already normalized, so we weight and renormalize
combined = np.concatenate([
clip_embeddings * self.clip_weight,
lpips_embeddings * (1 - self.clip_weight)
], axis=1)
# Normalize the combined embedding
norms = np.linalg.norm(combined, axis=1, keepdims=True)