-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgradio_app.py
More file actions
1561 lines (1390 loc) · 59 KB
/
Copy pathgradio_app.py
File metadata and controls
1561 lines (1390 loc) · 59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import inspect
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import datetime
import cv2
import gradio as gr
import numpy as np
# Reuse core discovery + layout/crop logic from the CLI implementation.
import compare
@dataclass
class _Session:
comparator: compare.InteractiveCropComparator
source: str
root: str
group: str
dataset: str
pair: str
structure: str
effective_structure: str
reference_key: str
pending_point: Optional[Tuple[int, int]] = None
def _parse_bg_color(layout_bg_color: str) -> tuple:
# Return RGBA tuple or a transparent-like default.
try:
if isinstance(layout_bg_color, str) and layout_bg_color.strip().lower() != "transparent":
parts = [int(x) for x in layout_bg_color.replace(' ', '').split(',') if x != '']
print(parts)
if len(parts) not in (3, 4):
raise ValueError
return tuple(max(0, min(255, v)) for v in parts)
except Exception:
pass
return (0, 0, 0, 0)
def _bgr_to_rgb(img: Optional[np.ndarray]) -> Optional[np.ndarray]:
if img is None:
return None
if img.ndim == 2:
return cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
if img.shape[2] == 4:
return cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
def _next_available_roi_id(rois: Dict[int, Dict[str, Any]]) -> int:
used = {int(k) for k in (rois or {}).keys() if isinstance(k, int) or str(k).isdigit()}
n = 1
while n in used:
n += 1
return n
def _draw_rois_on_bgr(
img_bgr: np.ndarray,
rois: Dict[int, Dict[str, Any]],
thickness: int = 2,
active_roi: Optional[int] = None,
cmp_: Optional[compare.InteractiveCropComparator] = None,
) -> np.ndarray:
out = img_bgr.copy()
for rid in sorted(rois.keys()):
rect = rois[rid].get("rect")
if rect is None:
continue
x1, y1, x2, y2 = rect
x1, x2 = (x1, x2) if x1 <= x2 else (x2, x1)
y1, y2 = (y1, y2) if y1 <= y2 else (y2, y1)
color = tuple(int(c) for c in rois[rid].get("color", (0, 0, 255)))
# Prefer reusing compare.py drawing helpers when available.
if cmp_ is not None and hasattr(cmp_, "draw_dashed_rect") and getattr(cmp_, "mode", "selection") == "selection" and active_roi == rid:
try:
cmp_.draw_dashed_rect(out, (x1, y1), (x2, y2), color, thickness=max(1, int(thickness)))
except Exception:
cv2.rectangle(out, (x1, y1), (x2, y2), color, max(1, int(thickness)))
else:
cv2.rectangle(out, (x1, y1), (x2, y2), color, max(1, int(thickness)))
# Match compare.py label positions:
# - active ROI: circled label near (x1+20, max(20, y1-20))
# - inactive ROI: text near (x1+3, max(0, y1-5))
if active_roi is not None and rid == active_roi:
cx = int(x1 + 20)
cy = int(max(20, y1 - 20))
if cmp_ is not None and hasattr(cmp_, "draw_circled_label"):
try:
cmp_.draw_circled_label(out, (cx, cy), rid, color)
except Exception:
pass
else:
radius = 12
cv2.circle(out, (cx, cy), radius, color, thickness=max(1, int(thickness)))
cv2.circle(out, (cx, cy), radius - 2, (0, 0, 0), thickness=-1)
text = str(rid)
(tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
cv2.putText(
out,
text,
(cx - tw // 2, cy + th // 2),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
color,
2,
)
else:
cv2.putText(out, f"{rid}", (x1 + 3, max(0, y1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
return out
def _list_methods_from_root(root: str) -> List[str]:
if not root or not os.path.isdir(root):
return []
names = []
for d in os.listdir(root):
p = os.path.join(root, d)
if os.path.isdir(p) and not d.startswith('.'):
names.append(d)
return sorted(names)
def _load_methods_from_file(path: str = "./methods.txt") -> List[str]:
if not os.path.exists(path):
return []
with open(path, "r", encoding="utf-8") as f:
return [line.strip() for line in f.read().splitlines() if line.strip()]
def _parse_exclude_methods(raw: str) -> set:
"""Parse comma/space separated method names to exclude."""
if not raw:
return set()
return {p.strip() for p in str(raw).replace(',', ' ').split() if p.strip()}
def _apply_exclude(methods: List[str], exclude_set: set) -> Tuple[List[str], List[str]]:
"""Filter methods by exclusion set. Returns (kept_methods, removed_methods)."""
if not exclude_set:
return methods, []
removed = [m for m in methods if m in exclude_set]
kept = [m for m in methods if m not in exclude_set]
return kept, removed
def _build_input_folder(
source: str,
root: str,
group: str,
dataset: str,
pair: str,
structure: str,
exclude: str = "",
) -> Dict[str, Any]:
methods = _load_methods_from_file("./methods.txt")
exclude_set = _parse_exclude_methods(exclude)
if source == "external":
if not methods:
raise ValueError("methods.txt is required for external source")
methods, removed = _apply_exclude(methods, exclude_set)
if not methods:
raise ValueError("No methods left after applying exclude filter")
input_folder = {m: f"/data/user/results/{m}/{dataset}/pred/{pair}" for m in methods}
return input_folder
if not methods:
methods = _list_methods_from_root(root)
methods, removed = _apply_exclude(methods, exclude_set)
if not methods:
raise ValueError("No methods left after applying exclude filter")
input_folder = compare.discover_local_inputs(root, methods, group=group, dataset=dataset, pair=pair, structure=structure)
if not input_folder:
raise ValueError(
"No valid method inputs found. Checked layouts: "
"<method>/<group>/<dataset>[/<pair>], <method>/<dataset>, <method>/, "
"and shared-folder layout (image-id folders containing per-method files)."
)
return input_folder
def _infer_effective_structure(
source: str,
root: str,
structure: str,
input_folder: Dict[str, Any],
) -> str:
if source == "external":
return "external"
if structure == "shared":
return "shared"
try:
# shared detection: method -> list-of-files
if any(isinstance(v, list) for v in input_folder.values()):
return "shared"
except Exception:
pass
try:
method = next(iter(input_folder.keys()))
cand = input_folder[method]
if not isinstance(cand, str):
return structure
method_root = os.path.join(root, method)
rel = os.path.relpath(cand, method_root)
if rel in (".", ""):
return "flat"
parts = [p for p in rel.split(os.sep) if p and p != "."]
if len(parts) >= 3:
return "group-dataset-pair"
if len(parts) == 2:
return "group-dataset"
if len(parts) == 1:
return "dataset-only"
return "flat"
except Exception:
return structure
def _structure_uses_fields(source: str, eff_structure: str) -> Dict[str, bool]:
# Controls whether fields are relevant to *path resolution*.
if source == "external":
return {"root": False, "group": False, "dataset": True, "pair": True, "structure": False}
s = (eff_structure or "auto").lower()
if s == "group-dataset-pair":
return {"root": True, "group": True, "dataset": True, "pair": True, "structure": True}
if s == "group-dataset":
return {"root": True, "group": True, "dataset": True, "pair": False, "structure": True}
if s == "dataset-only":
return {"root": True, "group": False, "dataset": True, "pair": False, "structure": True}
if s == "flat":
return {"root": True, "group": False, "dataset": False, "pair": False, "structure": True}
if s == "shared":
return {"root": True, "group": False, "dataset": False, "pair": False, "structure": True}
# auto/unknown: keep everything editable (except pair, which is only meaningful for group-dataset-pair)
return {"root": True, "group": True, "dataset": True, "pair": True, "structure": True}
def ui_update_param_relevance(
sess: Optional[_Session],
source: str,
root: str,
group: str,
dataset: str,
pair: str,
structure: str,
) -> Tuple[gr.update, gr.update, gr.update, gr.update, gr.update]:
# Determine effective structure for UI hinting.
eff = structure
if source == "external":
eff = "external"
elif structure == "auto":
# On initial page load (no session yet), avoid any filesystem inference.
if sess is None:
eff = "auto"
elif sess is not None and sess.source == source and sess.root == root and sess.group == group and sess.dataset == dataset and sess.pair == pair and sess.structure == structure:
eff = sess.effective_structure
else:
# Best-effort inference (may be slow on large folders; safe fallback).
try:
inputs = _build_input_folder(source, root, group, dataset, pair, structure)
eff = _infer_effective_structure(source, root, structure, inputs)
except Exception:
eff = "auto"
uses = _structure_uses_fields(source, eff)
# Gray out by disabling the field (matches inactive input styling).
return (
gr.update(interactive=bool(uses.get("root", True))),
gr.update(interactive=bool(uses.get("group", True))),
gr.update(interactive=bool(uses.get("dataset", True))),
gr.update(interactive=bool(uses.get("pair", True))),
gr.update(interactive=bool(uses.get("structure", True))),
)
def _frame_choices(sess: _Session) -> List[str]:
files = sess.comparator.image_files.get(sess.reference_key, [])
return [os.path.basename(p) for p in files]
def _roi_table_from_comparator(cmp_: compare.InteractiveCropComparator) -> List[List[int]]:
rows: List[List[int]] = []
for rid in sorted(cmp_.rois.keys()):
rect = cmp_.rois[rid].get("rect")
if rect is None:
rows.append([rid, 0, 0, 0, 0])
else:
x1, y1, x2, y2 = rect
rows.append([rid, int(x1), int(y1), int(x2), int(y2)])
return rows
def _apply_roi_table_to_comparator(
cmp_: compare.InteractiveCropComparator,
table: Any,
) -> None:
def _to_rows(obj: Any) -> List[List[Any]]:
if obj is None:
return []
if isinstance(obj, list):
return obj
# Gradio Dataframe may return a pandas.DataFrame depending on version.
try:
# pandas.DataFrame has .values
values = getattr(obj, "values", None)
if values is not None:
return values.tolist()
except Exception:
pass
try:
to_numpy = getattr(obj, "to_numpy", None)
if callable(to_numpy):
return to_numpy().tolist()
except Exception:
pass
return []
def _safe_int(v: Any, default: int = 0) -> int:
if v is None:
return default
try:
if isinstance(v, float) and np.isnan(v):
return default
except Exception:
pass
try:
return int(v)
except Exception:
return default
rois: Dict[int, Dict[str, Any]] = {}
rows = _to_rows(table)
for row in rows:
if row is None or len(row) < 5:
continue
rid = _safe_int(row[0], default=0)
if rid <= 0:
continue
x1, y1, x2, y2 = (
_safe_int(row[1]),
_safe_int(row[2]),
_safe_int(row[3]),
_safe_int(row[4]),
)
color = cmp_.color_for_id(rid)
rect = None
if any(v != 0 for v in (x1, y1, x2, y2)):
rect = (x1, y1, x2, y2)
rois[rid] = {"rect": rect, "color": color}
cmp_.rois = rois
cmp_.active_roi = max(rois.keys()) if rois else None
cmp_.selection_start = None
def _render_outputs(sess: _Session, preview_key: str) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray], List[List[int]]]:
cmp_ = sess.comparator
ref = cmp_.read_frame(sess.reference_key, cmp_.current_frame)
if ref is None:
return None, None, None, _roi_table_from_comparator(cmp_)
ref_overlay = _draw_rois_on_bgr(ref, cmp_.rois, thickness=cmp_.line_thickness, active_roi=cmp_.active_roi, cmp_=cmp_)
grid = cmp_.build_grid()
# In the CLI, display_scale/magnify is used when showing the OpenCV window.
# In Gradio, we need to explicitly scale the rendered grid image.
if grid is not None:
try:
dscale = float(getattr(cmp_, "display_scale", 1.0) or 1.0)
if dscale > 0 and dscale != 1.0:
grid = cv2.resize(grid, dsize=None, fx=dscale, fy=dscale, interpolation=cv2.INTER_NEAREST)
except Exception:
pass
final = cmp_.build_final_layout_for_key(preview_key or sess.reference_key, sort_mode=cmp_.sort_mode, reverse_sort=cmp_.sort_reverse)
return _bgr_to_rgb(ref_overlay), _bgr_to_rgb(grid) if grid is not None else None, _bgr_to_rgb(final) if final is not None else None, _roi_table_from_comparator(cmp_)
def ui_load(
source: str,
root: str,
group: str,
dataset: str,
pair: str,
structure: str,
exclude: str,
roi_file: str,
compose_layout: bool,
output_dir: str,
columns: int,
grid_gap: int,
magnify: float,
thickness: int,
layout: str,
layout_gap: int,
layout_border_scale: float,
layout_bg_color: str,
layout_use_alpha: bool,
grid_sort_mode: str,
grid_sort_reverse: bool,
) -> Tuple[Any, ...]:
input_folder = _build_input_folder(source, root, group, dataset, pair, structure, exclude)
# Parse background color
bg = _parse_bg_color(layout_bg_color)
# Instantiate comparator (no OpenCV windows used in Gradio mode)
cmp_ = compare.InteractiveCropComparator(
input_folder,
output_folder=output_dir or "./crop_grids/",
reference_key=('GT' if 'GT' in input_folder else ('input' if 'input' in input_folder else next(iter(input_folder.keys())))),
columns=columns,
grid_gap=grid_gap,
display_scale=magnify,
line_thickness=thickness,
layout_border_scale=layout_border_scale,
layout_gap=layout_gap,
layout_bg_color=bg,
layout_use_alpha=layout_use_alpha,
compose_layout=compose_layout if compose_layout is not None else True,
current_group=group,
current_dataset=dataset,
)
cmp_.layout_mode = layout
cmp_.sort_mode = grid_sort_mode
cmp_.sort_reverse = grid_sort_reverse
cmp_.mode = 'selection'
if len(cmp_.rois) == 0:
cmp_.add_roi(1)
roi_note = ""
roi_path = (roi_file or "").strip()
if roi_path:
ok = cmp_.load_rois_from_txt(os.path.expanduser(roi_path))
roi_note = f" Loaded ROIs from {roi_path}." if ok else f" Failed to load ROIs from {roi_path}."
sess = _Session(
comparator=cmp_,
source=source,
root=root,
group=group,
dataset=dataset,
pair=pair,
structure=structure,
effective_structure=_infer_effective_structure(source, root, structure, input_folder),
reference_key=cmp_.reference_key,
pending_point=None,
)
frames = _frame_choices(sess)
methods = sorted(list(cmp_.image_files.keys()))
preview_default = 'GT' if 'GT' in methods else (sess.reference_key if sess.reference_key in methods else methods[0])
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_default)
status = f"Loaded {len(methods)} methods, {len(frames)} frames (reference={sess.reference_key}).{roi_note}"
root_u, group_u, dataset_u, pair_u, structure_u = ui_update_param_relevance(sess, source, root, group, dataset, pair, structure)
# After a successful load: keep Load clickable but make it non-primary; enable Save as primary.
load_btn_u = gr.Button(value="Load", interactive=True, variant="secondary")
save_btn_u = gr.Button(value="Save Outputs", interactive=True, variant="primary")
save_grid_btn_u = gr.Button(value="Save Grid Images", interactive=True, variant="secondary")
# ROI panel state
set_btn_u = gr.Button(value="Set ROI", variant="primary" if cmp_.mode == "selection" else "secondary")
move_btn_u = gr.Button(value="Move ROI", variant="primary" if cmp_.mode == "position" else "secondary")
active_roi_u = gr.Number(value=int(cmp_.active_roi) if cmp_.active_roi is not None else 0, precision=0)
add_roi_id_u = gr.Number(value=_next_available_roi_id(cmp_.rois), precision=0)
return (
sess,
gr.Dropdown(choices=frames, value=frames[0] if frames else None),
gr.Dropdown(choices=methods, value=preview_default),
ref_img,
grid_img,
final_img,
roi_table,
status,
root_u,
group_u,
dataset_u,
pair_u,
structure_u,
load_btn_u,
save_btn_u,
set_btn_u,
move_btn_u,
active_roi_u,
add_roi_id_u,
save_grid_btn_u,
)
def _mode_button_updates(mode: str) -> Tuple[gr.Button, gr.Button]:
m = (mode or "selection").lower()
if m not in ("selection", "position"):
m = "selection"
set_btn_u = gr.Button(value="Set ROI", variant="primary" if m == "selection" else "secondary")
move_btn_u = gr.Button(value="Move ROI", variant="primary" if m == "position" else "secondary")
return set_btn_u, move_btn_u
def ui_set_mode(sess: _Session, mode: str) -> Tuple[Optional[np.ndarray], str, gr.Button, gr.Button, gr.Number]:
if sess is None:
set_u, move_u = _mode_button_updates("selection")
return None, "Session not loaded yet. Click Load first.", set_u, move_u, gr.Number(value=0, precision=0)
m = (mode or "selection").lower()
if m not in ("selection", "position"):
m = "selection"
sess.comparator.mode = m
# Cancel any partial click if user switches modes.
sess.pending_point = None
set_u, move_u = _mode_button_updates(m)
active = sess.comparator.active_roi
ref = sess.comparator.read_frame(sess.reference_key, sess.comparator.current_frame)
ref_overlay = None
if ref is not None:
ref_overlay = _draw_rois_on_bgr(
ref,
sess.comparator.rois,
thickness=sess.comparator.line_thickness,
active_roi=sess.comparator.active_roi,
cmp_=sess.comparator,
)
return (
_bgr_to_rgb(ref_overlay) if ref_overlay is not None else None,
f"Switched mode to: {m}",
set_u,
move_u,
gr.Number(value=int(active) if active is not None else 0, precision=0),
)
def ui_set_active_roi(sess: _Session, rid: Any, preview_key: str) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], gr.Number]:
if sess is None:
return None, None, gr.Number(value=0, precision=0)
try:
rid_i = int(rid)
except Exception:
rid_i = 0
if rid_i > 0 and rid_i in sess.comparator.rois:
sess.comparator.active_roi = rid_i
else:
# If invalid, keep current
rid_i = int(sess.comparator.active_roi) if sess.comparator.active_roi is not None else 0
sess.pending_point = None
ref = sess.comparator.read_frame(sess.reference_key, sess.comparator.current_frame)
ref_overlay = None
if ref is not None:
ref_overlay = _draw_rois_on_bgr(ref, sess.comparator.rois, thickness=sess.comparator.line_thickness, active_roi=sess.comparator.active_roi, cmp_=sess.comparator)
final = sess.comparator.build_final_layout_for_key(preview_key or sess.reference_key, sort_mode=sess.comparator.sort_mode, reverse_sort=sess.comparator.sort_reverse)
return (
_bgr_to_rgb(ref_overlay) if ref_overlay is not None else None,
_bgr_to_rgb(final) if final is not None else None,
gr.Number(value=rid_i, precision=0),
)
def ui_apply_grid_settings(
sess: _Session,
columns: int,
grid_gap: int,
magnify: float,
grid_sort_mode: str,
grid_sort_reverse: bool,
) -> Tuple[Optional[np.ndarray], str]:
if sess is None:
return None, "Session not loaded yet. Click Load first."
cmp_ = sess.comparator
try:
cmp_.columns = max(int(columns), 1)
except Exception:
pass
try:
cmp_.grid_gap = int(grid_gap)
except Exception:
pass
try:
if hasattr(cmp_, "display_scale"):
cmp_.display_scale = float(magnify)
except Exception:
pass
try:
cmp_.sort_mode = grid_sort_mode
except Exception:
pass
try:
cmp_.sort_reverse = bool(grid_sort_reverse)
except Exception:
pass
grid = cmp_.build_grid()
if grid is not None:
try:
dscale = float(getattr(cmp_, "display_scale", 1.0) or 1.0)
if dscale > 0 and dscale != 1.0:
grid = cv2.resize(grid, dsize=None, fx=dscale, fy=dscale, interpolation=cv2.INTER_NEAREST)
except Exception:
pass
return (_bgr_to_rgb(grid) if grid is not None else None), "Updated Per-ROI Method Grid."
def ui_apply_final_settings(
sess: _Session,
preview_key: str,
layout: str,
compose_layout: bool,
layout_gap: int,
layout_border_scale: float,
layout_bg_color: str,
) -> Tuple[Optional[np.ndarray], str]:
if sess is None:
return None, "Session not loaded yet. Click Load first."
cmp_ = sess.comparator
try:
cmp_.layout_mode = layout
except Exception:
pass
try:
cmp_.compose_layout = bool(compose_layout)
except Exception:
pass
try:
cmp_.layout_gap = int(layout_gap)
except Exception:
pass
try:
cmp_.layout_border_scale = float(layout_border_scale)
except Exception:
pass
try:
cmp_.layout_bg_color = _parse_bg_color(layout_bg_color)
except Exception:
pass
final = cmp_.build_final_layout_for_key(preview_key or sess.reference_key, sort_mode=cmp_.sort_mode, reverse_sort=cmp_.sort_reverse)
return (_bgr_to_rgb(final) if final is not None else None), "Updated Final Layout Preview."
def ui_apply_reference_settings(
sess: _Session,
preview_key: str,
thickness: int,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], str]:
if sess is None:
return None, None, "Session not loaded yet. Click Load first."
cmp_ = sess.comparator
try:
cmp_.line_thickness = max(int(thickness), 1)
except Exception:
pass
ref = cmp_.read_frame(sess.reference_key, cmp_.current_frame)
ref_overlay = None
if ref is not None:
ref_overlay = _draw_rois_on_bgr(ref, cmp_.rois, thickness=cmp_.line_thickness, active_roi=cmp_.active_roi, cmp_=cmp_)
final = cmp_.build_final_layout_for_key(preview_key or sess.reference_key, sort_mode=cmp_.sort_mode, reverse_sort=cmp_.sort_reverse)
return (
_bgr_to_rgb(ref_overlay) if ref_overlay is not None else None,
_bgr_to_rgb(final) if final is not None else None,
"Updated Reference + ROIs (and Final Layout Preview).",
)
def ui_set_preview_key(sess: _Session, preview_key: str) -> Tuple[Optional[np.ndarray], str]:
if sess is None:
return None, "Session not loaded yet. Click Load first."
cmp_ = sess.comparator
final = cmp_.build_final_layout_for_key(preview_key or sess.reference_key, sort_mode=cmp_.sort_mode, reverse_sort=cmp_.sort_reverse)
return (_bgr_to_rgb(final) if final is not None else None), f"Preview method: {preview_key}" if preview_key else "Updated preview method."
def ui_apply_settings(
sess: _Session,
preview_key: str,
columns: int,
grid_gap: int,
magnify: float,
thickness: int,
layout: str,
compose_layout: bool,
layout_gap: int,
layout_border_scale: float,
layout_bg_color: str,
layout_use_alpha: bool,
grid_sort_mode: str,
grid_sort_reverse: bool,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray], List[List[int]], str]:
if sess is None:
return None, None, None, [], "Session not loaded yet. Click Load first."
cmp_ = sess.comparator
try:
cmp_.columns = max(int(columns), 1)
except Exception:
pass
try:
cmp_.grid_gap = int(grid_gap)
except Exception:
pass
try:
# display_scale is used for grid magnification
if hasattr(cmp_, "display_scale"):
cmp_.display_scale = float(magnify)
except Exception:
pass
try:
cmp_.line_thickness = max(int(thickness), 1)
except Exception:
pass
try:
cmp_.layout_mode = layout
except Exception:
pass
try:
cmp_.compose_layout = bool(compose_layout)
except Exception:
pass
try:
cmp_.layout_gap = int(layout_gap)
except Exception:
pass
try:
cmp_.layout_border_scale = float(layout_border_scale)
except Exception:
pass
try:
cmp_.layout_bg_color = _parse_bg_color(layout_bg_color)
except Exception:
pass
try:
cmp_.layout_use_alpha = bool(layout_use_alpha)
except Exception:
pass
try:
cmp_.sort_mode = grid_sort_mode
except Exception:
pass
try:
cmp_.sort_reverse = bool(grid_sort_reverse)
except Exception:
pass
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
return ref_img, grid_img, final_img, roi_table, "Applied layout/advanced settings."
def ui_set_frame(sess: _Session, frame_name: str, preview_key: str) -> Tuple[np.ndarray, Optional[np.ndarray], Optional[np.ndarray], List[List[int]], str]:
files = sess.comparator.image_files.get(sess.reference_key, [])
if not files:
return None, None, None, _roi_table_from_comparator(sess.comparator), "No frames loaded."
idx = 0
for i, p in enumerate(files):
if os.path.basename(p) == frame_name:
idx = i
break
sess.comparator.current_frame = idx
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
return ref_img, grid_img, final_img, roi_table, f"Frame: {frame_name}"
def ui_update_from_table(sess: _Session, roi_table: Any, preview_key: str) -> Tuple[Any, ...]:
if sess is None:
return None, None, None, [], "Session not loaded yet. Click Load first.", gr.Number(value=0, precision=0), gr.Number(value=1, precision=0)
def _to_rows(obj: Any) -> List[List[Any]]:
if obj is None:
return []
if isinstance(obj, list):
return obj
# Gradio Dataframe may return a pandas.DataFrame depending on version.
try:
values = getattr(obj, "values", None)
if values is not None:
return values.tolist()
except Exception:
pass
try:
to_numpy = getattr(obj, "to_numpy", None)
if callable(to_numpy):
return to_numpy().tolist()
except Exception:
pass
return []
def _safe_int(v: Any, default: int = 0) -> int:
if v is None:
return default
try:
if isinstance(v, float) and np.isnan(v):
return default
except Exception:
pass
try:
return int(v)
except Exception:
return default
def _normalize_table(obj: Any) -> List[List[int]]:
out: List[List[int]] = []
for row in _to_rows(obj):
if row is None or len(row) < 5:
continue
rid = _safe_int(row[0], default=0)
if rid <= 0:
continue
x1 = _safe_int(row[1])
y1 = _safe_int(row[2])
x2 = _safe_int(row[3])
y2 = _safe_int(row[4])
out.append([rid, x1, y1, x2, y2])
out.sort(key=lambda r: r[0])
return out
# Gradio can fire roi_table.change even when roi_table is updated programmatically
# (e.g. Add ROI or image click handler returns a new table), which can cause a
# second render. If the incoming table already matches the current comparator
# state, treat this as a no-op.
if _normalize_table(roi_table) == _normalize_table(_roi_table_from_comparator(sess.comparator)):
return gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
_apply_roi_table_to_comparator(sess.comparator, roi_table)
ref_img, grid_img, final_img, roi_table2 = _render_outputs(sess, preview_key)
active = sess.comparator.active_roi
return (
ref_img,
grid_img,
final_img,
roi_table2,
"Updated ROIs.",
gr.Number(value=int(active) if active is not None else 0, precision=0),
gr.Number(value=_next_available_roi_id(sess.comparator.rois), precision=0),
)
def ui_add_roi(sess: _Session, roi_id: int, preview_key: str) -> Tuple[Any, ...]:
if sess is None:
set_u, move_u = _mode_button_updates("selection")
return None, None, None, [], "Session not loaded yet. Click Load first.", gr.Number(value=0, precision=0), set_u, move_u, gr.Number(value=1, precision=0)
# In the CLI, add_roi(None) may re-select an existing empty ROI.
# In Gradio, the expectation for the button is: always add a *new* ROI.
requested = None
try:
requested = int(roi_id)
except Exception:
requested = None
used = set(sess.comparator.rois.keys())
if requested is None or requested <= 0:
rid = (max(used) + 1) if used else 1
else:
if requested in used:
rid = max(used) + 1
else:
rid = requested
sess.comparator.add_roi(roi_id=rid)
# Requirement: Add ROI forces selection mode and Set ROI button becomes active.
sess.comparator.mode = "selection"
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
active = sess.comparator.active_roi
set_u, move_u = _mode_button_updates(sess.comparator.mode)
next_id = _next_available_roi_id(sess.comparator.rois)
return (
ref_img,
grid_img,
final_img,
roi_table,
"Added ROI. Click twice to define its rectangle, or edit the table.",
gr.Number(value=int(active) if active is not None else 0, precision=0),
set_u,
move_u,
gr.Number(value=next_id, precision=0),
)
def ui_clear_rois(sess: _Session, preview_key: str) -> Tuple[Any, ...]:
if sess is None:
set_u, move_u = _mode_button_updates("selection")
return None, None, None, [], "Session not loaded yet. Click Load first.", gr.Number(value=0, precision=0), set_u, move_u, gr.Number(value=1, precision=0)
sess.comparator.rois = {}
sess.comparator.active_roi = None
sess.comparator.selection_start = None
sess.pending_point = None
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
# Clearing resets mode back to selection for predictable next action.
sess.comparator.mode = "selection"
set_u, move_u = _mode_button_updates(sess.comparator.mode)
return ref_img, grid_img, final_img, roi_table, "Cleared all ROIs.", gr.Number(value=0, precision=0), set_u, move_u, gr.Number(value=1, precision=0)
def ui_click_image(sess: _Session, evt: gr.SelectData, preview_key: str) -> Tuple[Any, ...]:
if sess is None:
set_u, move_u = _mode_button_updates("selection")
return None, None, None, [], "Session not loaded yet. Click Load first.", gr.Number(value=0, precision=0), set_u, move_u, gr.Number(value=1, precision=0)
x, y = int(evt.index[0]), int(evt.index[1])
# Position mode: single click moves the active ROI while keeping its size.
if getattr(sess.comparator, "mode", "selection") == "position":
sess.pending_point = None
rid = sess.comparator.active_roi
if rid is None or rid not in sess.comparator.rois or sess.comparator.rois[rid].get("rect") is None:
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
active = sess.comparator.active_roi
set_u, move_u = _mode_button_updates(sess.comparator.mode)
return (
ref_img,
grid_img,
final_img,
roi_table,
"Position mode: no active ROI rectangle to move.",
gr.Number(value=int(active) if active is not None else 0, precision=0),
set_u,
move_u,
gr.Number(value=_next_available_roi_id(sess.comparator.rois), precision=0),
)
ref = sess.comparator.read_frame(sess.reference_key, sess.comparator.current_frame)
h_img, w_img = (ref.shape[0], ref.shape[1]) if ref is not None else (None, None)
x1, y1, x2, y2 = sess.comparator.rois[rid]["rect"]
w = abs(int(x2) - int(x1))
h = abs(int(y2) - int(y1))
new_x1 = int(x - w // 2)
new_y1 = int(y - h // 2)
new_x2 = int(new_x1 + w)
new_y2 = int(new_y1 + h)
if w_img is not None and h_img is not None:
new_x1 = max(0, min(w_img - 1, new_x1))
new_y1 = max(0, min(h_img - 1, new_y1))
new_x2 = max(0, min(w_img - 1, new_x2))
new_y2 = max(0, min(h_img - 1, new_y2))
sess.comparator.rois[rid]["rect"] = (new_x1, new_y1, new_x2, new_y2)
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
active = sess.comparator.active_roi
set_u, move_u = _mode_button_updates(sess.comparator.mode)
return (
ref_img,
grid_img,
final_img,
roi_table,
f"Moved ROI {rid} to center ({x}, {y}).",
gr.Number(value=int(active) if active is not None else 0, precision=0),
set_u,
move_u,
gr.Number(value=_next_available_roi_id(sess.comparator.rois), precision=0),
)
if sess.pending_point is None:
sess.pending_point = (x, y)
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
active = sess.comparator.active_roi
set_u, move_u = _mode_button_updates(sess.comparator.mode)
return (
ref_img,
grid_img,
final_img,
roi_table,
f"Start point set at ({x}, {y}). Click again to finish ROI.",
gr.Number(value=int(active) if active is not None else 0, precision=0),
set_u,
move_u,
gr.Number(value=_next_available_roi_id(sess.comparator.rois), precision=0),
)
sx, sy = sess.pending_point
sess.pending_point = None
# Ensure there is an active ROI to write into
if sess.comparator.active_roi is None or sess.comparator.active_roi not in sess.comparator.rois:
sess.comparator.add_roi()
rid = sess.comparator.active_roi
sess.comparator.rois[rid]["rect"] = (sx, sy, x, y)
# After a rectangle is defined (two clicks), switch to position mode
# so the next click can move the active ROI immediately.
sess.comparator.mode = "position"
ref_img, grid_img, final_img, roi_table = _render_outputs(sess, preview_key)
active = sess.comparator.active_roi
set_u, move_u = _mode_button_updates(sess.comparator.mode)
return (
ref_img,