-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnnotations.py
More file actions
2865 lines (2490 loc) · 124 KB
/
Annotations.py
File metadata and controls
2865 lines (2490 loc) · 124 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
# -*- coding: utf-8 -*-
import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
from tkinter import ttk
from PIL import Image, ImageTk, ImageOps
import json
import shutil
from datetime import datetime
import random
import math, time
from collections import defaultdict, Counter
import itertools
import statistics
from typing import Optional, List, Dict, Tuple
# Graphiques
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
# ------------------------
# Helpers globaux
# ------------------------
_TS_PATTERNS = [
re.compile(r'(\d{4})[-_]?(\d{2})[-_]?(\d{2})[T _\-]?(\d{2})[:\-]?(\d{2})[:\-]?(\d{2})'),
re.compile(r'ts[_-]?(\d{10})'),
re.compile(r'(\d{10})')
]
_IMG_EXTS = ('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff')
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', s)]
def gini_index(counts):
total = sum(counts)
if total <= 1:
return 0.0
sorted_counts = sorted(counts)
cum = 0
for i, x in enumerate(sorted_counts, 1):
cum += i * x
return (2*cum)/(total*(len(counts)+1)) - (len(counts)+1)/len(counts)
def entropy_from_counts(counts):
total = sum(counts)
if total == 0:
return 0.0
import math
ent = 0.0
for c in counts:
if c > 0:
p = c/total
ent -= p*math.log(p+1e-12)
return ent
def jain_index(counts):
if not counts:
return 1.0
s = sum(counts)
if s == 0: return 1.0
sq = sum(c*c for c in counts)
n = len(counts)
return (s*s) / (n * max(sq, 1e-12))
def theil_T(counts):
n = len(counts)
if n == 0:
return 0.0
mean = (sum(counts) / n) if sum(counts) > 0 else 0
if mean <= 0:
return 0.0
import math
t = 0.0
for x in counts:
if x > 0:
r = x / mean
t += r * math.log(r)
return t / n
def hhi(counts):
s = sum(counts)
if s == 0:
return 0.0
return sum((c/s)**2 for c in counts)
def simpson_diversity(counts):
return 1.0 - hhi(counts)
def _path_with_alt_ext(path: str) -> Optional[str]:
"""Si path n'existe pas, essaie les mêmes nom/chemin avec extensions d'images usuelles."""
if not path:
return None
root, ext = os.path.splitext(path)
# Essai tel quel
if os.path.exists(path):
return path
# Essai en normalisant l'extension s'il y en a une
if ext:
cand = root + ext.lower()
if os.path.exists(cand):
return cand
# Essai sur chaque extension image connue
for e in _IMG_EXTS:
cand = root + e
if os.path.exists(cand):
return cand
return None
# ------------------------
# Conteneur scrollable anti-boucle
# ------------------------
class SafeScrollableFrame(tk.Frame):
"""
Conteneur scrollable qui évite les boucles de <Configure> en dé-bounçant
la mise à jour du scrollregion avec after_idle.
"""
def __init__(self, master, orient="vertical", **kwargs):
super().__init__(master, **kwargs)
self.canvas = tk.Canvas(self, highlightthickness=0)
self.inner = tk.Frame(self.canvas)
self.window_id = self.canvas.create_window((0, 0), window=self.inner, anchor="nw")
self.vbar = None
if orient == "vertical":
self.vbar = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vbar.set)
self.vbar.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True)
self._pending = False
self.inner.bind("<Configure>", self._on_inner_configure)
self.canvas.bind("<Configure>", self._on_canvas_configure)
# molette
self.canvas.bind("<Enter>", lambda e: self.canvas.focus_set())
self.canvas.bind("<MouseWheel>", self._on_mousewheel)
self.canvas.bind("<Button-4>", self._on_mousewheel_linux)
self.canvas.bind("<Button-5>", self._on_mousewheel_linux)
def _on_inner_configure(self, _event=None):
if not self._pending:
self._pending = True
self.after_idle(self._update_scrollregion)
def _on_canvas_configure(self, event):
self.canvas.itemconfigure(self.window_id, width=event.width)
if not self._pending:
self._pending = True
self.after_idle(self._update_scrollregion)
def _update_scrollregion(self):
try:
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
finally:
self._pending = False
def _on_mousewheel(self, event):
if self.vbar:
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
def _on_mousewheel_linux(self, event):
if self.vbar:
if event.num == 4:
self.canvas.yview_scroll(-3, "units")
elif event.num == 5:
self.canvas.yview_scroll(3, "units")
# ------------------------
# Égalisation stricte + caps (Hamilton)
# ------------------------
def fair_quotas(sizes: dict, N: int, min_frac: float = 0.0, max_frac: float = 1.0) -> dict:
srcs = list(sizes.keys())
S = len(srcs)
if N <= 0 or S == 0:
return {s: 0 for s in srcs}
base = math.floor(N / S)
min_q = {s: min(sizes[s], math.floor(min_frac * N)) for s in srcs}
max_q = {s: min(sizes[s], math.floor(max_frac * N)) for s in srcs}
q = {s: min(max(base, min_q[s]), max_q[s]) for s in srcs}
for s in srcs:
q[s] = min(q[s], sizes[s])
total = sum(q.values())
def room(s):
return max(0, min(sizes[s], max_q[s]) - q[s])
while total < N:
candidates = [s for s in srcs if room(s) > 0]
if not candidates:
break
candidates.sort(key=lambda s: (room(s), sizes[s]), reverse=True)
for s in candidates:
if total >= N: break
q[s] += 1
total += 1
while total > N:
candidates = sorted(srcs, key=lambda s: (q[s], sizes[s]), reverse=True)
for s in candidates:
if total <= N: break
if q[s] > min_q[s]:
q[s] -= 1
total -= 1
return q
# ------------------------
# Égalité douce (Efraimidis–Spirakis)
# ------------------------
def efraimidis_spirakis_pick(by_src: dict, target: int, rng: random.Random) -> list:
if target <= 0:
return []
keys = []
for s, lst in by_src.items():
n = max(1, len(lst))
w = 1.0 / n
for a in lst:
u = rng.random()
k = u ** (1.0 / max(w, 1e-12))
keys.append((k, a))
if not keys:
return []
keys.sort(key=lambda t: t[0], reverse=True)
picked = [a for _, a in keys[:target]]
return picked
class ImageAnnotator:
def __init__(self, root):
self.root = root
self.root.title("Annotateur d'Images Météo")
self.root.geometry("1300x800")
self.root.resizable(True, True)
# 0) Langue de l'interface : À DÉFINIR ICI
self.ui_lang_var = tk.StringVar(value="EN") # interface EN par défaut
# Données principales
self.images: List[str] = []
self.annotations: Dict[str, Dict[str, dict]] = {}
self.filtered_annotations: Dict[str, Dict[str, dict]] = {}
self.annotation_file_path = ""
self.current_index = 0
self.image_folders = {}
self.annotated_image_paths: List[str] = []
# Racines (pour résoudre des chemins des JSON)
self.initial_images_root: Optional[str] = None # dossier choisi au lancement
self.annotations_images_root: Optional[str] = None # racine choisie si chemins du JSON sont relatifs/invalides
self.attributes = {
"Weather Type": ["Clear", "Sun and Clear", "Rain", "Snow", "Fog", "Fog and Rain", "Fog and Snow", "None"],
"Weather Intensity": ["Low", "Average", "High", "None"],
"Visibility": ["Very Low", "Low", "Average", "Good"],
"Sky Condition": ["Unknown", "Clear Sky", "Partly Cloudy", "Cloudy", "Overcast", "Partly Overcast"],
"Precipitation Presence": ["None", "Rain", "Snow", "Hail"],
"Precipitation Intensity": ["None", "Low", "Average", "High"],
"Ground Condition": ["Dry", "Wet", "Partly Wet", "Snowy", "Partly Snowy", "Wet and Snowy", "Unknown"],
"Glare or Reflections": ["Absent", "Present"],
"Light Conditions": ["Day", "Night", "Sunset", "Sunrise", "artificial"],
"Road Spray": ["Absent", "Present"],
"Water On Window": ["Absent", "Present", "None"],
"Snow On Window": ["Absent", "Present", "None"],
"Point of view": ["Road Vehicules", "Pedestrian", "Road Camera", "Other"]
}
self.default_values = {}
self.annotation_vars = {}
# 1) Valeurs par défaut
self.setup_defaults()
# 2) Charger les images (peut être annulé : on pourra n’utiliser que le JSON)
self.load_images(allow_cancel=True)
# 3) Notebook
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill="both", expand=True)
self.annotation_tab = ttk.Frame(self.notebook)
self.manager_tab = ttk.Frame(self.notebook)
self.stats_tab = ttk.Frame(self.notebook)
self.notebook.add(self.annotation_tab, text=self._ui("tab_annotation"))
self.notebook.add(self.manager_tab, text=self._ui("tab_manager"))
self.notebook.add(self.stats_tab, text=self._ui("tab_stats"))
# 4) UI avec conteneur scrollable de chaque onglet
self.create_annotation_tab_ui(self.annotation_tab)
self.create_manager_tab_ui(self.manager_tab)
self.create_stats_tab_ui(self.stats_tab)
# Anti-boucle / mémo de rendu
self._resize_job = None
self._rendering_image = False
self._last_render_size = (None, None)
self._last_image_path = None
# 7) Première image
self.update_interface()
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.root.bind('<Configure>', self.on_window_resize)
self.root.bind('<Left>', self.on_left_arrow)
self.root.bind('<Right>', self.on_right_arrow)
# 2) Sélecteur de langue UI en haut de fenêtre
self.setup_ui_language_switch()
# Langue de l'interface (EN par défaut)
# "EN" -> interface en anglais, "FR" -> interface en français
# ---------------------------------------------------------
# Résolution robuste des chemins d'image venant des annotations
# ---------------------------------------------------------
def _resolve_image_path(self, folder: str, image_name: str, ann: dict) -> Optional[str]:
"""
Ordre d'essais :
1) ann['image_path'] s'il existe (ou avec extension alternative)
2) chemin relatif à self.annotations_images_root (si définie) : root/folder/image_name
3) chemin relatif à self.initial_images_root (si définie)
4) si 'image_path' est relatif et que annotations_images_root est définie, join(root, image_path)
5) si 'image_path' est relatif et initial_images_root est définie, join(initial_root, image_path)
"""
# 1) Champs 'image_path' direct
p = ann.get('image_path') or ''
if p:
cand = _path_with_alt_ext(p if os.path.isabs(p) else os.path.abspath(p))
if cand:
return cand
# 2) Racine d'images choisie POUR le JSON (si cochée)
if self.annotations_images_root:
cand2 = _path_with_alt_ext(os.path.join(self.annotations_images_root, folder, image_name))
if cand2:
return cand2
if p and not os.path.isabs(p):
cand2 = _path_with_alt_ext(os.path.join(self.annotations_images_root, p))
if cand2:
return cand2
# 3) Racine d'images INITIALE (si l’utilisateur a sélectionné un dossier au démarrage)
if self.initial_images_root:
cand2 = _path_with_alt_ext(os.path.join(self.initial_images_root, folder, image_name))
if cand2:
return cand2
# 5) Dernière chance : si p est un chemin relatif et initial_images_root est connue
if p and not os.path.isabs(p) and self.initial_images_root:
cand2 = _path_with_alt_ext(os.path.join(self.initial_images_root, p))
if cand2:
return cand2
return None
# ---------------------------------------------------------
# 1) Configuration par défaut
# ---------------------------------------------------------
def setup_defaults(self):
setup_window = tk.Toplevel(self.root)
setup_window.title("Définir les Valeurs par Défaut")
setup_window.grab_set()
tk.Label(setup_window, text="Sélectionnez les valeurs par défaut :", font=("Arial", 10)).pack(pady=10)
self.setup_vars = {}
for attribute, options in self.attributes.items():
frame = tk.LabelFrame(setup_window, text=attribute)
frame.pack(fill="x", padx=10, pady=5)
var = tk.StringVar(value=options[0])
self.setup_vars[attribute] = var
num_columns = 2
options_frame = tk.Frame(frame)
options_frame.pack()
for idx, option in enumerate(options):
tk.Radiobutton(options_frame, text=option, variable=var, value=option)\
.grid(row=idx // num_columns, column=idx % num_columns, sticky='w', padx=5, pady=2)
btn_frame = tk.Frame(setup_window)
btn_frame.pack(pady=10)
tk.Button(btn_frame, text="Confirmer", command=lambda: self.confirm_defaults(setup_window)).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Annuler", command=setup_window.destroy).pack(side=tk.LEFT, padx=5)
self.root.wait_window(setup_window)
def confirm_defaults(self, setup_window):
for attribute, var in self.setup_vars.items():
self.default_values[attribute] = var.get()
setup_window.destroy()
# ---------------------------------------------------------
# 2) Chargement des images (dossier)
# ---------------------------------------------------------
def load_images(self, allow_cancel=False):
directory = filedialog.askdirectory(title="Sélectionnez le répertoire des images (Annuler si vous utiliserez un JSON)")
if not directory:
if allow_cancel:
self.initial_images_root = None
return
messagebox.showerror("Erreur", "Aucun répertoire sélectionné.")
self.root.destroy()
return
self.initial_images_root = directory
image_paths = []
for root_dir, _, files in os.walk(directory):
for file in files:
if file.lower().endswith(_IMG_EXTS):
image_paths.append(os.path.join(root_dir, file))
image_paths.sort(key=lambda x: natural_sort_key(os.path.basename(x)))
self.images.extend(image_paths)
for img_path in image_paths:
folder = os.path.basename(os.path.dirname(img_path))
img_name = os.path.basename(img_path)
self.image_folders.setdefault(folder, []).append(img_name)
if not self.images and not allow_cancel:
messagebox.showwarning("Avertissement", "Aucune image trouvée dans ce répertoire.")
self.root.destroy()
# ---------------------------------------------------------
# Parcours / Annotées
# ---------------------------------------------------------
def toggle_browse_mode(self):
is_browse = self.browse_mode_var.get()
self._apply_browse_mode_state(is_browse)
self.update_interface(load_saved_annotations=True)
def toggle_only_annotated_mode(self):
if self.only_annotated_var.get():
if not self.annotations:
messagebox.showwarning("Attention", "Aucun fichier d'annotations chargé. Charge-le d'abord.")
self.only_annotated_var.set(False)
return
self._rebuild_annotated_image_list()
if not self.annotated_image_paths:
messagebox.showwarning("Attention", "Aucune image valide trouvée dans le fichier d'annotations (chemins introuvables).")
self.only_annotated_var.set(False)
return
self.current_index = 0
self.update_interface(load_saved_annotations=True)
def _rebuild_annotated_image_list(self):
"""Reconstruit la liste d'images à partir du JSON en résolvant les chemins."""
paths = []
missing = 0
for folder in sorted(self.annotations.keys()):
imgs = self.annotations[folder]
for image_name, ann in sorted(imgs.items(), key=lambda kv: natural_sort_key(kv[0])):
p = self._resolve_image_path(folder, image_name, ann)
if p and os.path.exists(p):
paths.append(p)
else:
missing += 1
self.annotated_image_paths = paths
# Si beaucoup d'images manquantes, proposer une racine
if missing > 0 and (not self.annotations_images_root):
if messagebox.askyesno("Chemins manquants",
f"{missing} image(s) d'annotations introuvable(s).\n"
f"Voulez-vous choisir une racine d'images pour résoudre les chemins ?"):
root = filedialog.askdirectory(title="Choisissez la racine d'images correspondant au JSON")
if root:
self.annotations_images_root = root
# Re-essayer avec la nouvelle racine
return self._rebuild_annotated_image_list()
def _get_active_images(self):
if getattr(self, 'only_annotated_var', None) and self.only_annotated_var.get():
return self.annotated_image_paths
return self.images
def _apply_browse_mode_state(self, is_browse: bool):
if is_browse:
self.set_state_recursive(self.annotation_frame, 'disabled')
if 'state' in self.change_save_path_btn.configure():
self.change_save_path_btn.configure(state='disabled')
if 'state' in self.change_defaults_btn.configure():
self.change_defaults_btn.configure(state='disabled')
self.prev_button.configure(state='normal')
self.next_button.configure(state='normal')
else:
self.set_state_recursive(self.annotation_frame, 'normal')
if 'state' in self.change_save_path_btn.configure():
self.change_save_path_btn.configure(state='normal')
if 'state' in self.change_defaults_btn.configure():
self.change_defaults_btn.configure(state='normal')
# ---------------------------------------------------------
# 3) Interface onglet Annotation (scroll global)
# ---------------------------------------------------------
def create_annotation_tab_ui(self, parent):
# conteneur scrollable de l’onglet
tab_scroll = SafeScrollableFrame(parent, orient="vertical")
tab_scroll.pack(fill="both", expand=True)
tab = tab_scroll.inner
main_frame = tk.Frame(tab)
main_frame.pack(fill="both", expand=True)
main_frame.grid_rowconfigure(1, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
main_frame.grid_columnconfigure(1, weight=1)
# Top actions
top_frame = tk.Frame(main_frame)
top_frame.grid(row=0, column=0, columnspan=2, pady=5)
self.btn_load_annotations = tk.Button(
top_frame,
text=self._ui("btn_load_ann"),
command=self.load_annotations
)
self.btn_load_annotations.pack(side=tk.LEFT, padx=5)
self.btn_create_annotations = tk.Button(
top_frame,
text=self._ui("btn_create_ann"),
command=self.create_new_annotations
)
self.btn_create_annotations.pack(side=tk.LEFT, padx=5)
self.load_more_btn = tk.Button(
top_frame,
text=self._ui("btn_load_more"),
command=self.load_additional_images
)
self.load_more_btn.pack(side=tk.LEFT, padx=5)
self.btn_open_manager = tk.Button(
top_frame,
text=self._ui("btn_manage_ann"),
command=self.open_annotation_manager
)
self.btn_open_manager.pack(side=tk.LEFT, padx=5)
self.btn_use_json_images = tk.Button(
top_frame,
text=self._ui("btn_use_json_images"),
command=self.use_images_from_annotations
)
self.btn_use_json_images.pack(side=tk.LEFT, padx=5)
# Content split
content_frame = tk.Frame(main_frame)
content_frame.grid(row=1, column=0, columnspan=2, sticky="nsew")
content_frame.grid_rowconfigure(0, weight=1)
content_frame.grid_columnconfigure(0, weight=1)
# Image area
image_frame = tk.Frame(content_frame)
image_frame.grid(row=0, column=0, sticky="nsew")
self.image_label = tk.Label(image_frame, bg="#101014")
self.image_label.pack(fill="both", expand=True)
self.remaining_label = tk.Label(image_frame, text="")
self.remaining_label.pack()
# Annotation area (scrollable, SAFE)
annotation_container = tk.Frame(content_frame)
annotation_container.grid(row=0, column=1, sticky="ns")
scrollable = SafeScrollableFrame(annotation_container, orient="vertical")
scrollable.pack(fill="both", expand=True)
self.annotation_frame = scrollable.inner
# Radios
self.annotation_vars.clear()
for attribute, options in self.attributes.items():
frame = tk.LabelFrame(self.annotation_frame, text=attribute)
frame.pack(fill="x", padx=10, pady=5)
var = tk.StringVar(value=self.default_values.get(attribute, options[0]))
self.annotation_vars[attribute] = var
for option in options:
tk.Radiobutton(frame, text=option, variable=var, value=option).pack(anchor='w', padx=5, pady=2)
# Bottom bar
bottom_frame = tk.Frame(main_frame)
bottom_frame.grid(row=2, column=0, columnspan=2, pady=5)
self.buttons_frame = tk.Frame(bottom_frame)
self.buttons_frame.pack()
self.prev_button = tk.Button(self.buttons_frame, text=self._ui("btn_prev"), command=self.prev_image)
self.prev_button.pack(side=tk.LEFT, padx=5)
self.next_button = tk.Button(self.buttons_frame, text=self._ui("btn_next"), command=self.next_image)
self.next_button.pack(side=tk.LEFT, padx=5)
# Cases à cocher
mode_frame = tk.Frame(bottom_frame)
mode_frame.pack(pady=2)
self.browse_mode_var = tk.BooleanVar(value=False)
self.browse_checkbutton = tk.Checkbutton(
mode_frame,
text=self._ui("chk_browse"),
variable=self.browse_mode_var,
command=self.toggle_browse_mode
)
self.browse_checkbutton.grid(row=0, column=0, padx=6, sticky="w")
self.only_annotated_var = tk.BooleanVar(value=False)
self.only_annotated_checkbutton = tk.Checkbutton(
mode_frame,
text=self._ui("chk_only_annotated"),
variable=self.only_annotated_var,
command=self.toggle_only_annotated_mode
)
self.only_annotated_checkbutton.grid(row=0, column=1, padx=6, sticky="w")
self.change_defaults_btn = tk.Button(
bottom_frame,
text=self._ui("btn_change_defaults"),
command=self.setup_defaults
)
self.change_defaults_btn.pack(pady=5)
self.change_save_path_btn = tk.Button(
bottom_frame,
text=self._ui("btn_change_save"),
command=self.change_save_path
)
self.change_save_path_btn.pack(pady=5)
self.save_path_label = tk.Label(bottom_frame, text=self._ui("label_save_path_none"))
self.save_path_label.pack()
# Etat initial
self.disable_annotation_widgets()
self.enable_annotation_widgets()
# Enable/Disable
def set_state_recursive(self, widget, state):
if isinstance(widget, (tk.Canvas,)):
return
try:
widget.configure(state=state)
except Exception:
pass
for child in widget.winfo_children():
self.set_state_recursive(child, state)
def disable_annotation_widgets(self):
self.set_state_recursive(self.annotation_frame, 'disabled')
self.set_state_recursive(self.buttons_frame, 'disabled')
if 'state' in self.change_save_path_btn.configure():
self.change_save_path_btn.configure(state='disabled')
if 'state' in self.load_more_btn.configure():
self.load_more_btn.configure(state='disabled')
if 'state' in self.change_defaults_btn.configure():
self.change_defaults_btn.configure(state='disabled')
def enable_annotation_widgets(self):
self.set_state_recursive(self.annotation_frame, 'normal')
self.set_state_recursive(self.buttons_frame, 'normal')
if 'state' in self.change_save_path_btn.configure():
self.change_save_path_btn.configure(state='normal')
if 'state' in self.load_more_btn.configure():
self.load_more_btn.configure(state='normal')
if 'state' in self.change_defaults_btn.configure():
self.change_defaults_btn.configure(state='normal')
# ---------------------------------------------------------
# Bouton : utiliser les images résolues depuis le JSON
# ---------------------------------------------------------
def use_images_from_annotations(self):
if not self.annotations:
messagebox.showwarning("Info", "Charge d'abord un fichier d'annotations.")
return
self._rebuild_annotated_image_list()
if not self.annotated_image_paths:
messagebox.showwarning("Info", "Aucune image résolue depuis le JSON.")
return
# Remplace la liste d'images active par celles du JSON résolu
self.images = list(self.annotated_image_paths)
self.current_index = 0
messagebox.showinfo("Succès", f"{len(self.images)} images chargées depuis le JSON (chemins résolus).")
self.update_interface(load_saved_annotations=True)
# ---------------------------------------------------------
# Diagnostic faisabilité split
# ---------------------------------------------------------
def diagnose_split_feasibility(self):
if not self.annotations:
messagebox.showerror("Erreur", "Aucune annotation chargée.")
return
anns = [ann for imgs in (self.filtered_annotations or self.annotations).values() for ann in imgs.values()]
if not anns:
messagebox.showerror("Erreur", "Aucune annotation disponible.")
return
strat_task = self.stratify_task_var.get()
if strat_task == "(aucune)":
strat_task = None
by_src = self._group_by_source(anns)
prepared = {}
for s, v in by_src.items():
prepared[s] = self._ensure_diversity_per_source(
v,
gap_mode=self.gap_mode_var.get(),
min_gap_s=float(self.min_time_gap_var.get()),
min_gap_frames=int(self.min_frame_gap_var.get())
)
total_after = sum(len(v) for v in prepared.values())
n_sources = len(prepared)
max_pct = max(5.0, min(100.0, float(self.max_pct_per_source_var.get()))) / 100.0
min_pct = max(0.0, min(100.0, float(self.min_pct_per_source_var.get()))) / 100.0
per_source_counts = sorted((len(v) for v in prepared.values()), reverse=True)
mean_per_source = (sum(per_source_counts) / n_sources) if n_sources else 0
gap_desc = f"mode={self.gap_mode_var.get()} | min_gap={self.min_time_gap_var.get():.2f}s / {int(self.min_frame_gap_var.get())} frames"
lines = [
f"Images après préparation: {total_after}",
f"Nombre de sources: {n_sources}",
f"Moyenne images/source: {mean_per_source:.1f}",
f"Bornes par source: min={int(min_pct*100)}% max={int(max_pct*100)}%",
f"Préparation: thinning + interleave quantiles ({gap_desc})",
f"Soft sampling (Efraimidis–Spirakis): {'ON' if self.soft_equal_sampling_var.get() else 'OFF'}"
]
if strat_task:
class_per_source = defaultdict(Counter)
for s, lst in prepared.items():
for a in lst:
class_per_source[s][a.get(strat_task, "__none__")] += 1
class_tot = Counter()
for s, c in class_per_source.items():
class_tot.update(c)
lines.append(f"Tâche de stratification: {strat_task}")
for cls, cnt in class_tot.items():
src_with_cls = sum(1 for s in class_per_source if class_per_source[s][cls] > 0)
lines.append(f" - {cls}: {cnt} images, présentes dans {src_with_cls} sources")
messagebox.showinfo("Diagnostic de faisabilité", "\n".join(lines))
# ---------------------------------------------------------
# 4) Interface onglet Gestion (scroll global)
# ---------------------------------------------------------
def create_manager_tab_ui(self, parent):
tab_scroll = SafeScrollableFrame(parent, orient="vertical")
tab_scroll.pack(fill="both", expand=True)
main_frame = tk.Frame(tab_scroll.inner)
main_frame.pack(fill="both", expand=True, padx=10, pady=10)
# Ligne d'actions
top_frame = tk.Frame(main_frame)
top_frame.pack(fill="x", pady=5)
tk.Button(top_frame, text="Charger annotations", command=self.load_annotations_manager).pack(side=tk.LEFT, padx=5)
tk.Button(top_frame, text="Filtrer", command=self.filter_annotations).pack(side=tk.LEFT, padx=5)
tk.Button(top_frame, text="Exporter JSON", command=self.export_filtered_annotations).pack(side=tk.LEFT, padx=5)
tk.Button(top_frame, text="Générer JSON avec N images", command=self.generate_selected_json).pack(side=tk.LEFT, padx=5)
tk.Button(top_frame, text="Split Train/Test", command=self.split_train_test).pack(side=tk.LEFT, padx=5)
tk.Button(top_frame, text="Copier les images annotées", command=self.copy_annotated_images).pack(side=tk.LEFT, padx=5)
# Filtres par attribut
filter_frame = tk.LabelFrame(main_frame, text="Filtres")
filter_frame.pack(fill="x", padx=5, pady=5)
self.filter_vars = {}
row_idx = 0
for attribute, options in self.attributes.items():
tk.Label(filter_frame, text=attribute).grid(row=row_idx, column=0, padx=5, pady=2, sticky='w')
var = tk.StringVar(value="Tous")
self.filter_vars[attribute] = var
tk.OptionMenu(filter_frame, var, "Tous", *options).grid(row=row_idx, column=1, padx=5, pady=2, sticky='w')
row_idx += 1
list_image_frame = tk.Frame(main_frame)
list_image_frame.pack(fill="both", expand=True, padx=5, pady=5)
list_image_frame.grid_columnconfigure(0, weight=0)
list_image_frame.grid_columnconfigure(1, weight=1)
list_image_frame.grid_rowconfigure(0, weight=1)
# --- Liste (col 0) ---
list_frame = tk.Frame(list_image_frame)
list_frame.grid(row=0, column=0, sticky="ns")
self.annotations_listbox = tk.Listbox(list_frame, selectmode=tk.SINGLE, width=50)
self.annotations_listbox.pack(side=tk.LEFT, fill="both", expand=True)
scrollbar = tk.Scrollbar(list_frame, orient="vertical", command=self.annotations_listbox.yview)
scrollbar.pack(side=tk.RIGHT, fill="y")
self.annotations_listbox.config(yscrollcommand=scrollbar.set)
self.annotations_listbox.bind("<<ListboxSelect>>", self.on_annotation_select)
# --- Aperçu (col 1) ---
image_frame = tk.Frame(list_image_frame)
image_frame.grid(row=0, column=1, sticky="nsew", padx=10)
self.manager_image_label = tk.Label(image_frame, bg="#101014")
self.manager_image_label.pack(fill="both", expand=True)
self.filtered_count_label = tk.Label(main_frame, text="Nombre d'images filtrées: 0")
self.filtered_count_label.pack(pady=5)
# Options de split / hétérogénéité
options_frame = tk.LabelFrame(main_frame, text="Options de split / hétérogénéité")
options_frame.pack(fill="x", padx=5, pady=5)
self.split_by_source_var = tk.BooleanVar(value=True)
tk.Checkbutton(options_frame, text="Split par source vidéo (dossier)", variable=self.split_by_source_var)\
.grid(row=0, column=0, sticky="w", padx=5, pady=2)
self.timestamp_diverse_var = tk.BooleanVar(value=True)
tk.Checkbutton(options_frame, text="Diversifier dans chaque set (espacer les prises)",
variable=self.timestamp_diverse_var).grid(row=0, column=1, sticky="w", padx=5, pady=2)
# --- Mode d'écart (secondes vs images) ---
self.gap_mode_var = tk.StringVar(value="seconds") # "seconds" | "frames"
tk.Label(options_frame, text="Mode d'écart:").grid(row=0, column=2, sticky="e", padx=5)
tk.Radiobutton(options_frame, text="Secondes", variable=self.gap_mode_var, value="seconds")\
.grid(row=0, column=3, sticky="w", padx=2)
tk.Radiobutton(options_frame, text="Images", variable=self.gap_mode_var, value="frames")\
.grid(row=0, column=4, sticky="w", padx=2)
# Valeurs minimales selon le mode
tk.Label(options_frame, text="Min écart (s):").grid(row=0, column=5, sticky="e", padx=5)
self.min_time_gap_var = tk.DoubleVar(value=2.0)
entry_time = tk.Entry(options_frame, width=6, textvariable=self.min_time_gap_var)
entry_time.grid(row=0, column=6, sticky="w", padx=5)
tk.Label(options_frame, text="Min écart (images):").grid(row=0, column=7, sticky="e", padx=5)
self.min_frame_gap_var = tk.IntVar(value=5)
entry_frames = tk.Entry(options_frame, width=6, textvariable=self.min_frame_gap_var)
entry_frames.grid(row=0, column=8, sticky="w", padx=5)
def _refresh_gap_inputs(*_):
is_sec = (self.gap_mode_var.get() == "seconds")
entry_time.configure(state=("normal" if is_sec else "disabled"))
entry_frames.configure(state=("disabled" if is_sec else "normal"))
self.gap_mode_var.trace_add("write", _refresh_gap_inputs)
_refresh_gap_inputs()
# --- Caps min/max par source ---
tk.Label(options_frame, text="Min %/source:").grid(row=0, column=9, sticky="e", padx=5)
self.min_pct_per_source_var = tk.DoubleVar(value=0.0)
tk.Entry(options_frame, width=6, textvariable=self.min_pct_per_source_var)\
.grid(row=0, column=10, sticky="w", padx=5)
tk.Label(options_frame, text="Max %/source:").grid(row=0, column=11, sticky="e", padx=5)
self.max_pct_per_source_var = tk.DoubleVar(value=40.0)
tk.Entry(options_frame, width=6, textvariable=self.max_pct_per_source_var)\
.grid(row=0, column=12, sticky="w", padx=5)
# --- Soft sampling (Efraimidis–Spirakis) ---
self.soft_equal_sampling_var = tk.BooleanVar(value=False)
tk.Checkbutton(options_frame,
text="Soft sampling (Efraimidis–Spirakis) — égalité douce entre sources",
variable=self.soft_equal_sampling_var)\
.grid(row=1, column=0, columnspan=6, sticky="w", padx=5, pady=2)
tk.Label(options_frame, text="Tâche de stratification:").grid(row=2, column=0, sticky="e", padx=5, pady=2)
choices = ["(aucune)"] + list(self.attributes.keys())
self.stratify_task_var = tk.StringVar(value="(aucune)")
tk.OptionMenu(options_frame, self.stratify_task_var, *choices)\
.grid(row=2, column=1, sticky="w", padx=5, pady=2)
# --- Modes EXACTS (exclusifs) + entrées N train / N test ---
self.exact_mode_var = tk.BooleanVar(value=False) # disjoint
self.exact_shared_mode_var = tk.BooleanVar(value=False) # sources partagées
def _toggle_exact_entries():
any_exact = self.exact_mode_var.get() or self.exact_shared_mode_var.get()
self.train_exact_entry.configure(state=("normal" if any_exact else "disabled"))
self.test_exact_entry.configure(state=("normal" if any_exact else "disabled"))
self.timestamp_diverse_var.set(False)
def _on_toggle_disjoint():
if self.exact_mode_var.get():
self.exact_shared_mode_var.set(False)
_toggle_exact_entries()
def _on_toggle_shared():
if self.exact_shared_mode_var.get():
self.exact_mode_var.set(False)
_toggle_exact_entries()
tk.Checkbutton(
options_frame,
text="Mode exact (N train & N test, sources disjointes, quotas Hamilton + min/max, tirage intra-source)",
variable=self.exact_mode_var,
command=_on_toggle_disjoint
).grid(row=3, column=0, columnspan=12, sticky="w", padx=5, pady=4)
tk.Checkbutton(
options_frame,
text="Mode exact (sources partagées, mêmes distributions, quotas Hamilton combinés, sans répétition d'images)",
variable=self.exact_shared_mode_var,
command=_on_toggle_shared
).grid(row=4, column=0, columnspan=12, sticky="w", padx=5, pady=2)
tk.Label(options_frame, text="N train:").grid(row=5, column=0, sticky="e", padx=5)
self.train_exact_n_var = tk.IntVar(value=0)
self.train_exact_entry = tk.Entry(options_frame, width=8, textvariable=self.train_exact_n_var, state="disabled")
self.train_exact_entry.grid(row=5, column=1, sticky="w", padx=5)
tk.Label(options_frame, text="N test:").grid(row=5, column=2, sticky="e", padx=5)
self.test_exact_n_var = tk.IntVar(value=0)
self.test_exact_entry = tk.Entry(options_frame, width=8, textvariable=self.test_exact_n_var, state="disabled")
self.test_exact_entry.grid(row=5, column=3, sticky="w", padx=5)
tk.Button(options_frame, text="Diagnostiquer faisabilité", command=self.diagnose_split_feasibility)\
.grid(row=2, column=2, columnspan=2, sticky="w", padx=5)
self.manager_displayed_image = None
# ----------------- Helpers sources/timestamps/frames -----------------
def _extract_source(self, ann):
return ann.get('folder', 'unknown')
def _get_timestamp_s(self, ann):
"""
Extrait un timestamp en SECONDES (float) de façon robuste :
1) séquence compacte YYYYMMDDhhmmss[sss|uuuuuu|nnnnnnnnn] dans image_name
2) patterns existants (_TS_PATTERNS) dans image_name
3) mtime du fichier image_path (si disponible)
Renvoie 0.0 en dernier recours.
"""
import os, re, datetime
name = ann.get('image_name', '') or ''
# (1) Compact : 20250620142150[188075]...
m = max(re.findall(r'(\d{14,})', name), key=len, default=None)
if m:
digits = m
try:
y = int(digits[0:4])
mo = int(digits[4:6])
d = int(digits[6:8])
h = int(digits[8:10])
mi = int(digits[10:12])
sec = int(digits[12:14])
sub = digits[14:] # sous-secondes optionnelles
micro = 0
if sub:
if len(sub) >= 9:
micro = int(round(int(sub[:9]) / 1000.0)) # ns -> µs
elif len(sub) >= 6:
micro = int(sub[:6]) # µs
elif len(sub) >= 3:
micro = int(sub[:3]) * 1000 # ms -> µs
else:
micro = int(sub) * (10 ** (6 - len(sub))) # 1–2 chiffres
dt = datetime.datetime(y, mo, d, h, mi, sec, micro,
tzinfo=datetime.timezone.utc)
return dt.timestamp()
except Exception:
pass # on tente (2)
# (2) Tes patterns existants
for pat in _TS_PATTERNS:
m = pat.search(name)
if m:
try:
if len(m.groups()) == 6:
y, mo, d, h, mi, s = map(int, m.groups())
dt = datetime.datetime(y, mo, d, h, mi, s,
tzinfo=datetime.timezone.utc)
return dt.timestamp()
else:
return float(m.group(1))
except Exception:
pass
# (3) mtime du fichier
p = ann.get('image_path', '')
try:
if p and os.path.exists(p):
return os.path.getmtime(p)
except Exception:
pass
return 0.0
def _group_by_source(self, anns):
g = defaultdict(list)
for a in anns:
g[self._extract_source(a)].append(a)
return g
def _extract_frame_index(self, ann) -> Optional[int]:
name = (ann.get('image_name', '') or '')
m = re.search(r'(?i)(?:^|[_-])(?:frame|img|image|shot|f)[_-]?(\d{1,9})(?:\D|$)', name)
if m:
try:
return int(m.group(1))
except Exception:
pass