-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmain_window.py
More file actions
2053 lines (1767 loc) · 89.9 KB
/
main_window.py
File metadata and controls
2053 lines (1767 loc) · 89.9 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
"""PySide6 based GUI for DeepLabCut Live."""
from __future__ import annotations
import importlib.metadata
import json
import logging
import os
import time
from pathlib import Path
# NOTE @C-Achard: his could be added in settings eventually
# Forces pypylon to create 2 emulation virtual cameras,
# mostly for testing. This shold not be enabled for release.
# os.environ["PYLON_CAMEMU"] = "2"
import cv2
import numpy as np
from PySide6.QtCore import QRect, QSettings, Qt, QTimer, QUrl
from PySide6.QtGui import (
QAction,
QActionGroup,
QCloseEvent,
QColor,
QDesktopServices,
QFont,
QIcon,
QImage,
QPainter,
QPixmap,
)
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
QDockWidget,
QFileDialog,
QFormLayout,
QGridLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QMainWindow,
QMessageBox,
QPushButton,
QSizePolicy,
QSpinBox,
QStatusBar,
QStyle,
QVBoxLayout,
QWidget,
)
from dlclivegui.cameras import CameraFactory
from dlclivegui.config import (
DEFAULT_CONFIG,
ApplicationSettings,
BoundingBoxSettings,
CameraSettings,
DLCProcessorSettings,
MultiCameraSettings,
RecordingSettings,
VisualizationSettings,
)
from ..processors.processor_utils import (
default_processors_dir,
instantiate_from_scan,
scan_processor_folder,
scan_processor_package,
)
from ..services.dlc_processor import DLCLiveProcessor, PoseResult
from ..services.multi_camera_controller import MultiCameraController, MultiFrameData, get_camera_id
from ..utils.display import BBoxColors, compute_tile_info, create_tiled_frame, draw_bbox, draw_pose
from ..utils.settings_store import DLCLiveGUISettingsStore, ModelPathStore
from ..utils.stats import format_dlc_stats
from ..utils.utils import FPSTracker
from .camera_config.camera_config_dialog import CameraConfigDialog
from .misc import color_dropdowns as color_ui
from .misc import layouts as lyts
from .misc.drag_spinbox import ScrubSpinBox
from .misc.eliding_label import ElidingPathLabel
from .recording_manager import RecordingManager
from .theme import LOGO, LOGO_ALPHA, AppStyle, apply_theme
logger = logging.getLogger("DLCLiveGUI")
class DLCLiveMainWindow(QMainWindow):
"""Main application window."""
def __init__(self, config: ApplicationSettings | None = None):
super().__init__()
self.setWindowTitle("DeepLabCut Live GUI")
self.settings = QSettings("DeepLabCut", "DLCLiveGUI")
self._model_path_store = ModelPathStore(self.settings)
self._settings_store = DLCLiveGUISettingsStore(self.settings)
if config is None:
# 1) snapshot
cfg = self._settings_store.load_full_config_snapshot()
if cfg is not None:
config = cfg
self._config_path = None
logger.info("Loaded configuration from QSettings snapshot.")
else:
# 2) last config file path
last_cfg_path = self._settings_store.get_last_config_path()
if last_cfg_path:
try:
p = Path(last_cfg_path)
if p.exists() and p.is_file():
config = ApplicationSettings.load(str(p))
self._config_path = p
logger.info(f"Loaded configuration from last config path: {p}")
else:
config = DEFAULT_CONFIG
self._config_path = None
except Exception as exc:
logger.warning(
f"Failed to load last config path ({last_cfg_path}): {exc}. Using default config."
)
config = DEFAULT_CONFIG
self._config_path = None
else:
# 3) default
config = DEFAULT_CONFIG
self._config_path = None
else:
self._config_path = None
self._fps_tracker = FPSTracker()
self._rec_manager = RecordingManager()
self._dlc = DLCLiveProcessor()
self.multi_camera_controller = MultiCameraController()
self._config = config
self._inference_camera_id: str | None = None # Camera ID used for inference
self._running_cams_ids: set[str] = set()
self._current_frame: np.ndarray | None = None
self._raw_frame: np.ndarray | None = None
self._last_pose: PoseResult | None = None
self._dlc_active: bool = False
self._active_camera_settings: CameraSettings | None = None
self._last_drop_warning = 0.0
self._last_recorder_summary = "Recorder idle"
self._display_interval = 1.0 / 25.0
self._last_display_time = 0.0
self._dlc_initialized = False
self._scanned_processors: dict = {}
self._processor_keys: list = []
self._last_processor_vid_recording = False
self._auto_record_session_name: str | None = None
self._bbox_x0 = 0
self._bbox_y0 = 0
self._bbox_x1 = 0
self._bbox_y1 = 0
self._bbox_enabled = False
# UI elements
self._current_style: AppStyle = AppStyle.DARK
self._cam_dialog: CameraConfigDialog | None = None
# Visualization settings (will be updated from config)
self._p_cutoff = 0.6
self._colormap = "hot"
self._bbox_color = (0, 0, 255) # BGR: red
# Multi-camera state
self._multi_camera_mode = False
self._multi_camera_frames: dict[str, np.ndarray] = {}
# DLC pose rendering info for tiled view
self._dlc_tile_offset: tuple[int, int] = (0, 0) # (x, y) offset in tiled frame
self._dlc_tile_scale: tuple[float, float] = (1.0, 1.0) # (scale_x, scale_y)
# Display flag (decoupled from frame capture for performance)
self._display_dirty: bool = False
self._load_icons()
self._preview_pixmap = QPixmap(LOGO_ALPHA)
self._setup_ui()
self._connect_signals()
self._apply_config(self._config)
self._refresh_processors() # Scan and populate processor dropdown
self._update_inference_buttons()
self._update_camera_controls_enabled()
self._metrics_timer = QTimer(self)
self._metrics_timer.setInterval(500)
self._metrics_timer.timeout.connect(self._update_metrics)
self._metrics_timer.start()
self._update_metrics()
# Display timer - decoupled from frame capture for performance
self._display_timer = QTimer(self)
self._display_timer.setInterval(33) # ~30 fps display rate
self._display_timer.timeout.connect(self._update_display_from_pending)
self._display_timer.start()
# Validate cameras from loaded config (deferred to allow window to show first)
# NOTE IMPORTANT (tests/CI): This is scheduled via a QTimer and may fire during pytest-qt teardown.
# NOTE @C-Achard 2026-03-02: Handling this in closeEvent should help
self._camera_validation_timer = QTimer(self)
self._camera_validation_timer.setSingleShot(True)
self._camera_validation_timer.timeout.connect(self._validate_configured_cameras)
self._camera_validation_timer.start(100)
# If validation triggers a modal QMessageBox (warning/error) while the parent window is closing,
# it can cause errors with unpredictable timing (heap corruption / access violations).
#
# Mitigations for tests/CI:
# - Disable this timer by monkeypatching _validate_configured_cameras in GUI tests
# - OR monkeypatch/override _show_warning/_show_error to no-op in GUI tests (easiest)
def resizeEvent(self, event):
super().resizeEvent(event)
if not self.multi_camera_controller.is_running():
self._show_logo_and_text()
# ------------------------------------------------------------------ UI
def _init_theme_actions(self) -> None:
"""Set initial checked state for theme actions based on current app stylesheet."""
self.action_dark_mode.setChecked(self._current_style == AppStyle.DARK)
self.action_light_mode.setChecked(self._current_style == AppStyle.SYS_DEFAULT)
def _apply_theme(self, mode: AppStyle) -> None:
"""Apply the selected theme and update menu action states."""
apply_theme(mode, self.action_dark_mode, self.action_light_mode)
self._current_style = mode
def _load_icons(self):
self.setWindowIcon(QIcon(LOGO))
def _setup_ui(self) -> None:
# central = QWidget()
# layout = QHBoxLayout(central)
# Video panel with display and performance stats
video_panel = QWidget()
video_layout = QVBoxLayout(video_panel)
video_layout.setContentsMargins(0, 0, 0, 0)
## Video display widget
self.video_label = QLabel()
self.video_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.video_label.setMinimumSize(640, 360)
self.video_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
video_layout.addWidget(self.video_label, stretch=1)
## Stats panel below video with clear labels
stats_widget = QWidget()
stats_widget.setStyleSheet("padding: 5px;")
# stats_widget.setMinimumWidth(800) # Prevent excessive line breaks
stats_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
stats_widget.setMinimumHeight(80)
self._build_stats_layout(stats_widget)
video_layout.addWidget(stats_widget, stretch=0)
# Central widget is just the video panel (video + stats)
video_panel.setLayout(video_layout)
self.setCentralWidget(video_panel)
# Allow user to select stats text
for lbl in (self.camera_stats_label, self.dlc_stats_label, self.recording_stats_label):
lbl.setTextInteractionFlags(Qt.TextSelectableByMouse)
# Controls panel with fixed width to prevent shifting
controls_widget = QWidget()
# controls_widget.setMaximumWidth(500)
controls_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
controls_layout = QVBoxLayout(controls_widget)
controls_layout.setContentsMargins(5, 5, 5, 5)
controls_layout.addWidget(self._build_camera_group())
controls_layout.addWidget(self._build_dlc_group())
controls_layout.addWidget(self._build_recording_group())
controls_layout.addWidget(self._build_viz_group())
# Preview/Stop buttons at bottom of controls - wrap in widget
button_bar_widget = QWidget()
button_bar = QHBoxLayout(button_bar_widget)
button_bar.setContentsMargins(0, 5, 0, 5)
self.preview_button = QPushButton("Start Preview")
self.preview_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
self.preview_button.setMinimumWidth(150)
self.stop_preview_button = QPushButton("Stop Preview")
self.stop_preview_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaStop))
self.stop_preview_button.setEnabled(False)
self.stop_preview_button.setMinimumWidth(150)
button_bar.addWidget(self.preview_button)
button_bar.addWidget(self.stop_preview_button)
controls_layout.addWidget(button_bar_widget)
controls_layout.addStretch(1)
# Add controls and video panel to main layout
## Dock widget for controls
self.controls_dock = QDockWidget("Controls", self)
self.controls_dock.setObjectName("ControlsDock") # important for state saving
self.controls_dock.setWidget(controls_widget)
### Dock features
self.controls_dock.setFeatures(
# must not be closable by user but visibility can be toggled from View -> Show controls
QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable # | QDockWidget.DockWidgetClosable
)
self.addDockWidget(Qt.LeftDockWidgetArea, self.controls_dock)
self.setDockOptions(
self.dockOptions()
| QMainWindow.DockOption.AllowTabbedDocks
| QMainWindow.DockOption.GroupedDragging
| QMainWindow.DockOption.AnimatedDocks
)
self.controls_dock.setStyleSheet(
"""/* Docked title bar: fully transparent */
QDockWidget#ControlsDock::title {
background-color: rgba(0, 0, 0, 0);
}
"""
)
self.setStatusBar(QStatusBar())
self._build_menus()
QTimer.singleShot(0, self._show_logo_and_text)
def _build_stats_layout(self, stats_widget: QWidget) -> QGridLayout:
stats_layout = QGridLayout(stats_widget)
stats_layout.setContentsMargins(5, 5, 5, 5)
stats_layout.setHorizontalSpacing(8) # tighten horizontal gap between title and value
stats_layout.setVerticalSpacing(3)
row = 0
# Camera
title_camera = QLabel("<b>Camera:</b>")
title_camera.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
stats_layout.addWidget(title_camera, row, 0, alignment=Qt.AlignTop)
self.camera_stats_label = QLabel("Camera idle")
self.camera_stats_label.setWordWrap(True)
self.camera_stats_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
stats_layout.addWidget(self.camera_stats_label, row, 1, alignment=Qt.AlignTop)
row += 1
# DLC
title_dlc = QLabel("<b>DLC Processor:</b>")
title_dlc.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
stats_layout.addWidget(title_dlc, row, 0, alignment=Qt.AlignTop)
self.dlc_stats_label = QLabel("DLC processor idle")
self.dlc_stats_label.setWordWrap(True)
self.dlc_stats_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
stats_layout.addWidget(self.dlc_stats_label, row, 1, alignment=Qt.AlignTop)
row += 1
# Recorder
title_rec = QLabel("<b>Recorder:</b>")
title_rec.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
stats_layout.addWidget(title_rec, row, 0, alignment=Qt.AlignTop)
self.recording_stats_label = QLabel("Recorder idle")
self.recording_stats_label.setWordWrap(True)
self.recording_stats_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
stats_layout.addWidget(self.recording_stats_label, row, 1, alignment=Qt.AlignTop)
# Critical: make column 1 (values) eat the width, keep column 0 tight
stats_layout.setColumnStretch(0, 0)
stats_layout.setColumnStretch(1, 1)
stats_widget.setLayout(stats_layout)
def _build_menus(self) -> None:
# File menu
file_menu = self.menuBar().addMenu("&File")
## Save/Load config
self.load_config_action = QAction("Load configuration…", self)
self.load_config_action.triggered.connect(self._action_load_config)
file_menu.addAction(self.load_config_action)
save_action = QAction("Save configuration", self)
save_action.triggered.connect(self._action_save_config)
file_menu.addAction(save_action)
save_as_action = QAction("Save configuration as…", self)
save_as_action.triggered.connect(self._action_save_config_as)
file_menu.addAction(save_as_action)
## Open recording folder
open_rec_folder_action = QAction("Open recording folder", self)
open_rec_folder_action.triggered.connect(self._action_open_recording_folder)
file_menu.addAction(open_rec_folder_action)
## Close
file_menu.addSeparator()
exit_action = QAction("Close window", self)
exit_action.triggered.connect(self.close)
file_menu.addAction(exit_action)
# View menu
view_menu = self.menuBar().addMenu("&View")
## Show/hide controls dock
self.action_show_controls = QAction("Show controls", self, checkable=True)
self.action_show_controls.setChecked(True)
self.action_show_controls.toggled.connect(self.controls_dock.setVisible)
self.controls_dock.visibilityChanged.connect(self.action_show_controls.setChecked)
view_menu.addAction(self.action_show_controls)
## --------------------
view_menu.addSeparator()
## Style actions
appearance_menu = view_menu.addMenu("Appearance")
self.action_dark_mode = QAction("Dark theme", self, checkable=True)
self.action_light_mode = QAction("System theme", self, checkable=True)
theme_group = QActionGroup(self)
theme_group.setExclusive(True)
theme_group.addAction(self.action_dark_mode)
theme_group.addAction(self.action_light_mode)
self.action_dark_mode.triggered.connect(lambda: self._apply_theme(AppStyle.DARK))
self.action_light_mode.triggered.connect(lambda: self._apply_theme(AppStyle.SYS_DEFAULT))
# ----------------------
appearance_menu.addAction(self.action_light_mode)
appearance_menu.addAction(self.action_dark_mode)
self._apply_theme(self._current_style)
self._init_theme_actions()
def _build_camera_group(self) -> QGroupBox:
group = QGroupBox("Camera")
form = QFormLayout(group)
# Camera config button - opens dialog for all camera configuration
config_layout = QHBoxLayout()
self.config_cameras_button = QPushButton("Configure Cameras...")
self.config_cameras_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_ComputerIcon))
self.config_cameras_button.setToolTip("Configure camera settings (single or multi-camera)")
config_layout.addWidget(self.config_cameras_button)
form.addRow(config_layout)
# Active cameras display label
self.active_cameras_label = QLabel("No cameras configured")
self.active_cameras_label.setWordWrap(True)
form.addRow("Active:", self.active_cameras_label)
return group
def _build_dlc_group(self) -> QGroupBox:
group = QGroupBox("DLCLive")
form = QFormLayout(group)
path_layout = QHBoxLayout()
self.model_path_edit = QLineEdit()
self.model_path_edit.setPlaceholderText("/path/to/exported/model")
path_layout.addWidget(self.model_path_edit)
self.browse_model_button = QPushButton("Browse…")
self.browse_model_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self.browse_model_button.clicked.connect(self._action_browse_model)
path_layout.addWidget(self.browse_model_button)
form.addRow("Model file", path_layout)
# Processor selection
processor_path_layout = QHBoxLayout()
self.processor_folder_edit = QLineEdit()
self.processor_folder_edit.setText(default_processors_dir())
processor_path_layout.addWidget(self.processor_folder_edit)
self.browse_processor_folder_button = QPushButton("Browse...")
self.browse_processor_folder_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self.browse_processor_folder_button.clicked.connect(self._action_browse_processor_folder)
self.browse_processor_folder_button.setToolTip(
"Select the folder to scan for DLC processor plugins."
"<br>Plugins must inherit from dlclive.Processor, see dlclivegui.processors for more details."
"<br><b>Important:</b> External processors are Python code that will be imported during discovery."
"<br>Only use processor plugins from trusted sources to avoid security risks."
)
processor_path_layout.addWidget(self.browse_processor_folder_button)
self.refresh_processors_button = QPushButton("Refresh")
self.refresh_processors_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_BrowserReload))
self.refresh_processors_button.clicked.connect(self._refresh_processors)
processor_path_layout.addWidget(self.refresh_processors_button)
form.addRow("Processor folder", processor_path_layout)
self.processor_combo = color_ui.ShrinkCurrentWidePopupComboBox(sizing=color_ui.ComboSizing(max_width=100))
self.processor_combo.addItem("No Processor", None)
# form.addRow("Processor", self.processor_combo)
# self.additional_options_edit = QPlainTextEdit()
# self.additional_options_edit.setPlaceholderText("")
# self.additional_options_edit.setFixedHeight(40)
# form.addRow("Additional options", self.additional_options_edit)
self.dlc_camera_combo = color_ui.ShrinkCurrentWidePopupComboBox(sizing=color_ui.ComboSizing(max_width=180))
self.dlc_camera_combo.setToolTip("Select which camera to use for pose inference")
# form.addRow("Inference camera", self.dlc_camera_combo)
self.dlc_camera_combo.setPlaceholderText("None")
processing_sttgs = lyts.make_two_field_row(
"Inference camera",
self.dlc_camera_combo,
"Processor",
self.processor_combo,
key_width=None,
)
self.dlc_camera_combo.update_shrink_width()
form.addRow(processing_sttgs)
# Wrap inference buttons in a widget to prevent shifting
inference_button_widget = QWidget()
inference_buttons = QHBoxLayout(inference_button_widget)
inference_buttons.setContentsMargins(0, 0, 0, 0)
self.start_inference_button = QPushButton("Start pose inference")
self.start_inference_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
self.start_inference_button.setEnabled(False)
self.start_inference_button.setMinimumWidth(150)
inference_buttons.addWidget(self.start_inference_button)
self.stop_inference_button = QPushButton("Stop pose inference")
self.stop_inference_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_BrowserStop))
self.stop_inference_button.setEnabled(False)
self.stop_inference_button.setMinimumWidth(150)
inference_buttons.addWidget(self.stop_inference_button)
form.addRow(inference_button_widget)
# self.show_predictions_checkbox = QCheckBox("Display pose predictions")
# self.show_predictions_checkbox.setChecked(True)
# form.addRow(self.show_predictions_checkbox)
self.allow_processor_ctrl_checkbox = QCheckBox("Allow processor-based control")
self.allow_processor_ctrl_checkbox.setChecked(False)
self.allow_processor_ctrl_checkbox.setToolTip(
"If enabled, the GUI will load and interact with the selected processor plugin.\n"
)
form.addRow(self.allow_processor_ctrl_checkbox)
self.processor_status_label = QLabel("Processor: No clients | Recording: No")
self.processor_status_label.setWordWrap(True)
form.addRow("Processor Status", self.processor_status_label)
return group
def _build_recording_group(self) -> QGroupBox:
"""Build recording controls group."""
group = QGroupBox("Recording")
form = QFormLayout(group)
# Output directory selection
dir_layout = QHBoxLayout()
self.output_directory_edit = QLineEdit()
dir_layout.addWidget(self.output_directory_edit)
browse_dir = QPushButton("Browse…")
browse_dir.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
browse_dir.clicked.connect(self._action_browse_directory)
dir_layout.addWidget(browse_dir)
form.addRow("Output directory", dir_layout)
# Session + run name
self.session_name_edit = QLineEdit()
self.session_name_edit.setPlaceholderText("e.g. mouseA_day1")
# form.addRow("Session name", self.session_name_edit)
self.use_timestamp_checkbox = QCheckBox("Use timestamp for run folder name")
self.use_timestamp_checkbox.setChecked(True)
self.use_timestamp_checkbox.setToolTip(
"If checked, run folder will be run_YYYYMMDD_HHMMSS_mmm.\n"
"If unchecked, run folder will be run_0001, run_0002, ..."
)
# form.addRow("", self.use_timestamp_checkbox)
session_opts = lyts.make_two_field_row(
"Session name", self.session_name_edit, None, self.use_timestamp_checkbox, key_width=100
)
form.addRow(session_opts)
# Show recording path preview
form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
form.setRowWrapPolicy(QFormLayout.DontWrapRows)
self.recording_path_preview = ElidingPathLabel("")
# No need to assign mouseReleaseEvent: the label handles click-to-copy internally
form.addRow("Will save to", self.recording_path_preview)
# self.recording_path_preview = QLabel("")
# # Ensure it never gets squished vertically
# self.recording_path_preview.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
# self.recording_path_preview.setWordWrap(False)
# self.recording_path_preview.setCursor(Qt.PointingHandCursor)
# self.recording_path_preview.setToolTip("") # will show the preview path
# self.recording_path_preview.setTextInteractionFlags(Qt.TextSelectableByMouse)
# self.recording_path_preview.mouseReleaseEvent = self._copy_path_on_click
# form.addRow("Will save to", self.recording_path_preview)
self.filename_edit = QLineEdit()
form.addRow("Filename", self.filename_edit)
# Container + codec + CRF in a single row
grid = QGridLayout()
grid.setContentsMargins(0, 2, 0, 2)
grid.setHorizontalSpacing(8)
grid.setColumnStretch(0, 0)
grid.setColumnStretch(1, 3)
grid.setColumnStretch(2, 0)
grid.setColumnStretch(3, 3)
grid.setColumnStretch(4, 0)
grid.setColumnStretch(5, 2)
## Container
container_label = QLabel("Container")
container_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
grid.addWidget(container_label, 0, 0)
self.container_combo = QComboBox()
self.container_combo.setToolTip("Select the video container/format")
self.container_combo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred)
self.container_combo.setEditable(True)
self.container_combo.addItems(["mp4", "avi", "mov"])
# Ensure it never becomes unreadable:
self.container_combo.setMinimumContentsLength(8)
self.container_combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
grid.addWidget(self.container_combo, 0, 1)
## Codec
codec_label = QLabel("Codec")
codec_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
grid.addWidget(codec_label, 0, 2)
self.codec_combo = QComboBox()
self.codec_combo.setToolTip("Select the video codec to use for recording")
self.codec_combo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred)
if os.sys.platform == "darwin":
self.codec_combo.addItems(["h264_videotoolbox", "libx264", "hevc_videotoolbox"])
else:
self.codec_combo.addItems(["h264_nvenc", "libx264", "hevc_nvenc"])
self.codec_combo.setCurrentText("libx264")
# Optional: a modest minimum content length helps prevent jitter
self.codec_combo.setMinimumContentsLength(6)
self.codec_combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
grid.addWidget(self.codec_combo, 0, 3)
## CRF
crf_label = QLabel("CRF")
crf_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred)
grid.addWidget(crf_label, 0, 4)
self.crf_spin = QSpinBox()
self.crf_spin.setRange(0, 51) # FFmpeg CRF range for x264/x265
self.crf_spin.setValue(RecordingSettings().crf)
self.crf_spin.setToolTip("Constant Rate Factor (0 = lossless, 51 = worst)")
self.crf_spin.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred)
grid.addWidget(self.crf_spin, 0, 5)
form.addRow(grid)
# Record with overlays
self.record_with_overlays_checkbox = QCheckBox("Record video with overlays")
self.record_with_overlays_checkbox.setToolTip(
"Enable to include pose overlays in recorded video (keypoints & bounding boxes)"
)
self.record_with_overlays_checkbox.setChecked(False)
form.addRow(self.record_with_overlays_checkbox)
# Wrap recording buttons in a widget to prevent shifting
recording_button_widget = QWidget()
buttons = QHBoxLayout(recording_button_widget)
buttons.setContentsMargins(0, 0, 0, 0)
self.start_record_button = QPushButton("Start recording")
self.start_record_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogYesButton))
self.start_record_button.setMinimumWidth(150)
buttons.addWidget(self.start_record_button)
self.stop_record_button = QPushButton("Stop recording")
self.stop_record_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogNoButton))
self.stop_record_button.setEnabled(False)
self.stop_record_button.setMinimumWidth(150)
buttons.addWidget(self.stop_record_button)
form.addRow(recording_button_widget)
# Add "Open folder" button
self.open_rec_folder_button = QPushButton("Open recording folder")
self.open_rec_folder_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self.open_rec_folder_button.clicked.connect(self._action_open_recording_folder)
form.addRow(self.open_rec_folder_button)
return group
def _build_viz_group(self) -> QGroupBox:
group = QGroupBox("Visualization")
form = QFormLayout(group)
self.show_predictions_checkbox = QCheckBox("Display pose predictions")
self.show_predictions_checkbox.setChecked(True)
self.cmap_combo = color_ui.make_colormap_combo(
current=self._colormap,
tooltip="Select colormap to use when displaying keypoints (bodypart-based coloring)",
favorites_first=["turbo", "jet", "hsv"],
exclude_reversed=True,
filters={"cet_": 5}, # include only first 5 colormaps from the 'cet_' family to avoid redundant options
include_icons=True,
sizing=color_ui.ComboSizing(min_width=80, max_width=200, popup_extra_padding=40),
)
keypoints_settings = lyts.make_two_field_row(
"Keypoint colormap: ",
self.cmap_combo,
None,
self.show_predictions_checkbox,
key_width=120,
left_stretch=0,
right_stretch=0,
)
form.addRow(keypoints_settings)
self.bbox_enabled_checkbox = QCheckBox("Show bounding box")
self.bbox_enabled_checkbox.setChecked(False)
self.bbox_color_combo = color_ui.make_bbox_color_combo(
BBoxColors,
current_bgr=self._bbox_color,
include_icons=True,
tooltip="Select color for bounding box",
sizing=color_ui.ComboSizing(
min_width=80,
max_width=200,
),
)
bbox_settings = lyts.make_two_field_row(
"Bounding box color: ",
self.bbox_color_combo,
None,
self.bbox_enabled_checkbox,
key_width=120,
left_stretch=0,
right_stretch=0,
)
form.addRow(bbox_settings)
bbox_layout = QHBoxLayout()
self.bbox_x0_spin = ScrubSpinBox()
self.bbox_x0_spin.setRange(0, 7680)
self.bbox_x0_spin.setPrefix("x0:")
self.bbox_x0_spin.setValue(0)
bbox_layout.addWidget(self.bbox_x0_spin)
self.bbox_y0_spin = ScrubSpinBox()
self.bbox_y0_spin.setRange(0, 4320)
self.bbox_y0_spin.setPrefix("y0:")
self.bbox_y0_spin.setValue(0)
bbox_layout.addWidget(self.bbox_y0_spin)
self.bbox_x1_spin = ScrubSpinBox()
self.bbox_x1_spin.setRange(0, 7680)
self.bbox_x1_spin.setPrefix("x1:")
self.bbox_x1_spin.setValue(100)
bbox_layout.addWidget(self.bbox_x1_spin)
self.bbox_y1_spin = ScrubSpinBox()
self.bbox_y1_spin.setRange(0, 4320)
self.bbox_y1_spin.setPrefix("y1:")
self.bbox_y1_spin.setValue(100)
bbox_layout.addWidget(self.bbox_y1_spin)
form.addRow("Coordinates", bbox_layout)
return group
# ------------------------------------------------------------------ signals
def _connect_signals(self) -> None:
self.preview_button.clicked.connect(self._start_preview)
self.stop_preview_button.clicked.connect(self._stop_preview)
self.start_record_button.clicked.connect(self._start_recording)
self.stop_record_button.clicked.connect(self._stop_recording)
self.start_inference_button.clicked.connect(self._start_inference)
self.stop_inference_button.clicked.connect(lambda: self._stop_inference())
self.show_predictions_checkbox.stateChanged.connect(self._on_show_predictions_changed)
# Camera config dialog
self.config_cameras_button.clicked.connect(self._open_camera_config_dialog)
# Visualization settings
## Colormap change
self.cmap_combo.currentIndexChanged.connect(self._on_colormap_changed)
## Connect bounding box controls
self.bbox_enabled_checkbox.stateChanged.connect(self._on_bbox_changed)
self.bbox_x0_spin.valueChanged.connect(self._on_bbox_changed)
self.bbox_y0_spin.valueChanged.connect(self._on_bbox_changed)
self.bbox_x1_spin.valueChanged.connect(self._on_bbox_changed)
self.bbox_y1_spin.valueChanged.connect(self._on_bbox_changed)
self.bbox_color_combo.currentIndexChanged.connect(self._on_bbox_color_changed)
# Multi-camera controller signals (used for both single and multi-camera modes)
self.multi_camera_controller.frame_ready.connect(self._on_multi_frame_ready)
self.multi_camera_controller.all_started.connect(self._on_multi_camera_started)
self.multi_camera_controller.all_stopped.connect(self._on_multi_camera_stopped)
self.multi_camera_controller.camera_error.connect(self._on_multi_camera_error)
self.multi_camera_controller.initialization_failed.connect(self._on_multi_camera_initialization_failed)
# DLC processor signals
self._dlc.pose_ready.connect(self._on_pose_ready)
self._dlc.error.connect(self._on_dlc_error)
self._dlc.initialized.connect(self._on_dlc_initialised)
self.dlc_camera_combo.currentIndexChanged.connect(self._on_dlc_camera_changed)
self.dlc_camera_combo.currentTextChanged.connect(self.dlc_camera_combo.update_shrink_width)
# Recording settings
## Session name persistence + preview updates
if hasattr(self, "session_name_edit"):
self.session_name_edit.editingFinished.connect(self._on_session_name_editing_finished)
if hasattr(self, "use_timestamp_checkbox"):
self.use_timestamp_checkbox.stateChanged.connect(self._on_use_timestamp_changed)
if hasattr(self, "output_directory_edit"):
self.output_directory_edit.textChanged.connect(lambda _t: self._update_recording_path_preview())
if hasattr(self, "filename_edit"):
self.filename_edit.textChanged.connect(lambda _t: self._update_recording_path_preview())
if hasattr(self, "container_combo"):
self.container_combo.currentTextChanged.connect(lambda _t: self._update_recording_path_preview())
# ------------------------------------------------------------------
# Config
def _apply_config(self, config: ApplicationSettings) -> None:
# Update active cameras label
self._update_active_cameras_label()
# Set DLC settings from config
dlc = config.dlc
resolved_model_path = self._model_path_store.resolve(dlc.model_path)
self.model_path_edit.setText(resolved_model_path)
# self.additional_options_edit.setPlainText(json.dumps(dlc.additional_options, indent=2))
# Set recording settings from config
recording = config.recording
self.output_directory_edit.setText(recording.directory)
self.filename_edit.setText(recording.filename)
self.container_combo.setCurrentText(recording.container)
codec_index = self.codec_combo.findText(recording.codec)
if codec_index >= 0:
self.codec_combo.setCurrentIndex(codec_index)
else:
self.codec_combo.addItem(recording.codec)
self.codec_combo.setCurrentIndex(self.codec_combo.count() - 1)
self.crf_spin.setValue(int(recording.crf))
## Restore persisted session name if empty
if hasattr(self, "session_name_edit"):
if not self.session_name_edit.text().strip():
persisted = self._settings_store.get_session_name()
if persisted:
self.session_name_edit.setText(persisted)
## Restore "Use timestamp" checkbox state
if hasattr(self, "use_timestamp_checkbox"):
self.use_timestamp_checkbox.setChecked(self._settings_store.get_use_timestamp(default=True))
# Set bounding box settings from config
bbox = config.bbox
self.bbox_enabled_checkbox.setChecked(bbox.enabled)
self.bbox_x0_spin.setValue(bbox.x0)
self.bbox_y0_spin.setValue(bbox.y0)
self.bbox_x1_spin.setValue(bbox.x1)
self.bbox_y1_spin.setValue(bbox.y1)
# Set visualization settings from config
viz = config.visualization
self._p_cutoff = viz.p_cutoff
self._colormap = viz.colormap
if hasattr(self, "cmap_combo"):
color_ui.set_cmap_combo_from_name(self.cmap_combo, self._colormap, fallback="viridis")
self._bbox_color = viz.get_bbox_color_bgr()
if hasattr(self, "bbox_color_combo"):
color_ui.set_bbox_combo_from_bgr(self.bbox_color_combo, self._bbox_color)
# Update DLC camera list
self._refresh_dlc_camera_list()
# Update recording path preview
self._update_recording_path_preview()
def _current_config(self) -> ApplicationSettings:
# Get the first camera from multi-camera config for backward compatibility
active_cameras = self._config.multi_camera.get_active_cameras()
camera = active_cameras[0] if active_cameras else CameraSettings()
return ApplicationSettings(
camera=camera,
multi_camera=self._config.multi_camera,
dlc=self._dlc_settings_from_ui(),
recording=self._recording_settings_from_ui(),
bbox=self._bbox_settings_from_ui(),
visualization=self._visualization_settings_from_ui(),
)
def _parse_json(self, value: str) -> dict:
text = value.strip()
if not text:
return {}
return json.loads(text)
def _dlc_settings_from_ui(self) -> DLCProcessorSettings:
model_path = self.model_path_edit.text().strip()
if Path(model_path).exists() and Path(model_path).suffix == ".pb":
# IMPORTANT NOTE: DLClive expects a directory for TensorFlow models,
# so if user selects a .pb file, we should pass the parent directory to DLCLive
model_path = str(Path(model_path).parent)
if model_path == "":
raise ValueError("Model path cannot be empty. Please enter a valid path to a DLCLive model file.")
try:
model_bknd = DLCLiveProcessor.get_model_backend(model_path)
except Exception as e:
raise RuntimeError(
"Could not determine model backend from path. "
"Please ensure the model file is valid and has an appropriate extension "
"(.pt, .pth for PyTorch or model directory for TensorFlow)."
) from e
return DLCProcessorSettings(
model_path=model_path,
model_directory=self._config.dlc.model_directory, # Preserve from config
device=self._config.dlc.device, # Preserve from config
dynamic=self._config.dlc.dynamic, # Preserve from config
resize=self._config.dlc.resize, # Preserve from config
precision=self._config.dlc.precision, # Preserve from config
model_type=model_bknd,
# additional_options=self._parse_json(self.additional_options_edit.toPlainText()),
)
def _recording_settings_from_ui(self) -> RecordingSettings:
return RecordingSettings(
enabled=True, # Always enabled - recording controlled by button
directory=self.output_directory_edit.text().strip(),
filename=self.filename_edit.text().strip() or "session.mp4",
container=self.container_combo.currentText().strip() or "mp4",
codec=self.codec_combo.currentText().strip() or "libx264",
crf=int(self.crf_spin.value()),
)
def _bbox_settings_from_ui(self) -> BoundingBoxSettings:
return BoundingBoxSettings(
enabled=self.bbox_enabled_checkbox.isChecked(),
x0=self.bbox_x0_spin.value(),
y0=self.bbox_y0_spin.value(),
x1=self.bbox_x1_spin.value(),
y1=self.bbox_y1_spin.value(),
)
def _visualization_settings_from_ui(self) -> VisualizationSettings:
return VisualizationSettings(
p_cutoff=self._p_cutoff,
colormap=self._colormap,
bbox_color=self._bbox_color,
)
# ------------------------------------------------------------------
# Actions
def _action_load_config(self) -> None:
file_name, _ = QFileDialog.getOpenFileName(self, "Load configuration", str(Path.home()), "JSON files (*.json)")
if not file_name:
return
try:
config = ApplicationSettings.load(file_name)
except Exception as exc: # pragma: no cover - GUI interaction
self._show_error(str(exc))
return
self._settings_store.set_last_config_path(file_name)
self._settings_store.save_full_config_snapshot(config)
self._config = config
self._config_path = Path(file_name)
self._apply_config(config)
self.statusBar().showMessage(f"Loaded configuration: {file_name}", 5000)
# Validate cameras after loading
self._validate_configured_cameras()
def _action_save_config(self) -> None:
if self._config_path is None:
self._action_save_config_as()
return
self._save_config_to_path(self._config_path)
def _action_save_config_as(self) -> None:
file_name, _ = QFileDialog.getSaveFileName(self, "Save configuration", str(Path.home()), "JSON files (*.json)")
if not file_name:
return
path = Path(file_name)
if path.suffix.lower() != ".json":
path = path.with_suffix(".json")
self._config_path = path
self._save_config_to_path(path)
def _save_config_to_path(self, path: Path) -> None:
try:
config = self._current_config()
config.save(path)
self._settings_store.set_last_config_path(str(path))
self._settings_store.save_full_config_snapshot(config)
except Exception as exc: # pragma: no cover - GUI interaction
self._show_error(str(exc))
return
self.statusBar().showMessage(f"Saved configuration to {path}", 5000)
def _action_browse_model(self) -> None:
# Prefer persisted last-used directory, then config.dlc.model_directory, then home
start_dir = self._model_path_store.suggest_start_dir(self._config.dlc.model_directory)
preselect = self._model_path_store.suggest_selected_file()
dlg = QFileDialog(self, "Select DLCLive model file")
dlg.setFileMode(QFileDialog.FileMode.ExistingFile)
dlg.setNameFilters(
[
"Model files (*.pt *.pth)",
"PyTorch models (*.pt *.pth)",
"TensorFlow models (*.pb)",
]
)
dlg.setDirectory(start_dir)
# Preselect last used model if it exists (optional but nice)
if preselect:
dlg.selectFile(preselect)
if dlg.exec():