-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
286 lines (245 loc) · 11.1 KB
/
main.py
File metadata and controls
286 lines (245 loc) · 11.1 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
#!/usr/bin/env python3
"""
DeepPerson Core API - Usage Examples
This script demonstrates the simplified, stateless DeepPerson API which provides:
- Multi-modal person detection and embedding generation
- Identity verification between images with fusion scoring
- Optimized batch processing with 2-5x speedup
- Automatic memory management for large batches
The API is stateless - no gallery management or state tracking required!
"""
from pathlib import Path
from src.api import DeepPerson
SAMPLE_IMAGE = Path("black.jpg")
def main() -> None:
"""Demonstrate the core DeepPerson API functionality."""
print("=" * 80)
print("DeepPerson Core API - Demonstration")
print("=" * 80)
print("\nThis demo shows the simplified, stateless API with 2 core methods:")
print(" 1. represent() - Generate multi-modal embeddings (single or batch)")
print(" 2. verify() - Verify if two images show the same person")
print()
# Check for sample image
if not SAMPLE_IMAGE.exists():
print(f"⚠️ Sample image missing: {SAMPLE_IMAGE}")
print(" Please place 'back.jpg' in the repository root to run the demo.")
print("\n📖 Quick Usage Guide:")
print(" from src.api import DeepPerson")
print(" dp = DeepPerson()")
print(" ")
print(" # Single image")
print(" result = dp.represent('image.jpg')")
print(" ")
print(" # Batch processing (2-5x faster)")
print(" batch = dp.represent(['img1.jpg', 'img2.jpg', 'img3.jpg'])")
print(" ")
print(" # Identity verification")
print(" verification = dp.verify('img1.jpg', 'img2.jpg')")
return
# Initialize DeepPerson
print("🔧 Initializing DeepPerson...")
dp = DeepPerson()
# Explicitly warmup (optional, but good for performance)
print(" Running warmup...")
dp.warmup()
print(f" ✓ Model: {dp.model_name}")
print(f" ✓ Device: {dp.device}")
print(f" ✓ Detector: {dp.detector_backend}")
print()
# ============================================================================
# STEP 1: Generate Multi-Modal Embeddings
# ============================================================================
print("=" * 80)
print("STEP 1: Generate Multi-Modal Embeddings")
print("=" * 80)
print("\n📸 Processing image:", SAMPLE_IMAGE)
print(" Generating body + face embeddings...")
print()
representation = dp.represent(
SAMPLE_IMAGE,
generate_face_embeddings=True,
)
subjects = representation.subjects
if not subjects:
print("❌ No persons detected in the sample image.")
return
primary_subject = subjects[0]
print(f"✓ Detected {len(subjects)} person(s)")
print(f" Body embedding: {primary_subject.embedding_vector.shape}")
face_embedding = primary_subject.face_embedding
if face_embedding is not None:
print(f" Face embedding: {face_embedding.shape} ✓")
else:
print(" Face embedding: Not available")
print("\n📊 Model Information:")
print(f" Model: {representation.model_info['name']}")
print(f" Device: {representation.model_info['device']}")
print(f" Feature Dim: {representation.model_info['feature_dim']}")
if representation.face_model_info:
print(f"\n Face Model: {representation.face_model_info['name']}")
print(
f" Face Feature Dim: {representation.face_model_info['feature_dim']}"
)
# Show some metadata
print("\n📋 Sample Metadata:")
print(f" Confidence: {primary_subject.subject_confidence:.3f}")
print(f" Normalization: {primary_subject.normalization}")
print(f" Modality: {primary_subject.modality.value}")
# ============================================================================
# STEP 2: Identity Verification
# ============================================================================
print("\n" + "=" * 80)
print("STEP 2: Identity Verification")
print("=" * 80)
# Self-verification (same image)
print(f"\n🔍 Verifying image against itself: {SAMPLE_IMAGE.name}")
verification_result = dp.verify(SAMPLE_IMAGE, SAMPLE_IMAGE)
print(
f"\n✓ Result: {'SAME PERSON' if verification_result.verified else 'DIFFERENT PERSONS'}"
)
print(f" Distance: {verification_result.distance:.4f}")
print(f" Threshold: {verification_result.threshold:.4f}")
print(f" Metric: {verification_result.distance_metric}")
print(f" Fusion used: {verification_result.used_fusion}")
print(f" Body Distance: {verification_result.body_distance:.4f}")
if verification_result.face_distance is not None:
print(f" Face Distance: {verification_result.face_distance:.4f}")
if verification_result.fusion_score is not None:
print(f" Fusion Score: {verification_result.fusion_score:.4f}")
print("\n Modalities available:")
for modality, available in verification_result.modality_available.items():
status = "✓" if available else "✗"
print(f" {modality:8s}: {status}")
if verification_result.warnings:
print("\n⚠️ Warnings:")
for warning in verification_result.warnings:
print(f" - {warning}")
# ============================================================================
# STEP 3: Batch Processing with represent()
# ============================================================================
print("\n" + "=" * 80)
print("STEP 3: Batch Processing with represent()")
print("=" * 80)
print("\n📦 Processing multiple images with optimized batch API...")
# In real usage, these would be different image files
image_paths = [SAMPLE_IMAGE] * 5
print(f" Processing {len(image_paths)} images...")
print(" Using vectorized operations for 2-5x speedup!")
batch_result = dp.represent(
image_paths,
generate_face_embeddings=False, # Disable for faster demo
batch_size=8,
)
print("\n✓ Batch processing complete!")
print(f" Total subjects detected: {len(batch_result.subjects)}")
# Show model info
print("\n📊 Model Information:")
print(f" Model: {batch_result.model_info['name']}")
print(f" Device: {batch_result.model_info['device']}")
print(f" Feature Dim: {batch_result.model_info['feature_dim']}")
# Show per-image results
print("\n📋 Subjects Detected (by source image):")
subjects_by_image = {}
for subject in batch_result.subjects:
source = subject.source_image_id or "unknown"
if source not in subjects_by_image:
subjects_by_image[source] = []
subjects_by_image[source].append(subject)
for i, (source, subjects) in enumerate(list(subjects_by_image.items())[:3]):
print(f" Image {i}: ✓ {len(subjects)} person(s) detected")
if len(subjects_by_image) > 3:
print(f" ... and {len(subjects_by_image) - 3} more images")
# ============================================================================
# STEP 4: Different Distance Metrics
# ============================================================================
print("\n" + "=" * 80)
print("STEP 4: Different Distance Metrics")
print("=" * 80)
print("\n📏 Testing verification with different distance metrics...")
print(" (Comparing image to itself, so all should return verified=True)\n")
metrics = ["cosine", "euclidean", "euclidean_l2"]
for metric in metrics:
result = dp.verify(
SAMPLE_IMAGE,
SAMPLE_IMAGE,
distance_metric=metric,
)
verified_str = "✓" if result.verified else "✗"
print(
f" {metric:15s} | Distance: {result.distance:6.4f} | "
f"Threshold: {result.threshold:5.4f} | {verified_str}"
)
# ============================================================================
# STEP 5: Custom Parameters
# ============================================================================
print("\n" + "=" * 80)
print("STEP 5: Custom Parameters")
print("=" * 80)
print("\n⚙️ Testing with custom verification threshold...")
# Use a very strict threshold
strict_result = dp.verify(
SAMPLE_IMAGE,
SAMPLE_IMAGE,
threshold=0.1, # Very strict
)
print("\n Strict threshold (0.1):")
print(f" Distance: {strict_result.distance:.4f}")
print(f" Threshold: {strict_result.threshold:.4f}")
print(
f" Result: {'✓ Verified' if strict_result.verified else '✗ Not verified'}"
)
# Use a very lenient threshold
lenient_result = dp.verify(
SAMPLE_IMAGE,
SAMPLE_IMAGE,
threshold=2.0, # Very lenient
)
print("\n Lenient threshold (2.0):")
print(f" Distance: {lenient_result.distance:.4f}")
print(f" Threshold: {lenient_result.threshold:.4f}")
print(
f" Result: {'✓ Verified' if lenient_result.verified else '✗ Not verified'}"
)
# ============================================================================
# Summary
# ============================================================================
print("\n" + "=" * 80)
print("📚 API Summary")
print("=" * 80)
print("\nThe DeepPerson API provides two core stateless methods:\n")
print("1️⃣ represent() - Generate multi-modal embeddings")
print(" • Single image or batch processing (automatic detection)")
print(" • Uses optimized batch processing for multiple images (2-5x speedup)")
print(" • Body embeddings (required)")
print(" • Optional face embeddings (generate_face_embeddings=True)")
print(" • Configurable normalization and batch size")
print(" • Returns: subjects with embeddings + metadata\n")
print("2️⃣ verify() - Identity verification")
print(" • Compare two images for same person")
print(" • Multi-modal fusion scoring (body + face)")
print(" • Configurable distance metrics: cosine, euclidean, euclidean_l2")
print(" • Automatic threshold lookup or custom threshold")
print(" • Returns: verification result + distances + fusion info\n")
print("✨ Key Features:")
print(" ✓ Stateless - no gallery management required")
print(" ✓ Multi-modal - body and face embeddings")
print(" ✓ Optimized batch processing - automatic for multiple images")
print(" ✓ Multiple metrics - choose the best for your use case")
print(" ✓ GPU acceleration - automatic CUDA detection")
print(" ✓ Confidence-based fusion - weighted scoring\n")
print("🚀 Quick Start:")
print(" from src.api import DeepPerson")
print(" dp = DeepPerson()")
print(" ")
print(" # Single image")
print(" result = dp.represent('image.jpg')")
print(" ")
print(" # Batch processing (optimized, automatic)")
print(" batch_result = dp.represent(['img1.jpg', 'img2.jpg', 'img3.jpg'])")
print(" ")
print(" # Identity verification")
print(" is_same = dp.verify('img1.jpg', 'img2.jpg')")
print()
if __name__ == "__main__":
main()