Repository navigation
Expand file tree
/
Copy pathrun_testset.py
More file actions
executable file
·1646 lines (1367 loc) · 59.2 KB
/
Copy pathrun_testset.py
File metadata and controls
executable file
·1646 lines (1367 loc) · 59.2 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
"""
CLI pour lancer un pipeline DuplicateFlow sur un testset avec cache de features.
Workflow en 2 phases:
1. Extraction : Pré-calcule et met en cache toutes les features
2. Comparaison : Compare rapidement en utilisant le cache
Usage:
python run_testset.py --testset default --pipeline audioshazam
python run_testset.py --testset default --pipeline balanced --limit 10
python run_testset.py --compare audioshazam,balanced,staged_test
python run_testset.py --interactive
python run_testset.py --list-testsets
python run_testset.py --list-pipelines
python run_testset.py --resume checkpoint_default_audioshazam.json
"""
import argparse
import sys
import json
import time
import threading
import termios
import tty
from pathlib import Path
from typing import Dict, List, Set, Any, Optional, Tuple
from datetime import datetime
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
# Rich imports
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.live import Live
from rich.layout import Layout
from rich.progress import (
Progress,
SpinnerColumn,
BarColumn,
TextColumn,
TimeRemainingColumn,
MofNCompleteColumn
)
from rich.prompt import Prompt, Confirm, IntPrompt
from rich.tree import Tree
from rich import box
from rich.text import Text
from rich.align import Align
console = Console()
def fix_terminal_mode():
"""Force terminal into cooked mode to handle Enter key properly."""
try:
if sys.stdin.isatty():
fd = sys.stdin.fileno()
# Get current settings
old_settings = termios.tcgetattr(fd)
# Make a copy
new_settings = termios.tcgetattr(fd)
# Enable canonical mode (ICANON) and echo (ECHO)
new_settings[3] |= termios.ICANON | termios.ECHO
# Apply new settings
termios.tcsetattr(fd, termios.TCSANOW, new_settings)
return old_settings
except Exception as e:
console.print(f"[yellow]Note: Could not configure terminal: {e}[/yellow]")
return None
def json_encoder(obj):
"""Custom JSON encoder for non-serializable types."""
if isinstance(obj, (bool, int, float, str, type(None))):
return obj
if isinstance(obj, dict):
return {k: json_encoder(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [json_encoder(item) for item in obj]
# For any other type, try to convert to string
return str(obj)
def safe_int_prompt(prompt: str, default: int) -> int:
"""Safe integer prompt that works with terminal issues."""
while True:
try:
# Force flush and use raw input
sys.stdout.write(f"\n{prompt} [{default}]: ")
sys.stdout.flush()
# Read directly from stdin
line = sys.stdin.readline()
if not line or line == '\n':
return default
value = line.strip()
if not value:
return default
return int(value)
except ValueError:
sys.stdout.write("Valeur invalide, veuillez entrer un nombre\n")
sys.stdout.flush()
except (EOFError, KeyboardInterrupt):
sys.stdout.write("\n")
sys.stdout.flush()
return default
def safe_confirm(prompt: str, default: bool) -> bool:
"""Safe yes/no prompt that works with terminal issues."""
default_str = "Y/n" if default else "y/N"
while True:
try:
# Force flush and use raw input
sys.stdout.write(f"\n{prompt} [{default_str}]: ")
sys.stdout.flush()
# Read directly from stdin
line = sys.stdin.readline()
if not line or line == '\n':
return default
value = line.strip().lower()
if not value:
return default
if value in ('y', 'yes', 'o', 'oui'):
return True
if value in ('n', 'no', 'non'):
return False
sys.stdout.write("Réponse invalide, utilisez y/n\n")
sys.stdout.flush()
except (EOFError, KeyboardInterrupt):
sys.stdout.write("\n")
sys.stdout.flush()
return default
def safe_text_prompt(prompt: str, default: str = "") -> str:
"""Safe text prompt that works with terminal issues."""
try:
# Force flush and use raw input
if default:
sys.stdout.write(f"\n{prompt} [{default}]: ")
else:
sys.stdout.write(f"\n{prompt}: ")
sys.stdout.flush()
# Read directly from stdin
line = sys.stdin.readline()
if not line or line == '\n':
return default
value = line.strip()
return value if value else default
except (EOFError, KeyboardInterrupt):
sys.stdout.write("\n")
sys.stdout.flush()
return default
# Add project to path
sys.path.insert(0, str(Path(__file__).parent))
# Add duplicateflow to path
duplicateflow_path = Path(__file__).parent / "duplicateflow"
if duplicateflow_path.exists():
sys.path.insert(0, str(duplicateflow_path))
from src.core.logger import Logger
from src.plugins.duplicate_finder.database_manager import VideoDatabase
from src.plugins.duplicate_finder.services.test_set_manager import TestSetManager
from src.plugins.duplicate_finder.orchestration.pipeline_manager import PipelineManager
# Import DuplicateFlow
from duplicateflow.storage import StorageManager
from duplicateflow.core import get_algorithm
import duplicateflow.algorithms
logger = Logger.get_logger('TestSetCLI')
# Use the ROOT database (same as GUI)
ROOT_DB_PATH = str(Path(__file__).parent / "video_duplicates.db")
# Checkpoint directory
CHECKPOINT_DIR = Path(__file__).parent / ".checkpoints"
CHECKPOINT_DIR.mkdir(exist_ok=True)
# Benchmark results directory
RESULTS_DIR = Path(__file__).parent / "benchmark_results"
RESULTS_DIR.mkdir(exist_ok=True)
class BenchmarkState:
"""Thread-safe benchmark state for live dashboard."""
def __init__(self, total_pairs: int, total_videos: int, total_algorithms: int):
self.total_pairs = total_pairs
self.total_videos = total_videos
self.total_algorithms = total_algorithms
self.current_phase = "Initialization"
self.current_pair = 0
self.current_video = ""
self.current_algorithm = ""
self.current_score = 0.0
self.current_result = ""
self.current_classification = ""
# Metrics
self.tp = 0
self.fp = 0
self.tn = 0
self.fn = 0
self.errors = 0
# Timing
self.start_time = time.time()
self.pair_times = []
# Extraction tracking
self.extracted_count = 0
self.cached_count = 0
self._lock = threading.Lock()
def update(self, **kwargs):
"""Thread-safe update of state."""
with self._lock:
for key, value in kwargs.items():
setattr(self, key, value)
def increment_metric(self, classification: str):
"""Thread-safe increment of classification metric."""
with self._lock:
if classification == 'tp':
self.tp += 1
elif classification == 'fp':
self.fp += 1
elif classification == 'tn':
self.tn += 1
elif classification == 'fn':
self.fn += 1
elif classification == 'error':
self.errors += 1
def add_pair_time(self, pair_time: float):
"""Thread-safe addition of pair timing."""
with self._lock:
self.pair_times.append(pair_time)
def get_metrics(self) -> Dict[str, int]:
"""Get current metrics."""
with self._lock:
return {
'tp': self.tp,
'fp': self.fp,
'tn': self.tn,
'fn': self.fn,
'errors': self.errors
}
def get_avg_time(self) -> float:
"""Get average pair time."""
with self._lock:
if not self.pair_times:
return 0.0
return sum(self.pair_times) / len(self.pair_times)
def get_eta(self) -> float:
"""Get estimated time remaining."""
with self._lock:
if not self.pair_times or self.current_pair == 0:
return 0.0
avg_time = sum(self.pair_times) / len(self.pair_times)
remaining = self.total_pairs - self.current_pair
return avg_time * remaining
def create_dashboard(state: BenchmarkState, pipeline_name: str) -> Layout:
"""Create rich dashboard layout."""
layout = Layout()
layout.split_column(
Layout(name="header", size=3),
Layout(name="body"),
Layout(name="footer", size=8)
)
# Header
elapsed = time.time() - state.start_time
header_text = f"[bold cyan]BENCHMARK:[/bold cyan] {pipeline_name} | Phase: {state.current_phase} | Elapsed: {elapsed:.1f}s"
layout["header"].update(Panel(header_text, style="bold blue"))
# Body - Current status
if state.current_phase == "Extraction":
body_content = f"""[yellow]Extracting features...[/yellow]
Video: {state.current_video}
Algorithm: {state.current_algorithm}
Progress: {state.extracted_count}/{state.total_videos * state.total_algorithms} ({state.cached_count} from cache)
"""
else:
body_content = f"""[cyan]Comparing pair {state.current_pair}/{state.total_pairs}[/cyan]
Videos: {state.current_video}
Score: [bold]{state.current_score:.1f}%[/bold]
Result: {state.current_result}
Classification: {state.current_classification}
"""
layout["body"].update(Panel(body_content, title="Current Status", border_style="cyan"))
# Footer - Metrics and timing
metrics = state.get_metrics()
total = metrics['tp'] + metrics['fp'] + metrics['tn'] + metrics['fn']
if total > 0:
precision = metrics['tp'] / (metrics['tp'] + metrics['fp']) if (metrics['tp'] + metrics['fp']) > 0 else 0
recall = metrics['tp'] / (metrics['tp'] + metrics['fn']) if (metrics['tp'] + metrics['fn']) > 0 else 0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
accuracy = (metrics['tp'] + metrics['tn']) / total
metrics_text = f"""[bold]Live Metrics:[/bold]
TP: [green]{metrics['tp']}[/green] FP: [yellow]{metrics['fp']}[/yellow] TN: [green]{metrics['tn']}[/green] FN: [red]{metrics['fn']}[/red] Errors: [red]{metrics['errors']}[/red]
Precision: [cyan]{precision*100:.1f}%[/cyan] Recall: [cyan]{recall*100:.1f}%[/cyan] F1: [cyan]{f1*100:.1f}%[/cyan] Accuracy: [cyan]{accuracy*100:.1f}%[/cyan]
Avg time: {state.get_avg_time():.2f}s/pair ETA: {state.get_eta():.0f}s
"""
else:
metrics_text = "[dim]Waiting for first comparison...[/dim]"
layout["footer"].update(Panel(metrics_text, title="Metrics", border_style="green"))
return layout
def list_testsets_interactive(db: VideoDatabase) -> Optional[str]:
"""List testsets and let user select one."""
test_set_manager = TestSetManager(db)
test_sets = test_set_manager.list_test_sets()
if not test_sets:
console.print("[red]Aucun testset trouvé.[/red]")
return None
table = Table(title="Testsets Disponibles", box=box.ROUNDED)
table.add_column("#", style="cyan", justify="right")
table.add_column("Nom", style="green")
table.add_column("Total", style="yellow", justify="right")
table.add_column("Positives", style="blue", justify="right")
table.add_column("Négatives", style="magenta", justify="right")
for i, ts in enumerate(test_sets, 1):
stats = test_set_manager.get_stats(ts['name'])
table.add_row(
str(i),
ts['name'],
str(stats['total']),
str(stats['positives']),
str(stats['negatives'])
)
console.print(table)
console.print()
choice = safe_int_prompt("Sélectionner un testset", default=1)
idx = choice - 1
if 0 <= idx < len(test_sets):
return test_sets[idx]['name']
else:
console.print(f"[red]Choix invalide: {choice}[/red]")
return None
def list_pipelines_interactive(db: VideoDatabase) -> Optional[str]:
"""List pipelines and let user select one."""
pipeline_manager = PipelineManager(db)
db_pipelines = pipeline_manager.list_pipelines(include_defaults=True)
if not db_pipelines:
console.print("[red]Aucun pipeline trouvé.[/red]")
return None
table = Table(title="Pipelines Disponibles", box=box.ROUNDED)
table.add_column("#", style="cyan", justify="right")
table.add_column("Nom", style="green")
table.add_column("Mode", style="yellow")
table.add_column("Algorithmes", style="blue", justify="right")
table.add_column("Type", style="magenta")
for i, p in enumerate(db_pipelines, 1):
methods = p.get('methods', [])
mode = p.get('mode', 'unknown')
is_default = "Défaut" if p.get('is_default') else "Custom"
table.add_row(
str(i),
p['name'],
mode,
str(len(methods)),
is_default
)
console.print(table)
console.print()
choice = safe_int_prompt("Sélectionner un pipeline", default=1)
idx = choice - 1
if 0 <= idx < len(db_pipelines):
return db_pipelines[idx]['name']
else:
console.print(f"[red]Choix invalide: {choice}[/red]")
return None
def list_testsets(db: VideoDatabase):
"""List all available test sets."""
test_set_manager = TestSetManager(db)
test_sets = test_set_manager.list_test_sets()
if not test_sets:
console.print("[red]Aucun testset trouvé.[/red]")
return
table = Table(title="Testsets Disponibles", box=box.ROUNDED)
table.add_column("Nom", style="green")
table.add_column("Total", style="yellow", justify="right")
table.add_column("Positives", style="blue", justify="right")
table.add_column("Négatives", style="magenta", justify="right")
for ts in test_sets:
stats = test_set_manager.get_stats(ts['name'])
table.add_row(
ts['name'],
str(stats['total']),
str(stats['positives']),
str(stats['negatives'])
)
console.print(table)
def list_pipelines(db: VideoDatabase):
"""List all available pipelines."""
try:
pipeline_manager = PipelineManager(db)
db_pipelines = pipeline_manager.list_pipelines(include_defaults=True)
if not db_pipelines:
console.print("[red]Aucun pipeline trouvé[/red]")
return
custom = [p for p in db_pipelines if not p.get('is_default')]
defaults = [p for p in db_pipelines if p.get('is_default')]
if custom:
table = Table(title="Pipelines Personnalisés", box=box.ROUNDED)
table.add_column("Nom", style="green")
table.add_column("Mode", style="cyan")
table.add_column("Algorithmes", style="yellow", justify="right")
for p in custom:
methods = p.get('methods', [])
mode = p.get('mode', 'unknown')
table.add_row(p['name'], mode, str(len(methods)))
console.print(table)
if defaults:
table = Table(title="Pipelines par Défaut", box=box.ROUNDED)
table.add_column("Nom", style="green")
table.add_column("Mode", style="cyan")
for p in defaults[:10]:
mode = p.get('mode', 'unknown')
table.add_row(p['name'], mode)
console.print(table)
except Exception as e:
console.print(f"[red]Erreur: {e}[/red]")
logger.error(f"Error listing pipelines: {e}", exc_info=True)
def extract_features_for_video(
video_path: str,
algorithm_name: str,
params: Dict,
storage: StorageManager,
force_recompute: bool = False
) -> Tuple[bool, bool]:
"""
Extract and cache features for a single video.
Returns:
(success, was_cached)
"""
try:
# Check if already cached (unless force_recompute)
if not force_recompute:
cached = storage.get_cached_features(video_path, algorithm_name, params)
if cached is not None:
return (True, True) # Success, was cached
# Extract features
AlgoClass = get_algorithm(algorithm_name)
algo = AlgoClass()
algo.configure(**params)
# Try extract_features() first (new standard), then extract_fingerprints() (legacy)
if hasattr(algo, 'extract_features'):
features = algo.extract_features(video_path)
metadata = {
'num_features': len(features) if isinstance(features, (list, dict)) else 0,
'feature_type': type(features).__name__
}
elif hasattr(algo, 'extract_fingerprints'):
# Fallback for legacy audio_fingerprint
features = algo.extract_fingerprints(video_path)
metadata = {
'num_hashes': len(features) if isinstance(features, dict) else 0,
'feature_type': 'fingerprints'
}
else:
# Algorithm doesn't support feature extraction yet
logger.warning(f"Algorithm {algorithm_name} doesn't have extract_features() method")
return (True, False)
# Store in cache
storage.store_features(video_path, algorithm_name, params, features, metadata)
return (True, False) # Success, was extracted
except Exception as e:
logger.error(f"Error extracting features from {video_path}: {e}")
return (False, False)
def save_checkpoint(
checkpoint_path: Path,
testset_name: str,
pipeline_name: str,
processed_pairs: List[Dict],
remaining_pairs: List[Dict],
metrics: Dict,
start_time: float
):
"""Save checkpoint for resume capability."""
checkpoint_data = {
'testset': testset_name,
'pipeline': pipeline_name,
'timestamp': datetime.now().isoformat(),
'processed_count': len(processed_pairs),
'remaining_count': len(remaining_pairs),
'metrics': metrics,
'elapsed_time': time.time() - start_time,
'processed_pairs': processed_pairs,
'remaining_pairs': remaining_pairs
}
# Sanitize data before saving
safe_checkpoint_data = json_encoder(checkpoint_data)
with open(checkpoint_path, 'w', encoding='utf-8') as f:
json.dump(safe_checkpoint_data, f, indent=2, ensure_ascii=False)
def load_checkpoint(checkpoint_path: Path) -> Optional[Dict]:
"""Load checkpoint data."""
try:
with open(checkpoint_path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logger.error(f"Failed to load checkpoint: {e}")
return None
def analyze_errors(results: List[Dict], pipeline_name: str):
"""Analyze and display detailed error analysis."""
fps = [r for r in results if r.get('classification') == 'fp']
fns = [r for r in results if r.get('classification') == 'fn']
tps = [r for r in results if r.get('classification') == 'tp']
console.print("\n")
console.print(Panel.fit(
f"[bold cyan]Analyse Détaillée des Résultats - {pipeline_name}[/bold cyan]",
border_style="cyan"
))
# True Positives (Matches correctly detected)
if tps:
console.print(f"\n[bold green]✅ TRUE POSITIVES ({len(tps)}) - MATCHES correctement détectés:[/bold green]")
tp_table = Table(box=box.ROUNDED, show_header=True)
tp_table.add_column("#", style="cyan", justify="right", width=4)
tp_table.add_column("Video 1", style="white", no_wrap=True, overflow="ellipsis", max_width=40)
tp_table.add_column("Video 2", style="white", no_wrap=True, overflow="ellipsis", max_width=40)
tp_table.add_column("Score", style="green", justify="right", width=10)
for i, r in enumerate(tps[:20], 1): # Limit to first 20
v1 = Path(r['video1']).name
v2 = Path(r['video2']).name
# Truncate long names manually with ellipsis in middle
if len(v1) > 38:
v1 = v1[:18] + "..." + v1[-17:]
if len(v2) > 38:
v2 = v2[:18] + "..." + v2[-17:]
tp_table.add_row(
str(i),
v1,
v2,
f"{r['score']:.1f}%"
)
if len(tps) > 20:
tp_table.add_row("...", f"... et {len(tps) - 20} autres", "", "")
console.print(tp_table)
# False Positives
if fps:
console.print(f"\n[bold yellow]⚠️ FALSE POSITIVES ({len(fps)}) - Fausses alertes (ne devraient PAS matcher):[/bold yellow]")
fp_table = Table(box=box.ROUNDED, show_header=True)
fp_table.add_column("#", style="cyan", justify="right", width=4)
fp_table.add_column("Video 1", style="white", no_wrap=True, overflow="ellipsis", max_width=35)
fp_table.add_column("Video 2", style="white", no_wrap=True, overflow="ellipsis", max_width=35)
fp_table.add_column("Score", style="yellow", justify="right", width=10)
fp_table.add_column("Raison", style="dim", no_wrap=True, max_width=30)
for i, r in enumerate(fps, 1):
v1 = Path(r['video1']).name
v2 = Path(r['video2']).name
# Truncate long names
if len(v1) > 33:
v1 = v1[:16] + "..." + v1[-14:]
if len(v2) > 33:
v2 = v2[:16] + "..." + v2[-14:]
# Analyze probable reason
metadata = r.get('metadata', {})
if 'votes' in metadata and metadata['votes'] < 5000:
reason = "Peu de votes"
elif r['score'] < 75:
reason = "Score proche seuil"
else:
reason = "Similitude partielle"
fp_table.add_row(
str(i),
v1,
v2,
f"{r['score']:.1f}%",
reason
)
console.print(fp_table)
# Suggestions for FP
console.print("\n[dim]💡 Suggestions pour réduire les FP:[/dim]")
avg_fp_score = sum(r['score'] for r in fps) / len(fps)
console.print(f" • Score moyen des FP: {avg_fp_score:.1f}%")
console.print(f" • Augmenter le seuil global à {avg_fp_score + 10:.0f}%")
console.print(f" • Activer la confirmation visuelle (pHash)")
console.print(f" • Utiliser un pipeline staged avec verification stricte")
# False Negatives
if fns:
console.print(f"\n[bold red]❌ FALSE NEGATIVES ({len(fns)}) - MATCHES ratés (devraient matcher):[/bold red]")
fn_table = Table(box=box.ROUNDED, show_header=True)
fn_table.add_column("#", style="cyan", justify="right", width=4)
fn_table.add_column("Video 1", style="white", no_wrap=True, overflow="ellipsis", max_width=35)
fn_table.add_column("Video 2", style="white", no_wrap=True, overflow="ellipsis", max_width=35)
fn_table.add_column("Score", style="red", justify="right", width=10)
fn_table.add_column("Raison", style="dim", no_wrap=True, max_width=30)
for i, r in enumerate(fns, 1):
v1 = Path(r['video1']).name
v2 = Path(r['video2']).name
# Truncate long names
if len(v1) > 33:
v1 = v1[:16] + "..." + v1[-14:]
if len(v2) > 33:
v2 = v2[:16] + "..." + v2[-14:]
# Analyze probable reason
metadata = r.get('metadata', {})
if 'votes' in metadata and metadata['votes'] < 1000:
reason = "Peu de votes"
elif r['score'] > 60:
reason = "Score proche seuil"
else:
reason = "Similitude faible"
fn_table.add_row(
str(i),
v1,
v2,
f"{r['score']:.1f}%",
reason
)
console.print(fn_table)
# Suggestions for FN
console.print("\n[dim]💡 Suggestions pour réduire les FN:[/dim]")
avg_fn_score = sum(r['score'] for r in fns) / len(fns)
console.print(f" • Score moyen des FN: {avg_fn_score:.1f}%")
console.print(f" • Baisser le seuil global à {avg_fn_score - 5:.0f}%")
console.print(f" • Ajouter des algorithmes complémentaires")
console.print(f" • Vérifier la qualité des vidéos (codec, résolution)")
def profile_performance(results: List[Dict], extraction_time: float, algorithm_names: List[str]):
"""Display performance profiling."""
console.print("\n")
console.print(Panel.fit(
"[bold cyan]Profil de Performance[/bold cyan]",
border_style="cyan"
))
# Extraction breakdown
console.print("\n[bold]Phase 1: Extraction[/bold]")
console.print(f" Temps total: {extraction_time:.1f}s")
# Comparison breakdown
total_comparison_time = sum(r.get('time_seconds', 0) for r in results)
avg_comparison_time = total_comparison_time / len(results) if results else 0
console.print(f"\n[bold]Phase 2: Comparaison[/bold]")
console.print(f" Temps total: {total_comparison_time:.1f}s")
console.print(f" Temps moyen: {avg_comparison_time:.2f}s/paire")
# Time distribution
if results:
times = [r.get('time_seconds', 0) for r in results]
times.sort()
p50 = times[len(times) // 2]
p95 = times[int(len(times) * 0.95)]
p99 = times[int(len(times) * 0.99)]
console.print(f"\n[bold]Distribution des temps:[/bold]")
console.print(f" P50: {p50:.2f}s")
console.print(f" P95: {p95:.2f}s")
console.print(f" P99: {p99:.2f}s")
console.print(f" Max: {max(times):.2f}s")
# Algorithm performance (if metadata available)
algo_stats = defaultdict(list)
for r in results:
metadata = r.get('metadata', {})
if 'algorithm_times' in metadata:
for algo, algo_time in metadata['algorithm_times'].items():
algo_stats[algo].append(algo_time)
if algo_stats:
console.print(f"\n[bold]Performance par algorithme:[/bold]")
for algo, times in algo_stats.items():
avg = sum(times) / len(times)
console.print(f" {algo}: {avg:.2f}s avg")
def export_to_benchmark_results(
testset_name: str,
pipeline_name: str,
results: List[Dict],
metrics: Dict,
total_time: float,
extraction_time: float,
comparison_time: float,
pipeline_config: Dict
) -> Path:
"""Export results to benchmark_results/ directory structure."""
# Create timestamped directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
pipeline_safe = pipeline_name.replace(' ', '_').replace('/', '_')
export_dir = RESULTS_DIR / f"{pipeline_safe}_{timestamp}"
export_dir.mkdir(parents=True, exist_ok=True)
# Calculate statistics
tp = metrics.get('tp', 0)
fp = metrics.get('fp', 0)
tn = metrics.get('tn', 0)
fn = metrics.get('fn', 0)
errors = metrics.get('errors', 0)
total = tp + fp + tn + fn
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
accuracy = (tp + tn) / total if total > 0 else 0.0
# Create JSON-safe pipeline config (remove non-serializable objects)
safe_pipeline_config = {
'mode': pipeline_config.get('mode', 'unknown'),
'global_threshold': pipeline_config.get('global_threshold', 70.0),
'algorithms': []
}
# Add algorithm names only (not full method objects)
if 'methods' in pipeline_config:
for method in pipeline_config['methods']:
if isinstance(method, dict):
safe_pipeline_config['algorithms'].append({
'name': method.get('name', 'unknown'),
'weight': method.get('weight', 1.0),
'enabled': method.get('enabled', True)
})
# Export JSON
json_data = {
'metadata': {
'timestamp': datetime.now().isoformat(),
'testset': testset_name,
'pipeline_name': pipeline_name,
'pipeline_mode': pipeline_config.get('mode', 'unknown'),
'threshold': pipeline_config.get('global_threshold', 70.0),
'total_pairs': len(results),
'total_time_seconds': round(total_time, 2),
'extraction_time_seconds': round(extraction_time, 2),
'comparison_time_seconds': round(comparison_time, 2),
'avg_time_seconds': round(comparison_time / len(results), 2) if results else 0
},
'pipeline_config': safe_pipeline_config,
'summary': {
'confusion_matrix': {
'tp': tp,
'fp': fp,
'tn': tn,
'fn': fn
},
'metrics': {
'precision': round(precision, 4),
'recall': round(recall, 4),
'f1_score': round(f1, 4),
'accuracy': round(accuracy, 4)
},
'counts': {
'total_positives': tp + fn,
'total_negatives': tn + fp,
'errors': errors
}
},
'results': results
}
json_path = export_dir / "results.json"
# Recursively sanitize the data using global json_encoder
safe_json_data = json_encoder(json_data)
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(safe_json_data, f, indent=2, ensure_ascii=False)
# Export summary text
summary_path = export_dir / "summary.txt"
with open(summary_path, 'w', encoding='utf-8') as f:
f.write(f"BENCHMARK SUMMARY\n")
f.write(f"=" * 70 + "\n\n")
f.write(f"Testset: {testset_name}\n")
f.write(f"Pipeline: {pipeline_name}\n")
f.write(f"Mode: {pipeline_config.get('mode', 'unknown')}\n")
f.write(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write(f"CONFUSION MATRIX:\n")
f.write(f" TP: {tp} FP: {fp} TN: {tn} FN: {fn}\n\n")
f.write(f"METRICS:\n")
f.write(f" Precision: {precision*100:.2f}%\n")
f.write(f" Recall: {recall*100:.2f}%\n")
f.write(f" F1-Score: {f1*100:.2f}%\n")
f.write(f" Accuracy: {accuracy*100:.2f}%\n\n")
f.write(f"TIMING:\n")
f.write(f" Extraction: {extraction_time:.1f}s\n")
f.write(f" Comparison: {comparison_time:.1f}s\n")
f.write(f" Total: {total_time:.1f}s\n")
f.write(f" Avg/pair: {comparison_time/len(results):.2f}s\n")
# Export failures CSV
fps = [r for r in results if r.get('classification') == 'fp']
fns = [r for r in results if r.get('classification') == 'fn']
if fps or fns:
failures_path = export_dir / "failures.csv"
with open(failures_path, 'w', encoding='utf-8') as f:
f.write("Type,Video1,Video2,Expected,Score,Metadata\n")
for r in fps:
f.write(f"FP,{r['video1']},{r['video2']},{r['expected']},{r['score']:.1f},\"{r.get('metadata', {})}\"\n")
for r in fns:
f.write(f"FN,{r['video1']},{r['video2']},{r['expected']},{r['score']:.1f},\"{r.get('metadata', {})}\"\n")
console.print(f"\n[green]✅ Résultats exportés vers:[/green] {export_dir}")
console.print(f" • [cyan]results.json[/cyan] - Données complètes")
console.print(f" • [cyan]summary.txt[/cyan] - Résumé textuel")
if fps or fns:
console.print(f" • [cyan]failures.csv[/cyan] - FP/FN pour analyse")
return export_dir
def run_single_benchmark(
testset_name: str,
pipeline_name: str,
limit: int = None,
force_recompute: bool = False,
resume_from: str = None,
analyze: bool = False,
profile: bool = False,
export_matrix: bool = False,
silent_progress: bool = False
) -> Dict[str, Any]:
"""
Run a single benchmark.
Args:
silent_progress: If True, disable live progress displays (for multi-pipeline mode)
Returns summary dict with metrics and results.
"""
# Initialize
db = VideoDatabase(ROOT_DB_PATH)
test_set_manager = TestSetManager(db)
pipeline_manager = PipelineManager(db)
storage = StorageManager()
# Check for resume
processed_results = []
resume_metrics = {'tp': 0, 'fp': 0, 'tn': 0, 'fn': 0, 'errors': 0}
resume_start_time = 0
if resume_from:
checkpoint_path = CHECKPOINT_DIR / resume_from
if checkpoint_path.exists():
checkpoint = load_checkpoint(checkpoint_path)
if checkpoint:
console.print(f"[yellow]📂 Reprise depuis checkpoint:[/yellow] {resume_from}")
console.print(f" Déjà traité: {checkpoint['processed_count']} paires")
processed_results = checkpoint['processed_pairs']
resume_metrics = checkpoint['metrics']
resume_start_time = checkpoint['elapsed_time']
# Get testset
console.print(f"\n[cyan]📋 Chargement du testset '{testset_name}'...[/cyan]")
all_testsets = test_set_manager.list_test_sets()
matched_testset = None
for ts in all_testsets:
if ts['name'].lower() == testset_name.lower():
matched_testset = ts['name']
break
if not matched_testset:
console.print(f"[red]❌ Testset '{testset_name}' non trouvé[/red]")
return None
pairs = test_set_manager.get_test_set(matched_testset)
# Apply resume filter
if resume_from and processed_results:
processed_ids = {r.get('pair_id') for r in processed_results}
pairs = [p for p in pairs if p.get('id') not in processed_ids]
if limit and limit < len(pairs):
pairs = pairs[:limit]
console.print(f"[green]✅ {len(pairs)} paires (limité à {limit})[/green]")
else:
console.print(f"[green]✅ {len(pairs)} paires chargées[/green]")
# Get pipeline
console.print(f"\n[cyan]🔧 Chargement du pipeline '{pipeline_name}'...[/cyan]")
all_pipelines = pipeline_manager.list_pipelines(include_defaults=True)
matched_pipeline = None
search_key = pipeline_name.lower().strip()
for p in all_pipelines:
normalized = p['name'].lower()
normalized = normalized.replace('🚀 ', '').replace('(duplicateflow)', '').strip()
if normalized == search_key or p['name'].lower() == search_key:
matched_pipeline = p
break
if not matched_pipeline:
console.print(f"[red]❌ Pipeline '{pipeline_name}' non trouvé[/red]")
return None
methods = matched_pipeline.get('methods', [])
global_threshold = matched_pipeline.get('global_threshold', 70.0) or 70.0
# Display pipeline info
panel_content = f"[bold]{matched_pipeline['name']}[/bold]\n"
panel_content += f"Seuil global: [cyan]{global_threshold:.1f}%[/cyan]\n"
panel_content += f"Algorithmes: {len(methods)}"
console.print(Panel(panel_content, title="Pipeline", border_style="blue"))
# Collect unique videos
unique_videos: Set[str] = set()
for pair in pairs:
unique_videos.add(pair['video1_path'])
unique_videos.add(pair['video2_path'])