mustafa2ak commited on
Commit
e23353b
·
verified ·
1 Parent(s): 5b5967c

Update reid.py

Browse files
Files changed (1) hide show
  1. reid.py +94 -905
reid.py CHANGED
@@ -1,145 +1,39 @@
1
  """
2
- Enhanced ReID with Recommendations 1-9 Applied
3
- Includes comprehensive debugging system for diagnostics
4
  """
5
  import numpy as np
6
  import cv2
7
  import torch
8
  import timm
9
  from sklearn.metrics.pairwise import cosine_similarity
10
- from typing import Dict, List, Optional, Tuple
11
- from dataclasses import dataclass, field
12
- from collections import defaultdict, deque
13
- from datetime import datetime, timedelta
14
- from pathlib import Path
15
- import warnings
16
- import json
17
- warnings.filterwarnings('ignore')
18
 
19
- from database import DogDatabase
20
 
21
- # Debug configuration
22
- DEBUG_CONFIG = {
23
- 'VERBOSE': True, # Master switch for debugging
24
- 'LOG_THRESHOLDS': True, # Log threshold decisions
25
- 'LOG_QUALITY': True, # Log feature quality scores
26
- 'LOG_ADAPTIVE': True, # Log adaptive threshold calculations
27
- 'LOG_STORAGE': True, # Log storage reduction
28
- 'LOG_AGGREGATION': True, # Log mean embedding stats
29
- 'LOG_MATCHES': True, # Log matching decisions
30
- 'SAVE_DEBUG_FILE': True, # Save debug info to file
31
- 'DEBUG_FILE_PATH': 'reid_debug.json'
32
- }
33
-
34
- @dataclass
35
- class DebugInfo:
36
- """Stores debug information for analysis"""
37
- timestamp: datetime = field(default_factory=datetime.now)
38
- frame_num: int = 0
39
- operation: str = ""
40
- details: Dict = field(default_factory=dict)
41
-
42
- def to_dict(self):
43
- return {
44
- 'timestamp': self.timestamp.isoformat(),
45
- 'frame': self.frame_num,
46
- 'operation': self.operation,
47
- 'details': self.details
48
- }
49
-
50
- @dataclass
51
- class DogFeatures:
52
- features: np.ndarray
53
- bbox: List[float] = field(default_factory=list)
54
- confidence: float = 0.5
55
- quality: float = 0.5 # ADDED: Recommendation #7
56
- frame_num: int = 0
57
- timestamp: datetime = field(default_factory=datetime.now)
58
- image: Optional[np.ndarray] = None
59
- angle: str = "unknown"
60
- distance: str = "medium"
61
 
62
- # Debug info
63
- quality_components: Dict = field(default_factory=dict) # Breakdown of quality score
64
-
65
- @dataclass
66
- class SleepingTrack:
67
- dog_id: int
68
- last_position: Tuple[float, float]
69
- last_seen: datetime
70
- last_frame: int
71
- features_list: List[DogFeatures]
72
- avg_embedding: np.ndarray
73
-
74
- @dataclass
75
- class ActiveDog:
76
- temp_id: int
77
- dog_id: int
78
- features_list: List[DogFeatures]
79
- last_frame_seen: int
80
- last_position: Tuple[float, float]
81
-
82
- # Debug tracking
83
- match_history: List[float] = field(default_factory=list) # Similarity scores over time
84
- threshold_history: List[float] = field(default_factory=list) # Applied thresholds
85
-
86
- class SQLiteEnhancedReID:
87
- """ReID with Recommendations 1-9 and comprehensive debugging"""
88
-
89
- def __init__(self, device: str = 'cuda', db_path: str = 'dog_monitoring.db'):
90
  self.device = device if torch.cuda.is_available() else 'cpu'
91
- self.db = DogDatabase(db_path)
92
 
93
- # RECOMMENDATION #1: Fixed threshold hierarchy (DB > Session)
94
- self.session_threshold = 0.35 # Base threshold for session matching
95
- self.database_threshold = 0.55 # STRICTER for database (was incorrectly lower)
96
- self.sleeping_threshold = 0.30 # More lenient for sleeping tracks
97
 
98
- self.sleeping_tracks: List[SleepingTrack] = []
99
- self.sleeping_track_timeout = 300
100
- self.sleeping_frame_timeout = 180
101
- self.max_sleeping_tracks = 30
102
-
103
- self.active_dogs: Dict[int, ActiveDog] = {}
104
- self.session_dogs = {}
105
- self.temp_id_features = {}
106
  self.next_temp_id = 1
107
  self.current_frame = 0
108
  self.current_video_source = "unknown"
109
 
110
- self.db_embeddings_cache = {}
111
- self._load_database_embeddings()
112
- self._initialize_megadescriptor()
113
-
114
- # Debug system
115
- self.debug_log = []
116
- self.debug_stats = defaultdict(list)
117
 
118
- # Quality tracking
119
- self.quality_history = defaultdict(list)
120
- self.feature_reduction_stats = defaultdict(int)
121
-
122
- # Aggregation tracking
123
- self.aggregation_stats = {
124
- 'mean_computations': 0,
125
- 'individual_comparisons': 0,
126
- 'mean_effectiveness': []
127
- }
128
-
129
- print("="*80)
130
- print("Enhanced ReID with Debugging Initialized")
131
- print("="*80)
132
- print(f"Device: {self.device}")
133
- print(f"Database: {db_path}")
134
- print(f"Registered dogs: {len(self.db_embeddings_cache)}")
135
- print("\n📊 RECOMMENDATION #1: Fixed Thresholds")
136
- print(f" Session threshold: {self.session_threshold:.2f}")
137
- print(f" Database threshold: {self.database_threshold:.2f} (STRICTER)")
138
- print(f" Sleeping threshold: {self.sleeping_threshold:.2f}")
139
- print(f" ✅ Database > Session: {self.database_threshold > self.session_threshold}")
140
- print("="*80)
141
-
142
- def _initialize_megadescriptor(self):
143
  try:
144
  self.model = timm.create_model(
145
  'hf-hub:BVRA/MegaDescriptor-L-384',
@@ -153,36 +47,32 @@ class SQLiteEnhancedReID:
153
  mean=[0.5, 0.5, 0.5],
154
  std=[0.5, 0.5, 0.5]
155
  )
156
- print("MegaDescriptor-L-384 loaded successfully")
157
  except Exception as e:
158
- print(f"Error loading model: {e}")
159
  self.model = None
160
-
161
- def _load_database_embeddings(self):
162
- self.db_embeddings_cache.clear()
163
- dogs_df = self.db.get_all_dogs(active_only=True)
164
-
165
- for _, dog in dogs_df.iterrows():
166
- dog_id = dog['dog_id']
167
- features = self.db.get_features(dog_id, limit=20)
168
-
169
- if features:
170
- embeddings = [f['resnet_features'] for f in features]
171
- self.db_embeddings_cache[dog_id] = {
172
- 'name': dog['name'] or f"Dog #{dog_id}",
173
- 'embeddings': embeddings,
174
- 'total_sightings': dog['total_sightings']
175
- }
176
-
177
- print(f"📁 Loaded {len(self.db_embeddings_cache)} dogs from database")
178
-
179
  def set_video_source(self, video_path: str):
 
180
  self.current_video_source = video_path
181
-
182
- def extract_features(self, image: np.ndarray, bbox: List[float] = None) -> Optional[DogFeatures]:
 
 
 
 
 
 
 
 
183
  if image is None or image.size == 0 or self.model is None:
184
  return None
185
-
186
  try:
187
  img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
188
  from PIL import Image
@@ -191,788 +81,87 @@ class SQLiteEnhancedReID:
191
 
192
  with torch.no_grad():
193
  features = self.model(img_tensor)
194
-
195
  features = features.squeeze().cpu().numpy()
196
  features = features / (np.linalg.norm(features) + 1e-7)
197
 
198
- # Check for degenerate features
199
- if np.allclose(features, 1.0) or np.allclose(features, 0.0):
200
- print(f"⚠️ WARNING: Degenerate features at frame {self.current_frame}")
201
- return None
202
-
203
- h, w = image.shape[:2]
204
- aspect_ratio = w / h if h > 0 else 1.0
205
- angle = "side" if 0.8 < aspect_ratio < 1.5 else "front" if aspect_ratio > 1.5 else "angled"
206
- distance = "close" if max(h, w) > 200 else "far" if max(h, w) < 80 else "medium"
207
-
208
- return DogFeatures(
209
- features=features,
210
- bbox=bbox if bbox else [0, 0, 100, 100],
211
- frame_num=self.current_frame,
212
- timestamp=datetime.now(),
213
- image=image.copy(),
214
- angle=angle,
215
- distance=distance
216
- )
217
  except Exception as e:
218
- print(f"Feature extraction error: {e}")
219
  return None
220
-
221
- def compute_feature_quality(self, image: np.ndarray, bbox: List[float],
222
- confidence: float) -> Tuple[float, Dict]:
223
- """
224
- RECOMMENDATION #7: Feature quality scoring with detailed breakdown
225
- Returns: (quality_score, components_dict)
226
- """
227
- components = {}
228
- score = 0.0
229
-
230
- # Factor 1: Detection confidence (30%)
231
- conf_score = confidence
232
- components['detection_confidence'] = conf_score
233
- score += 0.3 * conf_score
234
-
235
- # Factor 2: Bounding box size (20%)
236
- h, w = image.shape[:2]
237
- bbox_area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
238
- frame_area = h * w
239
- size_ratio = bbox_area / frame_area if frame_area > 0 else 0
240
- size_score = min(1.0, size_ratio / 0.15) # Ideal is 15% of frame
241
- components['bbox_size'] = size_score
242
- score += 0.2 * size_score
243
-
244
- # Factor 3: Image sharpness using Laplacian variance (30%)
245
- try:
246
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
247
- laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()
248
- sharp_score = min(1.0, laplacian_var / 500)
249
- components['sharpness'] = sharp_score
250
- score += 0.3 * sharp_score
251
- except:
252
- components['sharpness'] = 0.5
253
- score += 0.15
254
-
255
- # Factor 4: Centrality in frame (20%)
256
- center_x = (bbox[0] + bbox[2]) / 2
257
- center_y = (bbox[1] + bbox[3]) / 2
258
- frame_center_x = w / 2
259
- frame_center_y = h / 2
260
- dist_from_center = np.sqrt((center_x - frame_center_x)**2 + (center_y - frame_center_y)**2)
261
- max_dist = np.sqrt((w/2)**2 + (h/2)**2)
262
- center_score = 1.0 - (dist_from_center / max_dist) if max_dist > 0 else 0.5
263
- components['centrality'] = center_score
264
- score += 0.2 * center_score
265
-
266
- # Log quality if debugging enabled
267
- if DEBUG_CONFIG['LOG_QUALITY']:
268
- self.debug_log.append(DebugInfo(
269
- frame_num=self.current_frame,
270
- operation="quality_scoring",
271
- details={
272
- 'total_score': score,
273
- 'components': components,
274
- 'bbox_area_px': bbox_area,
275
- 'frame_coverage': f"{size_ratio*100:.1f}%"
276
- }
277
- ))
278
-
279
- return score, components
280
-
281
- def check_sleeping_tracks(self, features: np.ndarray, position: Tuple[float, float]) -> Optional[int]:
282
- """Check sleeping tracks with detailed debugging"""
283
- if not self.sleeping_tracks:
284
- return None
285
-
286
- current_time = datetime.now()
287
- best_match = None
288
- best_score = 0
289
- all_scores = []
290
-
291
- # Clean old sleeping tracks
292
- old_count = len(self.sleeping_tracks)
293
- self.sleeping_tracks = [
294
- st for st in self.sleeping_tracks
295
- if (current_time - st.last_seen).total_seconds() < self.sleeping_track_timeout
296
- and (self.current_frame - st.last_frame) < self.sleeping_frame_timeout
297
- ]
298
-
299
- if old_count != len(self.sleeping_tracks):
300
- print(f"🧹 Cleaned {old_count - len(self.sleeping_tracks)} old sleeping tracks")
301
-
302
- for sleeping_track in self.sleeping_tracks:
303
- time_diff = (current_time - sleeping_track.last_seen).total_seconds()
304
- frame_diff = self.current_frame - sleeping_track.last_frame
305
-
306
- # Temporal bonuses
307
- time_bonus = 0.08 if time_diff < 5 else 0.05 if time_diff < 15 else 0.02
308
- frame_bonus = 0.05 if frame_diff < 30 else 0.02 if frame_diff < 90 else 0
309
-
310
- # Spatial bonus
311
- last_x, last_y = sleeping_track.last_position
312
- curr_x, curr_y = position
313
- spatial_distance = np.sqrt((curr_x - last_x)**2 + (curr_y - last_y)**2)
314
- spatial_bonus = 0.06 if spatial_distance < 80 else 0.03 if spatial_distance < 150 else 0
315
-
316
- # Feature similarity
317
- similarity = cosine_similarity(
318
- features.reshape(1, -1),
319
- sleeping_track.avg_embedding.reshape(1, -1)
320
- )[0, 0]
321
-
322
- final_score = similarity + time_bonus + frame_bonus + spatial_bonus
323
-
324
- all_scores.append({
325
- 'dog_id': sleeping_track.dog_id,
326
- 'similarity': similarity,
327
- 'time_bonus': time_bonus,
328
- 'frame_bonus': frame_bonus,
329
- 'spatial_bonus': spatial_bonus,
330
- 'final_score': final_score,
331
- 'time_gap': time_diff,
332
- 'frame_gap': frame_diff,
333
- 'spatial_dist': spatial_distance
334
- })
335
-
336
- if final_score > best_score and final_score >= self.sleeping_threshold:
337
- best_score = final_score
338
- best_match = sleeping_track.dog_id
339
-
340
- # Debug logging
341
- if DEBUG_CONFIG['VERBOSE'] and all_scores:
342
- print(f"\n🛏️ Sleeping Track Check (Frame {self.current_frame}):")
343
- for s in sorted(all_scores, key=lambda x: x['final_score'], reverse=True)[:3]:
344
- print(f" Dog {s['dog_id']}: score={s['final_score']:.3f} "
345
- f"(sim={s['similarity']:.3f}, time_gap={s['time_gap']:.1f}s, "
346
- f"spatial={s['spatial_dist']:.1f}px)")
347
-
348
- if best_match:
349
- print(f" ✅ RE-ENTRY: Dog ID {best_match} (score: {best_score:.3f})")
350
- self.sleeping_tracks = [st for st in self.sleeping_tracks if st.dog_id != best_match]
351
-
352
- return best_match
353
-
354
- def check_database(self, features: np.ndarray) -> Optional[int]:
355
- """Database matching with debugging"""
356
- if not self.db_embeddings_cache:
357
- return None
358
-
359
- best_match = None
360
- best_score = 0
361
- all_scores = []
362
-
363
- for dog_id, dog_data in self.db_embeddings_cache.items():
364
- embeddings = dog_data['embeddings']
365
- similarities = []
366
-
367
- for emb in embeddings:
368
- sim = cosine_similarity(
369
- features.reshape(1, -1),
370
- emb.reshape(1, -1)
371
- )[0, 0]
372
- similarities.append(sim)
373
-
374
- max_sim = max(similarities) if similarities else 0
375
- avg_sim = np.mean(similarities) if similarities else 0
376
-
377
- all_scores.append({
378
- 'dog_id': dog_id,
379
- 'name': dog_data['name'],
380
- 'max_sim': max_sim,
381
- 'avg_sim': avg_sim,
382
- 'num_embeddings': len(embeddings)
383
- })
384
-
385
- if max_sim > best_score:
386
- best_score = max_sim
387
- best_match = dog_id
388
-
389
- # Debug output
390
- if DEBUG_CONFIG['LOG_MATCHES'] and all_scores:
391
- all_scores.sort(key=lambda x: x['max_sim'], reverse=True)
392
- print(f"\n🗄️ Database Matching (threshold={self.database_threshold:.2f}):")
393
- for s in all_scores[:3]:
394
- status = "✅" if s['max_sim'] >= self.database_threshold else "❌"
395
- print(f" {status} {s['name']}: max={s['max_sim']:.3f}, "
396
- f"avg={s['avg_sim']:.3f} ({s['num_embeddings']} samples)")
397
-
398
- if best_score >= self.database_threshold:
399
- dog_name = self.db_embeddings_cache[best_match]['name']
400
- print(f" 🎯 DATABASE MATCH: {dog_name} (ID: {best_match}, score: {best_score:.3f})")
401
- return best_match
402
-
403
- return None
404
-
405
- def compute_mean_embedding(self, features_list: List[DogFeatures]) -> np.ndarray:
406
- """
407
- RECOMMENDATION #9: Mean embedding aggregation with quality weighting
408
- """
409
- if not features_list:
410
- return None
411
-
412
- # Extract embeddings and qualities
413
- embeddings = []
414
- qualities = []
415
-
416
- for feat in features_list[-20:]: # Use last 20
417
- embeddings.append(feat.features)
418
- qualities.append(feat.quality)
419
-
420
- embeddings = np.array(embeddings)
421
- qualities = np.array(qualities)
422
 
423
- # Quality-weighted mean
424
- weights = np.array([]) # ✅ ensure weights always exists
425
- if np.sum(qualities) > 0:
426
- weights = qualities / np.sum(qualities)
427
- mean_embedding = np.average(embeddings, axis=0, weights=weights)
428
- else:
429
- mean_embedding = np.mean(embeddings, axis=0)
430
-
431
- # Normalize
432
- mean_embedding = mean_embedding / (np.linalg.norm(mean_embedding) + 1e-7)
433
-
434
- # Track aggregation stats
435
- self.aggregation_stats['mean_computations'] += 1
436
-
437
- if DEBUG_CONFIG['LOG_AGGREGATION']:
438
- variance = np.var(embeddings, axis=0).mean()
439
- self.debug_log.append(DebugInfo(
440
- frame_num=self.current_frame,
441
- operation="mean_aggregation",
442
- details={
443
- 'num_embeddings': len(embeddings),
444
- 'avg_quality': float(np.mean(qualities)) if qualities.size > 0 else 0,
445
- 'embedding_variance': float(variance),
446
- 'weight_range': [float(weights.min()), float(weights.max())] if weights.size > 0 else [0, 0]
447
- }
448
- ))
449
-
450
- return mean_embedding
451
-
452
-
453
- def check_session(self, features: np.ndarray, threshold: float = None) -> Optional[int]:
454
- """
455
- Session matching with hierarchical search and mean aggregation
456
- """
457
- if threshold is None:
458
- threshold = self.session_threshold
459
-
460
- # Stage 1: Active IDs (seen in last 30 frames)
461
- active_ids = [
462
- temp_id for temp_id in self.temp_id_features.keys()
463
- if temp_id in self.active_dogs and
464
- (self.current_frame - self.active_dogs[temp_id].last_frame_seen) < 30
465
- ]
466
-
467
- # Stage 2: Recently active (30-90 frames)
468
- recent_ids = [
469
- temp_id for temp_id in self.temp_id_features.keys()
470
- if temp_id in self.active_dogs and
471
- 30 <= (self.current_frame - self.active_dogs[temp_id].last_frame_seen) < 90
472
- ]
473
-
474
- # Stage 3: Inactive IDs
475
- all_ids = set(self.temp_id_features.keys())
476
- inactive_ids = list(all_ids - set(active_ids) - set(recent_ids))
477
-
478
- # Search with different thresholds
479
- stages = [
480
- ('active', active_ids, threshold),
481
- ('recent', recent_ids, threshold + 0.05),
482
- ('inactive', inactive_ids, threshold + 0.10)
483
- ]
484
-
485
- best_match = None
486
- best_score = -1.0
487
- best_stage = None
488
-
489
- for stage_name, ids, stage_threshold in stages:
490
- if not ids:
491
- continue
492
-
493
- for temp_id in ids:
494
- # RECOMMENDATION #9: Use mean embedding
495
- mean_emb = self.compute_mean_embedding(self.temp_id_features[temp_id])
496
- if mean_emb is None:
497
- continue
498
-
499
- similarity = cosine_similarity(
500
- features.reshape(1, -1),
501
- mean_emb.reshape(1, -1)
502
- )[0, 0]
503
-
504
- if similarity > best_score:
505
- best_score = similarity
506
- best_match = temp_id if similarity >= stage_threshold else None
507
- best_stage = stage_name
508
-
509
- # Debug output
510
- if DEBUG_CONFIG['LOG_MATCHES']:
511
- print(f"\n🔍 Session Matching (Frame {self.current_frame}):")
512
- print(f" Searching: {len(active_ids)} active, {len(recent_ids)} recent, "
513
- f"{len(inactive_ids)} inactive")
514
- if best_match:
515
- print(f" ✅ MATCH: Temp ID {best_match} (stage={best_stage}, "
516
- f"score={best_score:.3f}, threshold={threshold:.2f})")
517
- else:
518
- print(f" ❌ No match (best_score={best_score:.3f} < threshold={threshold:.2f})")
519
-
520
- return best_match
521
-
522
- def compute_adaptive_threshold(self, track_metadata: Dict) -> float:
523
- """
524
- RECOMMENDATION #6: Adaptive thresholding based on DeepSORT confidence
525
- """
526
- base_threshold = self.session_threshold
527
- adjustment = 0.0
528
-
529
- hits = track_metadata.get('deepsort_hits', 0)
530
- age = track_metadata.get('deepsort_age', 0)
531
- time_since_update = track_metadata.get('frames_since_update', 0)
532
-
533
- # Calculate confidence level
534
- if hits > 10 and time_since_update == 0:
535
- confidence_level = 'high'
536
- adjustment = -0.20 # More lenient
537
- elif hits > 5 and time_since_update == 0:
538
- confidence_level = 'medium'
539
- adjustment = -0.10
540
- elif hits > 2 and time_since_update < 5:
541
- confidence_level = 'low'
542
- adjustment = -0.05
543
- else:
544
- confidence_level = 'none'
545
- adjustment = 0.0
546
-
547
- effective_threshold = max(0.15, base_threshold + adjustment)
548
-
549
- # Debug logging
550
- if DEBUG_CONFIG['LOG_ADAPTIVE']:
551
- self.debug_log.append(DebugInfo(
552
- frame_num=self.current_frame,
553
- operation="adaptive_threshold",
554
- details={
555
- 'base_threshold': base_threshold,
556
- 'adjustment': adjustment,
557
- 'effective_threshold': effective_threshold,
558
- 'confidence_level': confidence_level,
559
- 'deepsort_hits': hits,
560
- 'deepsort_age': age,
561
- 'time_since_update': time_since_update
562
- }
563
- ))
564
-
565
- if DEBUG_CONFIG['VERBOSE'] and adjustment != 0:
566
- print(f" 🎯 Adaptive Threshold: {base_threshold:.2f} → {effective_threshold:.2f} "
567
- f"(confidence={confidence_level}, hits={hits})")
568
-
569
- return effective_threshold
570
-
571
- def smart_feature_storage(self, temp_id: int, new_feature: DogFeatures) -> bool:
572
- """
573
- RECOMMENDATION #8: Reduce storage to 20 best features
574
- Returns: True if feature was stored, False if rejected
575
- """
576
- features_list = self.temp_id_features[temp_id]
577
-
578
- # Always store if we have less than 5
579
- if len(features_list) < 5:
580
- features_list.append(new_feature)
581
- self.feature_reduction_stats['stored_initial'] += 1
582
- return True
583
-
584
- # Check quality threshold
585
- if new_feature.quality < 0.4:
586
- self.feature_reduction_stats['rejected_quality'] += 1
587
- if DEBUG_CONFIG['LOG_STORAGE']:
588
- print(f" ❌ Feature rejected: quality {new_feature.quality:.2f} < 0.4")
589
- return False
590
-
591
- # Check diversity (avoid redundant features)
592
- recent_features = features_list[-5:]
593
- max_similarity = max([
594
- np.dot(new_feature.features, f.features)
595
- for f in recent_features
596
- ])
597
-
598
- if max_similarity > 0.95:
599
- self.feature_reduction_stats['rejected_redundant'] += 1
600
- if DEBUG_CONFIG['LOG_STORAGE']:
601
- print(f" ❌ Feature rejected: too similar ({max_similarity:.3f}) to existing")
602
- return False
603
-
604
- # Add the feature
605
- features_list.append(new_feature)
606
- self.feature_reduction_stats['stored_diverse'] += 1
607
-
608
- # RECOMMENDATION #8: Keep only top 20 by quality
609
- if len(features_list) > 20:
610
- # Sort by quality
611
- features_list.sort(key=lambda x: x.quality, reverse=True)
612
- removed_count = len(features_list) - 20
613
- features_list = features_list[:20]
614
- self.temp_id_features[temp_id] = features_list
615
- self.feature_reduction_stats['pruned'] += removed_count
616
-
617
- if DEBUG_CONFIG['LOG_STORAGE']:
618
- qualities = [f.quality for f in features_list]
619
- print(f" 🗑️ Pruned {removed_count} features. Quality range: "
620
- f"[{min(qualities):.2f}-{max(qualities):.2f}]")
621
-
622
- return True
623
-
624
- def match_or_register_all(self, track, deepsort_hits=0, deepsort_age=0,
625
- frames_since_update=0) -> Dict:
626
  """
627
- RECOMMENDATION #5: Main matching with DeepSORT metadata integration
 
 
628
  """
629
  self.current_frame += 1
630
- self._auto_move_inactive_to_sleeping()
631
 
632
- # Get detection and image
633
  detection = None
634
  for det in reversed(track.detections[-3:]):
635
  if det.image_crop is not None:
636
  detection = det
637
  break
638
-
639
- if detection is None or detection.image_crop is None:
640
- return self._empty_result()
641
-
642
- # Extract features
643
- features_obj = self.extract_features(
644
- detection.image_crop,
645
- detection.bbox if hasattr(detection, 'bbox') else None
646
- )
647
-
648
- if features_obj is None:
649
- return self._empty_result()
650
-
651
- # RECOMMENDATION #7: Compute quality score
652
- features_obj.quality, features_obj.quality_components = self.compute_feature_quality(
653
- detection.image_crop,
654
- features_obj.bbox,
655
- detection.confidence if hasattr(detection, 'confidence') else 0.5
656
- )
657
-
658
- features = features_obj.features
659
- bbox = features_obj.bbox
660
- position = ((bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2)
661
 
662
- # Log current state
663
- if DEBUG_CONFIG['VERBOSE']:
664
- print(f"\n{'='*60}")
665
- print(f"Frame {self.current_frame} | Track {track.track_id}")
666
- print(f"Feature quality: {features_obj.quality:.2f} | "
667
- f"DeepSORT: hits={deepsort_hits}, age={deepsort_age}, "
668
- f"since_update={frames_since_update}")
669
-
670
- # STAGE 1: Check sleeping tracks
671
- sleeping_dog_id = self.check_sleeping_tracks(features, position)
672
- if sleeping_dog_id:
673
- temp_id = self._get_temp_id_for_dog(sleeping_dog_id)
674
- if temp_id not in self.temp_id_features:
675
- self.temp_id_features[temp_id] = []
676
- self.smart_feature_storage(temp_id, features_obj)
677
- self._update_active_dog(temp_id, sleeping_dog_id, features_obj, position)
678
- self._save_to_database(sleeping_dog_id, features_obj, detection)
679
- return self._create_result(temp_id, sleeping_dog_id, 1.0, True, "sleeping_reentry")
680
-
681
- # STAGE 2: Check database
682
- db_dog_id = self.check_database(features)
683
 
684
- # RECOMMENDATION #6: Compute adaptive threshold
685
- track_metadata = {
686
- 'deepsort_hits': deepsort_hits,
687
- 'deepsort_age': deepsort_age,
688
- 'frames_since_update': frames_since_update
689
- }
690
- effective_threshold = self.compute_adaptive_threshold(track_metadata)
691
 
692
- # STAGE 3: Check session with adaptive threshold
693
- session_temp_id = self.check_session(features, effective_threshold)
 
694
 
695
- if session_temp_id is not None:
696
- # RECOMMENDATION #8: Smart storage
697
- self.smart_feature_storage(session_temp_id, features_obj)
698
-
699
- # Determine permanent ID
700
- if session_temp_id in self.session_dogs:
701
- dog_id = self.session_dogs[session_temp_id]
702
- elif db_dog_id:
703
- dog_id = db_dog_id
704
- self.session_dogs[session_temp_id] = dog_id
705
- else:
706
- dog_id = 0
707
-
708
- self._update_active_dog(session_temp_id, dog_id, features_obj, position)
709
 
710
- if dog_id > 0:
711
- self._save_to_database(dog_id, features_obj, detection)
712
-
713
- return self._create_result(session_temp_id, dog_id, 0.8,
714
- (db_dog_id is not None), "session_match")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715
  else:
716
- # New temp ID
717
  new_temp_id = self.next_temp_id
718
  self.next_temp_id += 1
719
- self.temp_id_features[new_temp_id] = [features_obj]
720
 
721
- if db_dog_id:
722
- self.session_dogs[new_temp_id] = db_dog_id
723
- self._update_active_dog(new_temp_id, db_dog_id, features_obj, position)
724
- self._save_to_database(db_dog_id, features_obj, detection)
725
- print(f" 📂 Known dog (ID {db_dog_id}) → New Temp ID {new_temp_id}")
726
- return self._create_result(new_temp_id, db_dog_id, 1.0, True, "database_new")
727
- else:
728
- self._update_active_dog(new_temp_id, 0, features_obj, position)
729
- print(f" 🆕 New dog: Temp ID {new_temp_id}")
730
- return self._create_result(new_temp_id, 0, 1.0, False, "completely_new")
731
-
732
- def _create_result(self, temp_id: int, dog_id: int, confidence: float,
733
- is_known: bool, match_type: str) -> Dict:
734
- """Create result dictionary with debug info"""
735
- result = {
736
- 'MegaDescriptor': {
737
- 'dog_id': temp_id,
738
- 'permanent_id': dog_id,
739
- 'confidence': confidence,
740
- 'is_known': is_known,
741
- 'permanent_name': self.db_embeddings_cache.get(dog_id, {}).get('name') if dog_id > 0 else None,
742
- 'match_type': match_type
743
- }
744
- }
745
-
746
- # Add debug info
747
- if DEBUG_CONFIG['VERBOSE']:
748
- result['debug'] = {
749
- 'frame': self.current_frame,
750
- 'match_type': match_type,
751
- 'active_dogs': len(self.active_dogs),
752
- 'sleeping_tracks': len(self.sleeping_tracks),
753
- 'temp_ids': len(self.temp_id_features)
754
- }
755
 
756
- return result
757
-
758
- def _empty_result(self) -> Dict:
759
- """Return empty result when no match possible"""
760
- return {
761
- 'MegaDescriptor': {
762
- 'dog_id': 0,
763
- 'permanent_id': 0,
764
- 'confidence': 0.0,
765
- 'is_known': False,
766
- 'permanent_name': None,
767
- 'match_type': 'no_detection'
768
  }
769
- }
770
-
771
- def _update_active_dog(self, temp_id: int, dog_id: int, features: DogFeatures,
772
- position: Tuple[float, float]):
773
- """Update active dog with match history"""
774
- if temp_id in self.active_dogs:
775
- active = self.active_dogs[temp_id]
776
- active.last_frame_seen = self.current_frame
777
- active.last_position = position
778
- active.features_list.append(features)
779
-
780
- # Keep last 30 features
781
- if len(active.features_list) > 30:
782
- active.features_list = active.features_list[-30:]
783
- else:
784
- self.active_dogs[temp_id] = ActiveDog(
785
- temp_id=temp_id,
786
- dog_id=dog_id,
787
- features_list=[features],
788
- last_frame_seen=self.current_frame,
789
- last_position=position
790
- )
791
-
792
- def _auto_move_inactive_to_sleeping(self):
793
- """Automatically move inactive dogs to sleeping"""
794
- inactive_temp_ids = []
795
-
796
- for temp_id, active_dog in self.active_dogs.items():
797
- frames_since_seen = self.current_frame - active_dog.last_frame_seen
798
- if frames_since_seen > 30 and active_dog.dog_id > 0:
799
- inactive_temp_ids.append(temp_id)
800
-
801
- for temp_id in inactive_temp_ids:
802
- active_dog = self.active_dogs[temp_id]
803
- if active_dog.features_list:
804
- # Use mean embedding for sleeping track
805
- mean_emb = self.compute_mean_embedding(active_dog.features_list)
806
-
807
- sleeping_track = SleepingTrack(
808
- dog_id=active_dog.dog_id,
809
- last_position=active_dog.last_position,
810
- last_seen=datetime.now(),
811
- last_frame=active_dog.last_frame_seen,
812
- features_list=active_dog.features_list[-10:],
813
- avg_embedding=mean_emb
814
- )
815
-
816
- self.sleeping_tracks.append(sleeping_track)
817
-
818
- # Limit sleeping tracks
819
- if len(self.sleeping_tracks) > self.max_sleeping_tracks:
820
- self.sleeping_tracks = sorted(
821
- self.sleeping_tracks,
822
- key=lambda x: x.last_frame,
823
- reverse=True
824
- )[:self.max_sleeping_tracks]
825
-
826
- print(f" 💤 Moved Dog ID {active_dog.dog_id} to sleeping "
827
- f"(inactive for {frames_since_seen} frames)")
828
-
829
- del self.active_dogs[temp_id]
830
-
831
- def _get_temp_id_for_dog(self, dog_id: int) -> int:
832
- """Get or create temp ID for a permanent dog ID"""
833
- for temp_id, stored_dog_id in self.session_dogs.items():
834
- if stored_dog_id == dog_id:
835
- return temp_id
836
-
837
- new_temp_id = self.next_temp_id
838
- self.next_temp_id += 1
839
- self.session_dogs[new_temp_id] = dog_id
840
- return new_temp_id
841
-
842
- def _save_to_database(self, dog_id: int, features: DogFeatures, detection):
843
- """Save to database with error handling"""
844
- try:
845
- self.db.update_dog_sighting(dog_id)
846
-
847
- color_histogram = np.zeros(256)
848
- self.db.save_features(
849
- dog_id=dog_id,
850
- resnet_features=features.features,
851
- color_histogram=color_histogram,
852
- confidence=features.confidence
853
- )
854
-
855
- self.db.save_image(
856
- dog_id=dog_id,
857
- image=features.image,
858
- frame_number=features.frame_num,
859
- video_source=self.current_video_source,
860
- bbox=features.bbox,
861
- confidence=features.confidence
862
- )
863
-
864
- position = ((features.bbox[0] + features.bbox[2]) / 2,
865
- (features.bbox[1] + features.bbox[3]) / 2)
866
-
867
- self.db.add_sighting(
868
- dog_id=dog_id,
869
- position=position,
870
- video_source=self.current_video_source,
871
- frame_number=features.frame_num,
872
- confidence=features.confidence
873
- )
874
- except Exception as e:
875
- print(f"❌ Database save error: {e}")
876
-
877
- def set_all_thresholds(self, threshold: float):
878
- """
879
- RECOMMENDATION #1: Fixed threshold hierarchy
880
- Database MUST be stricter than session
881
- """
882
- self.session_threshold = max(0.15, min(0.95, threshold))
883
- self.database_threshold = self.session_threshold + 0.20 # STRICTER
884
- self.sleeping_threshold = self.session_threshold - 0.05 # More lenient
885
-
886
- print(f"\n📊 Threshold Update:")
887
- print(f" Session: {self.session_threshold:.2f}")
888
- print(f" Database: {self.database_threshold:.2f} (stricter)")
889
- print(f" Sleeping: {self.sleeping_threshold:.2f} (lenient)")
890
- print(f" ✅ Correct hierarchy: DB > Session > Sleeping")
891
-
892
- def print_debug_summary(self):
893
- """Print comprehensive debug summary"""
894
- print("\n" + "="*80)
895
- print("DEBUG SUMMARY")
896
- print("="*80)
897
- all_qualities = []
898
- # Feature quality stats
899
- if self.quality_history:
900
-
901
- for qualities in self.quality_history.values():
902
- all_qualities.extend(qualities)
903
- print(f"\n📊 Feature Quality Stats:")
904
- print(f" Average: {np.mean(all_qualities):.3f}")
905
- print(f" Range: [{min(all_qualities):.3f} - {max(all_qualities):.3f}]")
906
-
907
- # Storage reduction stats
908
- print(f"\n💾 Storage Reduction Stats:")
909
- for key, value in self.feature_reduction_stats.items():
910
- print(f" {key}: {value}")
911
-
912
- # Aggregation stats
913
- print(f"\n🔄 Aggregation Stats:")
914
- print(f" Mean computations: {self.aggregation_stats['mean_computations']}")
915
- print(f" Individual comparisons: {self.aggregation_stats['individual_comparisons']}")
916
-
917
- # Save debug file if enabled
918
- if DEBUG_CONFIG['SAVE_DEBUG_FILE'] and self.debug_log:
919
- debug_data = {
920
- 'summary': {
921
- 'total_frames': self.current_frame,
922
- 'temp_ids_created': self.next_temp_id - 1,
923
- 'active_dogs': len(self.active_dogs),
924
- 'sleeping_tracks': len(self.sleeping_tracks),
925
- 'quality_stats': {
926
- 'avg': float(np.mean(all_qualities)) if all_qualities else 0,
927
- 'min': float(min(all_qualities)) if all_qualities else 0,
928
- 'max': float(max(all_qualities)) if all_qualities else 0
929
- },
930
- 'storage_stats': dict(self.feature_reduction_stats),
931
- 'aggregation_stats': dict(self.aggregation_stats)
932
- },
933
- 'log': [log.to_dict() for log in self.debug_log[-1000:]] # Last 1000 entries
934
- }
935
-
936
- with open(DEBUG_CONFIG['DEBUG_FILE_PATH'], 'w') as f:
937
- json.dump(debug_data, f, indent=2, default=str)
938
-
939
- print(f"\n💾 Debug log saved to {DEBUG_CONFIG['DEBUG_FILE_PATH']}")
940
-
941
- def reset_all(self):
942
- """Reset with summary"""
943
- self.print_debug_summary()
944
-
945
- self.temp_id_features.clear()
946
- self.session_dogs.clear()
947
- self.sleeping_tracks.clear()
948
- self.active_dogs.clear()
949
- self.next_temp_id = 1
950
- self.current_frame = 0
951
- self.debug_log.clear()
952
- self.debug_stats.clear()
953
- self.quality_history.clear()
954
- self.feature_reduction_stats.clear()
955
-
956
- print("\n🔄 Session reset complete\n")
957
-
958
  def get_statistics(self) -> Dict:
959
- """Get statistics with debug info"""
960
- dogs_df = self.db.get_all_dogs()
961
- db_stats = self.db.get_dog_statistics()
962
-
963
  return {
964
- 'session_dogs': len(self.temp_id_features),
965
- 'database_dogs': len(dogs_df),
966
- 'sleeping_tracks': len(self.sleeping_tracks),
967
- 'active_dogs': len(self.active_dogs),
968
- 'total_images': db_stats.get('total_images', 0),
969
- 'total_sightings': db_stats.get('total_sightings', 0),
970
- 'debug': {
971
- 'feature_reduction': dict(self.feature_reduction_stats),
972
- 'aggregation_count': self.aggregation_stats['mean_computations']
973
- }
974
- }
975
-
976
- # Compatibility aliases
977
- MegaDescriptorReID = SQLiteEnhancedReID
978
- EnhancedMegaDescriptorReID = SQLiteEnhancedReID
 
1
  """
2
+ Simplified ReID - Basic threshold matching only
3
+ No adaptive thresholds, no quality scoring, no smart storage
4
  """
5
  import numpy as np
6
  import cv2
7
  import torch
8
  import timm
9
  from sklearn.metrics.pairwise import cosine_similarity
10
+ from typing import Dict, Optional
11
+ from collections import defaultdict
12
+ from datetime import datetime
 
 
 
 
 
13
 
 
14
 
15
+ class SimplifiedReID:
16
+ """Simplified ReID with basic threshold matching"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ def __init__(self, device: str = 'cuda'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  self.device = device if torch.cuda.is_available() else 'cpu'
 
20
 
21
+ # Single threshold for all matching
22
+ self.threshold = 0.40
 
 
23
 
24
+ # Session tracking (temp IDs)
25
+ self.temp_id_features = {} # temp_id -> list of feature vectors
 
 
 
 
 
 
26
  self.next_temp_id = 1
27
  self.current_frame = 0
28
  self.current_video_source = "unknown"
29
 
30
+ # Initialize model
31
+ self._initialize_model()
 
 
 
 
 
32
 
33
+ print(f"Simplified ReID initialized on {self.device}")
34
+
35
+ def _initialize_model(self):
36
+ """Load MegaDescriptor model"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  try:
38
  self.model = timm.create_model(
39
  'hf-hub:BVRA/MegaDescriptor-L-384',
 
47
  mean=[0.5, 0.5, 0.5],
48
  std=[0.5, 0.5, 0.5]
49
  )
50
+ print("MegaDescriptor-L-384 loaded")
51
  except Exception as e:
52
+ print(f"Error loading model: {e}")
53
  self.model = None
54
+
55
+ def set_threshold(self, threshold: float):
56
+ """Set matching threshold"""
57
+ self.threshold = max(0.10, min(0.95, threshold))
58
+ print(f"Threshold set to: {self.threshold:.2f}")
59
+
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def set_video_source(self, video_path: str):
61
+ """Set current video source"""
62
  self.current_video_source = video_path
63
+
64
+ def reset_session(self):
65
+ """Clear session data"""
66
+ self.temp_id_features.clear()
67
+ self.next_temp_id = 1
68
+ self.current_frame = 0
69
+ print("Session reset")
70
+
71
+ def extract_features(self, image: np.ndarray) -> Optional[np.ndarray]:
72
+ """Extract feature vector from image"""
73
  if image is None or image.size == 0 or self.model is None:
74
  return None
75
+
76
  try:
77
  img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
78
  from PIL import Image
 
81
 
82
  with torch.no_grad():
83
  features = self.model(img_tensor)
84
+
85
  features = features.squeeze().cpu().numpy()
86
  features = features / (np.linalg.norm(features) + 1e-7)
87
 
88
+ return features
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  except Exception as e:
90
+ print(f"Feature extraction error: {e}")
91
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ def match_or_register(self, track) -> Dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  """
95
+ Simple matching: compare features against existing temp_ids
96
+ If match found -> return temp_id
97
+ If no match -> create new temp_id
98
  """
99
  self.current_frame += 1
 
100
 
101
+ # Get image crop from track
102
  detection = None
103
  for det in reversed(track.detections[-3:]):
104
  if det.image_crop is not None:
105
  detection = det
106
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
+ if detection is None or detection.image_crop is None:
109
+ return {'temp_id': 0}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
+ # Extract features
112
+ features = self.extract_features(detection.image_crop)
113
+ if features is None:
114
+ return {'temp_id': 0}
 
 
 
115
 
116
+ # Search for match in existing temp_ids
117
+ best_temp_id = None
118
+ best_score = -1.0
119
 
120
+ for temp_id, features_list in self.temp_id_features.items():
121
+ # Compare against all stored features for this temp_id
122
+ similarities = []
123
+ for stored_features in features_list:
124
+ sim = np.dot(features, stored_features)
125
+ similarities.append(sim)
 
 
 
 
 
 
 
 
126
 
127
+ if similarities:
128
+ max_sim = max(similarities)
129
+ if max_sim > best_score:
130
+ best_score = max_sim
131
+ best_temp_id = temp_id
132
+
133
+ # Check if best score passes threshold
134
+ if best_temp_id is not None and best_score >= self.threshold:
135
+ # Match found - add features to existing temp_id
136
+ self.temp_id_features[best_temp_id].append(features)
137
+
138
+ # Limit storage (keep last 30)
139
+ if len(self.temp_id_features[best_temp_id]) > 30:
140
+ self.temp_id_features[best_temp_id] = self.temp_id_features[best_temp_id][-30:]
141
+
142
+ return {
143
+ 'temp_id': best_temp_id,
144
+ 'confidence': best_score,
145
+ 'match_type': 'existing'
146
+ }
147
  else:
148
+ # No match - create new temp_id
149
  new_temp_id = self.next_temp_id
150
  self.next_temp_id += 1
151
+ self.temp_id_features[new_temp_id] = [features]
152
 
153
+ print(f"New temp_id: {new_temp_id} (threshold: {self.threshold:.2f})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
+ return {
156
+ 'temp_id': new_temp_id,
157
+ 'confidence': 1.0,
158
+ 'match_type': 'new'
 
 
 
 
 
 
 
 
159
  }
160
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  def get_statistics(self) -> Dict:
162
+ """Get simple statistics"""
 
 
 
163
  return {
164
+ 'temp_ids': len(self.temp_id_features),
165
+ 'threshold': self.threshold,
166
+ 'current_frame': self.current_frame
167
+ }