Skip to content

dialog

sleap.gui.learning.dialog

Dialogs for running training and/or inference in GUI.

Classes:

Name Description
LearningDialog

Dialog for running training and/or inference.

TrainingEditorWidget

Dialog for viewing and modifying training profiles (model hyperparameters).

LearningDialog

Bases: QDialog

Dialog for running training and/or inference.

The dialog shows tabs for configuring the pipeline ( 🇵🇾class:MainTabWidget) and, depending on the pipeline, for each specific model (🇵🇾class:TrainingEditorWidget).

In training mode, the model hyperpameters are editable unless you're using a trained model; they are read-only in inference mode.

Parameters:

Name Type Description Default
mode Text

either "training" or "inference".

required
labels_filename Text

path to labels file, used for default location to save models.

required
labels Optional[Labels]

the Labels object (can also be loaded from given filename)

None
skeleton Optional[Skeleton]

the Skeleton object (can also be taken from Labels), used for list of nodes for (e.g.) selecting anchor node

None

Methods:

Name Description
add_tab

Add a tab to the dialog, creating the widget lazily if needed.

adjust_initial_size

Set initial dialog size based on mode and screen size.

closeEvent

Handle dialog close event.

connect_signals

Connect valueChanged signals for pipeline and any existing tabs.

copy

Copy scripts and configs to clipboard

disconnect_signals

Disconnect valueChanged signals from pipeline and tabs.

export_package

Export training job package.

get_items_for_inference

Build inference items from current selection.

get_selected_frames_to_predict

Get frames to predict based on user selection.

make_tabs

Initialize tab tracking without creating widgets yet (lazy loading).

run

Run with current dialog settings.

save

Save scripts and configs to run pipeline.

showEvent

Handle dialog show event.

update_file_lists

Update config file lists for all currently shown tabs.

update_loaded_config

Update a loaded preset config with values from the training editor.

Attributes:

Name Type Description
frame_selection Dict[str, Dict[Video, List[int]]]

Returns dictionary with frames that user has selected for learning.

Source code in sleap/gui/learning/dialog.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
class LearningDialog(QtWidgets.QDialog):
    """
    Dialog for running training and/or inference.

    The dialog shows tabs for configuring the pipeline (
    :py:class:`MainTabWidget`) and, depending on the pipeline, for
    each specific model (:py:class:`TrainingEditorWidget`).

    In training mode, the model hyperpameters are editable unless you're using
    a trained model; they are read-only in inference mode.

    Arguments:
        mode: either "training" or "inference".
        labels_filename: path to labels file, used for default location to
            save models.
        labels: the `Labels` object (can also be loaded from given filename)
        skeleton: the `Skeleton` object (can also be taken from `Labels`), used
            for list of nodes for (e.g.) selecting anchor node
    """

    _handle_learning_finished = QtCore.Signal(int)
    navigate_to_instance = QtCore.Signal(
        int, int, int
    )  # video_idx, frame_idx, instance_idx

    # Class-level cache for pipeline tab form state.
    # Persists across dialog sessions so values are restored after Cancel.
    # Key: (mode, labels_filename, tab_name), Value: form data dict
    _cached_tab_state: Dict[tuple, dict] = {}

    def __init__(
        self,
        mode: Text,
        labels_filename: Text,
        labels: Optional[Labels] = None,
        skeleton: Optional["Skeleton"] = None,
        parent=None,
        *args,
        **kwargs,
    ):
        super(LearningDialog, self).__init__(parent)

        # Set window title based on mode
        mode_title = "Training" if mode == "training" else "Inference"
        self.setWindowTitle(
            f"{mode_title} Configuration - SLEAP v{sleap.version.__version__}"
        )

        if labels is None:
            labels = load_file(labels_filename)

        if skeleton is None and labels.skeletons:
            skeleton = labels.skeletons[0]

        self.mode = mode
        self.labels_filename = labels_filename
        self.labels = labels
        self.skeleton = skeleton

        self._frame_selection = None

        self.current_pipeline = ""

        self.tabs: Dict[str, TrainingEditorWidget] = dict()
        self.shown_tab_names = []

        self._cfg_getter = configs.TrainingConfigsGetter.make_from_labels_filename(
            labels_filename=self.labels_filename
        )

        # Layout for buttons (manual layout for consistent cross-platform ordering)
        self.copy_button = QtWidgets.QPushButton("Copy to clipboard")
        self.save_button = QtWidgets.QPushButton("Save configuration files...")
        self.export_button = QtWidgets.QPushButton("Export training job package...")
        self.cancel_button = QtWidgets.QPushButton("Cancel")
        self.run_button = QtWidgets.QPushButton("Run")

        # Disable auto-default on all buttons except Run to prevent accidental defaults
        self.copy_button.setAutoDefault(False)
        self.save_button.setAutoDefault(False)
        self.export_button.setAutoDefault(False)
        self.cancel_button.setAutoDefault(False)

        self.copy_button.setToolTip("Copy configuration to the clipboard")
        self.save_button.setToolTip("Save scripts and configuration to run pipeline.")
        self.export_button.setToolTip(
            "Export data, configuration, and scripts for remote training and inference."
        )
        self.run_button.setToolTip("Run pipeline locally (GPU recommended).")
        self.run_button.setDefault(True)
        self.cancel_button.clicked.connect(self.reject)

        buttons_layout = QtWidgets.QHBoxLayout()
        buttons_layout.addWidget(self.copy_button)
        buttons_layout.addWidget(self.save_button)
        buttons_layout.addWidget(self.export_button)
        buttons_layout.addStretch()
        buttons_layout.addWidget(self.cancel_button)
        buttons_layout.addWidget(self.run_button)

        buttons_layout_widget = QtWidgets.QWidget()
        buttons_layout_widget.setLayout(buttons_layout)

        self.pipeline_form_widget = MainTabWidget(mode=mode, skeleton=skeleton)
        if mode == "training":
            tab_label = "Training Pipeline"
        elif mode == "inference":
            tab_label = "Inference Pipeline"
        else:
            raise ValueError(f"Invalid LearningDialog mode: {mode}")

        self.tab_widget = QtWidgets.QTabWidget()

        self.tab_widget.addTab(self.pipeline_form_widget, tab_label)
        self.make_tabs()

        self.message_widget = QtWidgets.QLabel("")
        self.message_widget.setWordWrap(True)
        # Hidden until there is something to say, so it takes no space otherwise.
        self.message_widget.setVisible(False)

        # Frame target selector is now owned by MainTabWidget
        self.frame_target_selector = self.pipeline_form_widget.frame_target_selector
        self._target_selection_user_changed = False

        # Layout for entire dialog - single scrollable area (same for both modes)
        content_widget = QtWidgets.QWidget()
        content_layout = QtWidgets.QVBoxLayout(content_widget)
        content_layout.addWidget(self.tab_widget)

        scroll_area = QtWidgets.QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setWidget(content_widget)
        scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        # Main layout: scrollable content + validation message + buttons. The
        # message widget lives outside the scroll area so warnings/errors are
        # always visible above the buttons rather than below the (scrollable) tab
        # content.
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(scroll_area)
        layout.addWidget(self.message_widget)
        layout.addWidget(buttons_layout_widget)

        self.adjust_initial_size()

        # Default to most recently trained pipeline (if there is one)
        self.set_default_pipeline_tab()

        # Connect functions to update pipeline tabs when pipeline changes
        self.pipeline_form_widget.updatePipeline.connect(self.set_pipeline)
        self.pipeline_form_widget.emitPipeline()

        self.connect_signals()

        # Track when user changes the frame target selector
        self.frame_target_selector.valueChanged.connect(
            self._on_target_selection_changed
        )

        # Connect actions for buttons
        self.copy_button.clicked.connect(self.copy)
        self.save_button.clicked.connect(lambda: self.save())
        self.export_button.clicked.connect(lambda: self.export_package())
        self.cancel_button.clicked.connect(self.reject)
        self.run_button.clicked.connect(self.run)

    def adjust_initial_size(self):
        """Set initial dialog size based on mode and screen size.

        V9 Layout: Both modes use single-column layout (no side panel)
        - Training: 880x900 (more sections, needs more height)
        - Inference: 880x850
        """
        screen = QtGui.QGuiApplication.primaryScreen().availableGeometry()

        if self.mode == "training":
            max_width = 880
            max_height = 900
        else:  # inference
            max_width = 880
            max_height = 850

        margin = 0.05  # 5% margin from screen edge

        # Calculate target width and height
        target_width = min(screen.width() - screen.width() * margin, max_width)
        target_height = min(screen.height() - screen.height() * margin, max_height)
        # Set the dialog's dimensions
        self.resize(int(target_width), int(target_height))

        # Note: minimum width is set dynamically in _update_minimum_width()
        # after tabs are added, since TrainingEditorWidget tabs may be wider
        # than the main tab.

    def _update_minimum_width(self):
        """Update dialog minimum width based on tab content.

        Called after tabs are added/changed to ensure the dialog cannot be
        resized smaller than its content requires. This is especially important
        on Windows 11 where Qt doesn't always propagate minimum size constraints
        from child widgets through scroll areas.
        """
        # Get minimum width from the tab widget which accounts for all tabs
        # Use sizeHint as it reflects the preferred size including all content
        tab_width = self.tab_widget.sizeHint().width()

        # Add margins for dialog layout and window frame decorations
        # The scroll area and content layout add some padding
        min_width = tab_width + 40

        # Floor at the main tab's requirement as a safety minimum
        min_width = max(min_width, MainTabWidget.BOX_MIN_WIDTH + 50)

        self.setMinimumWidth(min_width)

    def showEvent(self, event):
        """Handle dialog show event.

        Updates minimum width after the dialog is shown and layout is computed.
        This ensures accurate size calculations on all platforms.
        """
        super().showEvent(event)
        # Defer minimum width update to after event processing completes
        # to ensure layout is fully computed
        QtCore.QTimer.singleShot(0, self._update_minimum_width)

    def closeEvent(self, event):
        """Handle dialog close event.

        Saves current form state for all pipeline tabs before closing.
        This allows values to persist across Cancel operations - when the
        dialog is reopened, the cached values are restored.
        """
        # Save form state for all initialized tabs
        for tab_name, tab_widget in self.tabs.items():
            cache_key = (self.mode, self.labels_filename, tab_name)
            LearningDialog._cached_tab_state[cache_key] = tab_widget.get_all_form_data()

        super().closeEvent(event)

    def update_file_lists(self):
        """Update config file lists for all currently shown tabs.

        With lazy tab creation, we only update tabs that are currently visible.
        Tabs that haven't been created yet will get their file lists updated
        when they're first initialized in _ensure_tab_initialized().
        """
        self._cfg_getter.update()
        # Only update tabs that are currently shown (and thus initialized)
        for tab_name in self.shown_tab_names:
            if tab_name in self.tabs:
                self.tabs[tab_name].update_file_list()

    @staticmethod
    def count_total_frames_for_selection_option(
        videos_frames: Dict[Video, List[int]],
    ) -> int:
        if not videos_frames:
            return 0

        count = 0
        for frame_list in videos_frames.values():
            # Check for [X, Y) range given as (X, -Y) tuple
            if len(frame_list) == 2 and frame_list[1] < 0:
                count += -frame_list[1] - frame_list[0]
            elif frame_list != (0, 0):
                count += len(frame_list)

        return count

    @property
    def frame_selection(self) -> Dict[str, Dict[Video, List[int]]]:
        """
        Returns dictionary with frames that user has selected for learning.
        """
        return self._frame_selection

    @frame_selection.setter
    def frame_selection(self, frame_selection: Dict[str, Dict[Video, List[int]]]):
        """Sets options of frames on which to run learning."""
        self._frame_selection = frame_selection

        # Update frame target selector with options
        self._update_frame_target_selector()

    def _update_frame_target_selector(self):
        """Update frame target selector widget with current frame selection options."""
        if self._frame_selection is None:
            return

        # Build options for the new selector
        options = {}

        # Calculate frame counts for each option
        frame_count = self.count_total_frames_for_selection_option(
            self._frame_selection.get("frame", {})
        )
        options["frame"] = FrameTargetOption(
            key="frame",
            label="Current frame",
            description="Predict on just this frame",
            frame_count=frame_count,
        )

        if "clip" in self._frame_selection:
            frame_count = self.count_total_frames_for_selection_option(
                self._frame_selection["clip"]
            )
            options["clip"] = FrameTargetOption(
                key="clip",
                label="Selected clip",
                description="Predict on the frame range you selected",
                frame_count=frame_count,
                available=frame_count > 0,
            )

        if "video" in self._frame_selection:
            frame_count = self.count_total_frames_for_selection_option(
                self._frame_selection["video"]
            )
            options["video"] = FrameTargetOption(
                key="video",
                label="Entire video",
                description="Predict on all frames in current video",
                frame_count=frame_count,
            )

        if "all_videos" in self._frame_selection and len(self.labels.videos) > 1:
            frame_count = self.count_total_frames_for_selection_option(
                self._frame_selection["all_videos"]
            )
            options["all_videos"] = FrameTargetOption(
                key="all_videos",
                label="All videos",
                description="Predict on every frame across all videos",
                frame_count=frame_count,
            )

        # For random sample options, use sampling logic with default sample count
        # The actual count will be updated when settings change
        default_sample_count = 20

        if "random_video" in self._frame_selection:
            frame_count = self._sample_frames_from_pool(
                self._frame_selection["random_video"],
                default_sample_count,
                exclude_user_labeled=False,
            )
            options["random_video"] = FrameTargetOption(
                key="random_video",
                label="Random sample (current video)",
                description="Random frames from current video",
                frame_count=frame_count,
            )

        if "random" in self._frame_selection:
            frame_count = self._sample_frames_from_pool(
                self._frame_selection["random"],
                default_sample_count,
                exclude_user_labeled=False,
            )
            options["random"] = FrameTargetOption(
                key="random",
                label="Random sample (all videos)",
                description="Random frames from all videos",
                frame_count=frame_count,
            )

        if "suggestions" in self._frame_selection:
            frame_count = self.count_total_frames_for_selection_option(
                self._frame_selection["suggestions"]
            )
            if frame_count > 0:
                options["suggestions"] = FrameTargetOption(
                    key="suggestions",
                    label="Suggestions",
                    description="Frames in the Labeling Suggestions list",
                    frame_count=frame_count,
                )

        if "user" in self._frame_selection:
            frame_count = self.count_total_frames_for_selection_option(
                self._frame_selection["user"]
            )
            if frame_count > 0:
                options["user_labeled"] = FrameTargetOption(
                    key="user_labeled",
                    label="User labeled",
                    description="Frames you've annotated (for evaluation)",
                    frame_count=frame_count,
                )

        if "predicted" in self._frame_selection:
            frame_count = self.count_total_frames_for_selection_option(
                self._frame_selection["predicted"]
            )
            if frame_count > 0:
                options["predicted"] = FrameTargetOption(
                    key="predicted",
                    label="Frames with predictions",
                    description="Only frames that already have predictions",
                    frame_count=frame_count,
                )

        # Add "nothing" option for training mode only
        if self.mode == "training":
            options = {
                "nothing": FrameTargetOption(
                    key="nothing",
                    label="Nothing",
                    description="Skip predictions, training only",
                    frame_count=0,
                    training_only=True,
                ),
                **options,
            }

        self.frame_target_selector.set_options(options)

        # Set default selection based on precedence rules
        self._set_frame_target_default(options)

    def _set_frame_target_default(self, options: Dict[str, FrameTargetOption]):
        """Set default frame target selection based on precedence rules.

        Priority order:
        1. User selection this session - preserve user's explicit choice
        2. Selected clip - if a clip is selected in the timeline
        3. Suggestions - if there are suggested frames available
        4. Current frame - fallback for both training and inference
        """
        if self._target_selection_user_changed:
            # User already made a selection - keep it if still available
            current = self.frame_target_selector.get_selection()
            if current.target_key in options:
                return  # Keep current selection

        # Check for selected clip (highest priority after user selection)
        if "clip" in options and options["clip"].frame_count > 0:
            self.frame_target_selector.set_selection(
                FrameTargetSelection(target_key="clip")
            )
            return

        # Check for suggestions
        if "suggestions" in options and options["suggestions"].frame_count > 0:
            self.frame_target_selector.set_selection(
                FrameTargetSelection(target_key="suggestions")
            )
            return

        # Fallback: current frame for both training and inference
        if "frame" in options:
            self.frame_target_selector.set_selection(
                FrameTargetSelection(target_key="frame")
            )

    def _on_target_selection_changed(self):
        """Track when user explicitly changes the frame target selection.

        Also updates frame counts for random sample options based on current
        settings (sample count spinbox, exclude user labeled checkbox).
        """
        self._target_selection_user_changed = True
        self._update_random_sample_frame_counts()

    def _get_user_labeled_frame_indices(self, video: Video) -> Set[int]:
        """Get set of frame indices that have user-labeled instances for a video."""
        return {
            lf.frame_idx for lf in self.labels.user_labeled_frames if lf.video == video
        }

    def _sample_frames_from_pool(
        self,
        candidate_pool: Dict[Video, List[int]],
        sample_count: int,
        exclude_user_labeled: bool,
    ) -> int:
        """Sample frames from a candidate pool and return the sampled count.

        This implements the "filter then sample" approach, which maintains
        the target sample count when possible (unlike "sample then filter").

        Args:
            candidate_pool: Dict mapping videos to lists of candidate frame indices.
            sample_count: Target number of frames to sample.
            exclude_user_labeled: If True, exclude user-labeled frames first.

        Returns:
            The actual number of frames that would be sampled.
        """
        total_sampled = 0

        for video, candidates in candidate_pool.items():
            if not candidates:
                continue

            # Convert to set for efficient filtering
            available = set(candidates)

            # Filter out user-labeled frames if requested
            if exclude_user_labeled:
                user_labeled = self._get_user_labeled_frame_indices(video)
                available = available - user_labeled

            # Sample up to sample_count from available frames
            actual_sample_size = min(sample_count, len(available))
            total_sampled += actual_sample_size

        return total_sampled

    def _update_random_sample_frame_counts(self):
        """Update frame counts for random sample options based on current settings."""
        if self._frame_selection is None:
            return

        selection = self.frame_target_selector.get_selection()
        sample_count = selection.sample_count
        exclude_user_labeled = selection.exclude_user_labeled

        # Update random_video option
        if "random_video" in self._frame_selection:
            count = self._sample_frames_from_pool(
                self._frame_selection["random_video"],
                sample_count,
                exclude_user_labeled,
            )
            self.frame_target_selector.update_option_frame_count("random_video", count)

        # Update random (all videos) option
        if "random" in self._frame_selection:
            count = self._sample_frames_from_pool(
                self._frame_selection["random"],
                sample_count,
                exclude_user_labeled,
            )
            self.frame_target_selector.update_option_frame_count("random", count)

    def connect_signals(self):
        """Connect valueChanged signals for pipeline and any existing tabs.

        Note: With lazy tab creation, tabs may not exist yet at dialog startup.
        Signals for lazily-created tabs are connected in _ensure_tab_initialized().
        """
        self.pipeline_form_widget.valueChanged.connect(self.on_tab_data_change)

        # Only connect signals for tabs that already exist
        for head_name, tab in self.tabs.items():
            tab.valueChanged.connect(lambda n=head_name: self.on_tab_data_change(n))

    def disconnect_signals(self):
        """Disconnect valueChanged signals from pipeline and tabs.

        Uses try/except to handle cases where signals may not be connected
        (e.g., with lazy tab creation, some tabs may not exist yet).
        Warnings are suppressed since Qt prints RuntimeWarning before the
        exception can be caught.
        """
        import warnings

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=RuntimeWarning)
            try:
                self.pipeline_form_widget.valueChanged.disconnect()
            except (TypeError, RuntimeError):
                pass  # Signal was not connected

            for head_name, tab in self.tabs.items():
                try:
                    tab.valueChanged.disconnect()
                except (TypeError, RuntimeError):
                    pass  # Signal was not connected

    def make_tabs(self):
        """Initialize tab tracking without creating widgets yet (lazy loading).

        TrainingEditorWidget instances are created on-demand when tabs are first
        shown via add_tab(). This significantly reduces dialog startup time by
        avoiding creation of ~6 complex widgets upfront (~200-230ms each).
        """
        # Define available head types - widgets created lazily in add_tab()
        self._head_types = (
            "single_instance",
            "centroid",
            "centered_instance",
            "bottomup",
            "multi_class_topdown",
            "multi_class_bottomup",
        )
        # tabs dict will be populated lazily as tabs are added

    def _ensure_tab_initialized(self, head_name: str) -> "TrainingEditorWidget":
        """Create TrainingEditorWidget for a head type if not already created.

        This implements lazy tab creation - widgets are only created when the
        tab is first added to the UI, not at dialog startup.

        Args:
            head_name: The head type (e.g., "centroid", "centered_instance")

        Returns:
            The TrainingEditorWidget for this head type.
        """
        if head_name not in self.tabs:
            video = self.labels.videos[0] if self.labels else None
            widget = TrainingEditorWidget(
                video=video,
                skeleton=self.skeleton,
                head=head_name,
                cfg_getter=self._cfg_getter,
                require_trained=(self.mode == "inference"),
                labels=self.labels,
                parent_dialog=self,
            )
            self.tabs[head_name] = widget

            # Connect signals for the newly created tab
            widget.valueChanged.connect(lambda n=head_name: self.on_tab_data_change(n))

            # Update file list for the newly created tab
            widget.update_file_list()

            # Restore cached form state if available (persists across Cancel)
            cache_key = (self.mode, self.labels_filename, head_name)
            if cache_key in LearningDialog._cached_tab_state:
                cached_data = LearningDialog._cached_tab_state[cache_key]
                widget.set_fields_from_key_val_dict(cached_data)

        return self.tabs[head_name]

    def adjust_data_to_update_other_tabs(self, source_data, updated_data=None):
        if updated_data is None:
            updated_data = source_data

        anchor_part = None
        set_anchor = False

        # Map pipeline names to their anchor_part config keys
        _ci = "model_config.head_configs.centered_instance.confmaps.anchor_part"
        _mct = "model_config.head_configs.multi_class_topdown.confmaps.anchor_part"
        _cen = "model_config.head_configs.centroid.confmaps.anchor_part"
        pipeline_anchor_keys = {
            "top-down": _ci,
            "top-down-id": _mct,
            "bottom-up": _cen,
            "bottom-up-id": _cen,
        }

        # Determine the current pipeline's anchor key
        current_pipeline = source_data.get("_pipeline", "")
        current_anchor_key = pipeline_anchor_keys.get(current_pipeline)

        # First, try to get the anchor_part from the current pipeline's key
        if current_anchor_key and current_anchor_key in source_data:
            anchor_part = source_data[current_anchor_key]
            set_anchor = True
        else:
            # Fallback: check all anchor keys (for head tab changes, etc.)
            anchor_keys = [
                "model_config.head_configs.centroid.confmaps.anchor_part",
                "model_config.head_configs.centered_instance.confmaps.anchor_part",
                "model_config.head_configs.multi_class_topdown.confmaps.anchor_part",
            ]
            for key in anchor_keys:
                if key in source_data:
                    anchor_part = source_data[key]
                    set_anchor = True
                    break

        # Use None instead of empty string/list
        anchor_part = anchor_part or None

        if set_anchor:
            updated_data["model_config.head_configs.centroid.confmaps.anchor_part"] = (
                anchor_part
            )
            updated_data[
                "model_config.head_configs.centered_instance.confmaps.anchor_part"
            ] = anchor_part
            updated_data[
                "model_config.head_configs.multi_class_topdown.confmaps.anchor_part"
            ] = anchor_part

    def update_tabs_from_pipeline(self, source_data):
        self.adjust_data_to_update_other_tabs(source_data)

        for tab in self.tabs.values():
            tab.set_fields_from_key_val_dict(source_data)

    def update_tabs_from_tab(self, source_data):
        data_to_transfer = dict()
        self.adjust_data_to_update_other_tabs(source_data, data_to_transfer)

        if data_to_transfer:
            for tab in self.tabs.values():
                tab.set_fields_from_key_val_dict(data_to_transfer)

    def on_tab_data_change(self, tab_name=None):
        self.disconnect_signals()

        if tab_name is None:
            # Move data from pipeline tab to other tabs
            source_data = self.pipeline_form_widget.get_form_data()
            self.update_tabs_from_pipeline(source_data)
        else:
            # Get data from head-specific tab
            source_data = self.tabs[tab_name].get_all_form_data()

            self.update_tabs_from_tab(source_data)

            # Update pipeline tab, but filter out run_name to prevent cross-tab
            # contamination (each head has its own run_name from its base config,
            # but the pipeline run_name should remain independent)
            pipeline_data = {
                k: v for k, v in source_data.items() if k != "trainer_config.run_name"
            }
            self.pipeline_form_widget.set_form_data(pipeline_data)

        self._validate_pipeline()

        self.connect_signals()

    def get_most_recent_pipeline_trained(self) -> Text:
        recent_cfg_info = self._cfg_getter.get_first()

        if recent_cfg_info and recent_cfg_info.head_name:
            if recent_cfg_info.head_name in ("multi_class_topdown",):
                return "top-down-id"
            if recent_cfg_info.head_name in ("centroid", "centered_instance"):
                return "top-down"
            if recent_cfg_info.head_name in ("bottomup",):
                return "bottom-up"
            if recent_cfg_info.head_name in ("single_instance",):
                return "single"
            if recent_cfg_info.head_name in ("multi_class_bottomup",):
                return "bottom-up-id"
        return ""

    def _get_head_names_for_pipeline(self, pipeline: str) -> List[str]:
        """Get the head name(s) associated with a pipeline.

        Args:
            pipeline: Pipeline name (e.g., "top-down", "bottom-up").

        Returns:
            List of head names for this pipeline.
        """
        pipeline_to_heads = {
            "top-down": ["centroid", "centered_instance"],
            "bottom-up": ["bottomup"],
            "top-down-id": ["centroid", "multi_class_topdown"],
            "bottom-up-id": ["multi_class_bottomup"],
            "single": ["single_instance"],
        }
        return pipeline_to_heads.get(pipeline, [])

    def _get_trained_config_for_pipeline(
        self, pipeline: str
    ) -> Optional[configs.ConfigFileInfo]:
        """Get the most recent trained config for a pipeline.

        Args:
            pipeline: Pipeline name (e.g., "top-down", "bottom-up").

        Returns:
            ConfigFileInfo if a trained config exists, None otherwise.
        """
        head_names = self._get_head_names_for_pipeline(pipeline)
        for head_name in head_names:
            trained_cfgs = self._cfg_getter.get_filtered_configs(
                head_filter=head_name, only_trained=True
            )
            if trained_cfgs:
                return trained_cfgs[0]
        return None

    def _get_video_channels_default(self) -> str:
        """Determine default image conversion based on video channels.

        Returns:
            "RGB" if all videos are RGB, "grayscale" if all are grayscale,
            empty string if mixed or unknown.
        """
        if not self.labels or not self.labels.videos:
            return ""

        from sleap.sleap_io_adaptors.video_utils import video_get_channels

        channels_set = set()
        for video in self.labels.videos:
            try:
                channels = video_get_channels(video)
                channels_set.add(channels)
            except Exception:
                # If we can't determine channels, skip this video
                pass

        if len(channels_set) == 1:
            channels = channels_set.pop()
            if channels == 1:
                return "grayscale"
            elif channels == 3:
                return "RGB"

        return ""

    def _apply_pipeline_defaults(self, pipeline: str):
        """Apply defaults from previously trained config or video analysis.

        This sets image conversion and WandB defaults based on:
        1. Previously trained config for this pipeline (if exists)
        2. Video channel analysis (for image conversion only)

        Args:
            pipeline: Pipeline name being switched to.
        """
        if self.mode != "training":
            return

        # Try to get a trained config for this pipeline
        trained_cfg = self._get_trained_config_for_pipeline(pipeline)

        defaults_to_apply = {}
        used_trained_config = False

        if trained_cfg and trained_cfg.config:
            cfg = trained_cfg.config

            # Only use OmegaConf if cfg is actually an OmegaConf object
            if OmegaConf.is_config(cfg):
                used_trained_config = True

                # Image conversion from previous config
                ensure_rgb = OmegaConf.select(
                    cfg, "data_config.preprocessing.ensure_rgb", default=None
                )
                ensure_grayscale = OmegaConf.select(
                    cfg, "data_config.preprocessing.ensure_grayscale", default=None
                )
                if ensure_rgb:
                    defaults_to_apply["_ensure_channels"] = "RGB"
                elif ensure_grayscale:
                    defaults_to_apply["_ensure_channels"] = "grayscale"

                # WandB settings from previous config (except run_name)
                # Only apply if user is logged in to prevent enabling wandb
                # when credentials are not available (which would trigger an
                # interactive login prompt that stalls training)
                is_wandb_logged_in, _, _ = check_wandb_login_status()
                if is_wandb_logged_in:
                    use_wandb = OmegaConf.select(
                        cfg, "trainer_config.use_wandb", default=None
                    )
                    if use_wandb is not None:
                        defaults_to_apply["trainer_config.use_wandb"] = use_wandb

                    wandb_entity = OmegaConf.select(
                        cfg, "trainer_config.wandb.entity", default=None
                    )
                    if wandb_entity:
                        defaults_to_apply["trainer_config.wandb.entity"] = wandb_entity

                    wandb_project = OmegaConf.select(
                        cfg, "trainer_config.wandb.project", default=None
                    )
                    if wandb_project:
                        defaults_to_apply["trainer_config.wandb.project"] = (
                            wandb_project
                        )

                    wandb_group = OmegaConf.select(
                        cfg, "trainer_config.wandb.group", default=None
                    )
                    if wandb_group:
                        defaults_to_apply["trainer_config.wandb.group"] = wandb_group

                    save_viz = OmegaConf.select(
                        cfg, "trainer_config.wandb.save_viz_imgs_wandb", default=None
                    )
                    if save_viz is not None:
                        key = "trainer_config.wandb.save_viz_imgs_wandb"
                        defaults_to_apply[key] = save_viz

        if not used_trained_config:
            # No trained config - use video channel analysis for image conversion
            video_default = self._get_video_channels_default()
            if video_default:
                defaults_to_apply["_ensure_channels"] = video_default

        # Apply the defaults
        if defaults_to_apply:
            self.pipeline_form_widget.set_form_data(defaults_to_apply)

    def set_default_pipeline_tab(self):
        recent_pipeline_name = self.get_most_recent_pipeline_trained()
        if recent_pipeline_name:
            self.pipeline_form_widget.current_pipeline = recent_pipeline_name
        else:
            # Set default based on detection of single- vs multi-animal project.
            max_user_instance = 0
            for lf in self.labels:
                max_user_instance = max(max_user_instance, len(lf.user_instances))

            if max_user_instance == 1:
                self.pipeline_form_widget.current_pipeline = "single"
            else:
                self.pipeline_form_widget.current_pipeline = "top-down"

    def add_tab(self, tab_name):
        """Add a tab to the dialog, creating the widget lazily if needed.

        This method is idempotent - calling it multiple times with the same
        tab_name will only add the tab once (prevents issues with signal
        re-entrancy during widget construction).
        """
        # Prevent duplicate additions (can happen due to signal re-entrancy)
        if tab_name in self.shown_tab_names:
            return

        tab_labels = {
            "single_instance": "Single Instance Model Configuration",
            "centroid": "Centroid Model Configuration",
            "centered_instance": "Centered Instance Model Configuration",
            "bottomup": "Bottom-Up Model Configuration",
            "multi_class_topdown": "Top-Down-Id Model Configuration",
            "multi_class_bottomup": "Bottom-Up-Id Model Configuration",
        }
        # Mark as shown first to prevent re-entrancy issues
        self.shown_tab_names.append(tab_name)
        # Lazily create the widget if it doesn't exist yet
        widget = self._ensure_tab_initialized(tab_name)
        self.tab_widget.addTab(widget, tab_labels[tab_name])

    def remove_tabs(self):
        while self.tab_widget.count() > 1:
            self.tab_widget.removeTab(1)
        self.shown_tab_names = []

    def set_pipeline(self, pipeline: str):
        pipeline_changed = pipeline != self.current_pipeline
        if pipeline_changed:
            self.remove_tabs()
            if pipeline == "top-down":
                self.add_tab("centroid")
                self.add_tab("centered_instance")
            elif pipeline == "bottom-up":
                self.add_tab("bottomup")
            elif pipeline == "top-down-id":
                self.add_tab("centroid")
                self.add_tab("multi_class_topdown")
            elif pipeline == "bottom-up-id":
                self.add_tab("multi_class_bottomup")
            elif pipeline == "single":
                self.add_tab("single_instance")

            # Apply defaults from previous trained config or video analysis
            self._apply_pipeline_defaults(pipeline)

            # Update minimum width after tabs change (if dialog is visible)
            if self.isVisible():
                self._update_minimum_width()

        self.current_pipeline = pipeline

        self._validate_pipeline()

    def change_tab(self, tab_idx: int):
        print(tab_idx)

    def merge_pipeline_and_head_config_data(self, head_name, head_data, pipeline_data):
        # Inference-only fields that should not be merged into training config
        inference_only_fields = {
            "filter_overlapping",
            "filter_overlapping_method",
            "filter_overlapping_threshold",
        }
        for key, val in pipeline_data.items():
            # Skip GUI-only fields (not part of sleap-nn config schema)
            if key.startswith("gui."):
                continue
            # Skip inference-only fields
            if key in inference_only_fields:
                continue
            if key.startswith("model_config.head_configs."):
                key_scope = key.split(".")
                if key_scope[2] != head_name:
                    continue
            head_data[key] = val

    @staticmethod
    def update_loaded_config(
        loaded_cfg: dict, tab_cfg_key_val_dict: dict
    ):  # -> scopedkeydict.ScopedKeyDict:
        """Update a loaded preset config with values from the training editor.

        Args:
            loaded_cfg: Dict from a yaml file that was loaded from a preset or previous
                training run.
            tab_cfg_key_val_dict: A dictionary with the values extracted from the
                training editor GUI tab.

        Returns:
                    A `ScopedKeyDict` with the loaded config values overriden by the
        corresponding ones from the `tab_cfg_key_val_dict`.
        """
        # Replace params exposed in GUI with values from GUI
        for param, value in tab_cfg_key_val_dict.items():
            loaded_cfg[param] = value

        return loaded_cfg

    def get_every_head_config_data(
        self, pipeline_form_data
    ) -> List[configs.ConfigFileInfo]:
        cfg_info_list = []

        # Copy relevant data into linked fields (i.e., anchor part).
        self.adjust_data_to_update_other_tabs(pipeline_form_data)

        for tab_name in self.shown_tab_names:
            trained_cfg_info = self.tabs[tab_name].trained_config_info_to_use
            if self.tabs[tab_name].use_trained and (trained_cfg_info is not None):
                cfg_info_list.append(trained_cfg_info)

            else:
                # Get config data from GUI
                tab_cfg_key_val_dict = self.tabs[tab_name].get_all_form_data()
                self.merge_pipeline_and_head_config_data(
                    head_name=tab_name,
                    head_data=tab_cfg_key_val_dict,
                    pipeline_data=pipeline_form_data,
                )
                apply_cfg_transforms_to_key_val_dict(tab_cfg_key_val_dict)

                if trained_cfg_info is None:
                    # Config could not be loaded, just use the values from the GUI
                    loaded_cfg_scoped: dict = tab_cfg_key_val_dict
                else:
                    # Config was loaded, override with the values from the GUI
                    loaded_cfg_scoped = LearningDialog.update_loaded_config(
                        get_keyval_dict_from_omegaconf(trained_cfg_info.config),
                        tab_cfg_key_val_dict,
                    )

                # Clear wandb.name for new training runs (not resume) so sleap-nn
                # will default it to the new run_name. The wandb.name field is not
                # in the GUI form, so old values from base configs would persist.
                if not self.tabs[tab_name].resume_training:
                    loaded_cfg_scoped["trainer_config.wandb.name"] = None

                # Deserialize merged dict to object
                cfg = get_omegaconf_from_gui_form(loaded_cfg_scoped)

                if len(self.labels.tracks) > 0:
                    # For multiclass topdown, the class vectors output stride
                    # should be the max stride.
                    backbone_name = find_backbone_name_from_key_val_dict(
                        tab_cfg_key_val_dict
                    )
                    max_stride = tab_cfg_key_val_dict[
                        f"model_config.backbone_config.{backbone_name}.max_stride"
                    ]

                    # Classes should be added here to prevent value error in
                    # model since we don't add them in the training config yaml.
                    if (
                        OmegaConf.select(
                            cfg,
                            "model_config.head_configs.multi_class_bottomup",
                            default=None,
                        )
                        is not None
                    ):
                        (
                            cfg.model_config.head_configs.multi_class_bottomup.class_maps.classes
                        ) = [t.name for t in self.labels.tracks]
                    elif (
                        OmegaConf.select(
                            cfg,
                            "model_config.head_configs.multi_class_topdown",
                            default=None,
                        )
                        is not None
                    ):
                        (
                            cfg.model_config.head_configs.multi_class_topdown.class_vectors.classes
                        ) = [t.name for t in self.labels.tracks]
                        (
                            cfg.model_config.head_configs.multi_class_topdown.class_vectors.output_stride
                        ) = max_stride

                cfg_info = configs.ConfigFileInfo(config=cfg, head_name=tab_name)

                cfg_info_list.append(cfg_info)

        return cfg_info_list

    def get_selected_frames_to_predict(
        self, pipeline_form_data
    ) -> Dict[Video, List[int]]:
        """Get frames to predict based on user selection.

        Uses the new FrameTargetSelector widget for selection.

        For random sample options (random, random_video), this method performs
        the actual sampling based on sample_count and exclude_user_labeled settings.
        """
        import random

        frames_to_predict = dict()

        if self._frame_selection is None:
            return frames_to_predict

        # Get selection from new frame target selector
        selection = self.frame_target_selector.get_selection()
        target_key = selection.target_key

        # Map widget keys to frame_selection keys
        key_map = {
            "frame": "frame",
            "clip": "clip",
            "video": "video",
            "all_videos": "all_videos",
            "random": "random",
            "random_video": "random_video",
            "suggestions": "suggestions",
            "user_labeled": "user",
            "predicted": "predicted",
            "nothing": None,  # No frames to predict
        }

        frame_selection_key = key_map.get(target_key)
        if frame_selection_key and frame_selection_key in self._frame_selection:
            candidate_frames = self._frame_selection[frame_selection_key].copy()

            # For random sample options, perform actual sampling
            if target_key in ("random", "random_video"):
                sample_count = selection.sample_count
                exclude_user_labeled = selection.exclude_user_labeled

                frames_to_predict = {}
                for video, candidates in candidate_frames.items():
                    if not candidates:
                        frames_to_predict[video] = []
                        continue

                    # Convert to set for efficient filtering
                    available = set(candidates)

                    # Filter out user-labeled frames if requested
                    if exclude_user_labeled:
                        user_labeled = self._get_user_labeled_frame_indices(video)
                        available = available - user_labeled

                    # Sample from available frames
                    available_list = list(available)
                    actual_sample_size = min(sample_count, len(available_list))
                    if actual_sample_size > 0:
                        sampled = random.sample(available_list, actual_sample_size)
                        frames_to_predict[video] = sorted(sampled)
                    else:
                        frames_to_predict[video] = []
            else:
                frames_to_predict = candidate_frames

        return frames_to_predict

    def get_items_for_inference(self, pipeline_form_data) -> runners.ItemsForInference:
        """Build inference items from current selection.

        Uses the new FrameTargetSelector widget for selection.
        """
        frame_selection = self.get_selected_frames_to_predict(pipeline_form_data)
        frame_count = self.count_total_frames_for_selection_option(frame_selection)

        # Get target key from new widget
        selection = self.frame_target_selector.get_selection()
        target_key = selection.target_key

        if target_key == "user_labeled":
            items_for_inference = runners.ItemsForInference(
                items=[
                    runners.DatasetItemForInference(
                        labels_path=self.labels_filename, frame_filter="user"
                    )
                ],
                total_frame_count=frame_count,
            )
        elif target_key == "suggestions":
            items_for_inference = runners.ItemsForInference(
                items=[
                    runners.DatasetItemForInference(
                        labels_path=self.labels_filename, frame_filter="suggested"
                    )
                ],
                total_frame_count=frame_count,
            )
        elif target_key == "predicted":
            items_for_inference = runners.ItemsForInference(
                items=[
                    runners.DatasetItemForInference(
                        labels_path=self.labels_filename, frame_filter="predicted"
                    )
                ],
                total_frame_count=frame_count,
            )
        else:
            items_for_inference = runners.ItemsForInference.from_video_frames_dict(
                video_frames_dict=frame_selection,
                total_frame_count=frame_count,
                labels_path=self.labels_filename,
                labels=self.labels,
            )
        return items_for_inference

    def _validate_id_model(self) -> bool:
        """Make sure we have instances with tracks set for ID models."""
        if not self.labels.tracks:
            return False

        found_tracks = False
        for inst in instances(labels=self.labels):
            if type(inst) == sleap.Instance and inst.track is not None:
                found_tracks = True
                break

        return found_tracks

    def _validate_pipeline(self):
        can_run = True
        message = ""

        if self.mode == "inference":
            # Make sure we have trained models for each required head.
            untrained = [
                tab_name
                for tab_name in self.shown_tab_names
                if not self.tabs[tab_name].has_trained_config_selected
            ]
            if untrained:
                can_run = False
                message = (
                    "Cannot run inference with untrained models "
                    f"({', '.join(untrained)})."
                )
                can_run = False

        # Make sure we have instances with tracks set for ID models.
        if self.mode == "training" and self.current_pipeline in (
            "top-down-id",
            "bottom-up-id",
        ):
            can_run = self._validate_id_model()
            if not can_run:
                message = "Cannot run ID model training without tracks."

        # Make sure skeleton will be valid for bottom-up inference.
        if self.mode == "training" and self.current_pipeline == "bottom-up":
            skeleton = self.labels.skeletons[0]

            if not is_arborescence(skeleton):
                message += (
                    "Cannot run bottom-up pipeline when skeleton is not an "
                    "arborescence."
                )

                # These functions return node names (strings), not Node objects
                root_names = root_nodes(skeleton)
                over_max_in_degree = in_degree_over_one(skeleton)
                cycles_var = cycles(skeleton)

                if len(root_names) > 1:
                    message += (
                        f" There are multiple root nodes: {', '.join(root_names)} "
                        "(there should be exactly one node which is not a target)."
                    )

                if over_max_in_degree:
                    message += (
                        " There are nodes which are target in multiple edges: "
                        f"{', '.join(over_max_in_degree)} (maximum in-degree should be "
                        "1).</li>"
                    )

                if cycles_var:
                    cycle_strings = []
                    for cycle in cycles_var:
                        # cycles returns node names (strings), not Node objects
                        cycle_strings.append(" &ndash;&gt; ".join(cycle))

                    message += (
                        f" There are cycles in graph: {'; '.join(cycle_strings)}."
                    )

                can_run = False

        # Non-blocking warnings.
        warnings: List[str] = []

        # Negative frames enabled but none are marked.
        if (
            self.mode == "training"
            and self.labels is not None
            and not self.labels.negative_frames
        ):
            uses_negatives = any(
                self.tabs[tab_name]
                .get_all_form_data()
                .get("data_config.use_negative_frames", False)
                for tab_name in self.shown_tab_names
                if tab_name in self.tabs
            )
            if uses_negatives:
                warnings.append(
                    'The "Use Negative Frames" option is enabled, but no frames '
                    "are marked as negative, so it will have no effect. Mark "
                    "frames in the labeling window with Labels &gt; Mark Frame as "
                    "Negative (N)."
                )

        # Per-head crop size / input scaling warnings (top-down models).
        if self.mode == "training":
            for tab_name in self.shown_tab_names:
                tab = self.tabs.get(tab_name)
                if tab is not None:
                    warnings.extend(tab.get_config_warnings())

        # Compose the message with a bold colored header so errors/warnings stand
        # out above the buttons. Colors are mid-tones that stay legible on both
        # light and dark themes; no background box (which doesn't adapt to theme).
        sections = []
        if not can_run and message:
            sections.append(
                '<span style="color:#e74c3c; font-weight:bold; font-size:14px;">'
                "&#9888; CANNOT RUN</span>"
                f'<div style="margin-top:2px;">{message}</div>'
            )
        if warnings:
            body = "".join(f"&#8226;&nbsp;{w}<br/>" for w in warnings)
            sections.append(
                '<span style="color:#e67e22; font-weight:bold; font-size:14px;">'
                "&#9888; WARNING</span>"
                f'<div style="margin-top:2px;">{body}</div>'
            )

        banner = (
            '<div style="line-height:135%;">' + "<br/>".join(sections) + "</div>"
            if sections
            else ""
        )

        self.message_widget.setText(banner)
        self.message_widget.setVisible(bool(banner))
        self.run_button.setEnabled(can_run)

    def run(self):
        """Run with current dialog settings."""
        # Get selection from new widget
        selection = self.frame_target_selector.get_selection()

        pipeline_form_data = self.pipeline_form_widget.get_form_data()

        # Add prediction mode to pipeline form data for the runner
        pipeline_form_data["_prediction_mode"] = selection.prediction_mode

        items_for_inference = self.get_items_for_inference(pipeline_form_data)

        config_info_list = self.get_every_head_config_data(pipeline_form_data)

        # Close the dialog now that we have the data from it
        self.accept()

        # Run training/learning pipeline using the TrainingJobs
        new_counts = runners.run_learning_pipeline(
            labels_filename=self.labels_filename,
            labels=self.labels,
            config_info_list=config_info_list,
            inference_params=pipeline_form_data,
            items_for_inference=items_for_inference,
        )

        self._handle_learning_finished.emit(new_counts)
        # Note: The inference progress dialog now shows the completion message
        # with frame counts, so we don't need a separate popup here.

    def copy(self):
        """Copy scripts and configs to clipboard"""

        # Get all info from dialog
        pipeline_form_data = self.pipeline_form_widget.get_form_data()
        config_info_list = self.get_every_head_config_data(pipeline_form_data)

        # Format information for each tab in dialog
        # output = [OmegaConf.to_yaml(pipeline_form_data)] # TODO:cfg:
        output = []
        for config_info in config_info_list:
            config_info = config_info.config
            # convert to sleap-nn cfg (yaml)
            try:
                from sleap_nn.config.training_job_config import verify_training_cfg

                config_info = filter_cfg(config_info)
                cfg = verify_training_cfg(config_info)
                cfg.data_config.train_labels_path = [self.labels_filename]
                output.append(OmegaConf.to_yaml(cfg))
            except ImportError:
                show_sleap_nn_installation_message()
                print(
                    "sleap-nn is not installed. This appears to be GUI-only install."
                    "To enable training, please install SLEAP with the 'nn' dependency."
                    "See the installation guide: https://docs.sleap.ai/latest/installation/"
                )

        output = "\n".join(output)
        # Set the clipboard text
        clipboard = QtWidgets.QApplication.clipboard()
        clipboard.setText(output)

    def save(
        self, output_dir: Optional[str] = None, labels_filename: Optional[str] = None
    ):
        """Save scripts and configs to run pipeline."""
        if output_dir is None or not output_dir:
            labels_fn = Path(self.labels_filename)
            models_dir = Path(labels_fn.parent, "models")
            output_dir = FileDialog.openDir(
                None,
                dir=models_dir.as_posix(),
                caption="Select directory to save scripts",
            )

            if not output_dir:
                return

        pipeline_form_data = self.pipeline_form_widget.get_form_data()
        items_for_inference = self.get_items_for_inference(pipeline_form_data)
        config_info_list = self.get_every_head_config_data(pipeline_form_data)

        if labels_filename is None:
            labels_filename = self.labels_filename

        runners.write_pipeline_files(
            output_dir=output_dir,
            labels_filename=labels_filename,
            config_info_list=config_info_list,
            inference_params=pipeline_form_data,
            items_for_inference=items_for_inference,
            num_user_labeled_frames=len(self.labels.user_labeled_frames),
        )

    def export_package(self, output_path: Optional[str] = None, gui: bool = True):
        """Export training job package."""
        # TODO: Warn if self.mode != "training"?
        if output_path is None or not output_path:
            # Prompt for output path.
            output_path, _ = FileDialog.save(
                caption="Export Training Job Package...",
                dir=f"{self.labels_filename}.training_job.zip",
                filter="Training Job Package (*.zip)",
            )
            if len(output_path) == 0:
                return

        # Create temp dir before packaging.
        tmp_dir = tempfile.TemporaryDirectory()

        # Remove the temp dir when program exits in case something goes wrong.
        # atexit.register(shutil.rmtree, tmp_dir.name, ignore_errors=True)

        # Check if we need to include suggestions.
        include_suggestions = False
        items_for_inference = self.get_items_for_inference(
            self.pipeline_form_widget.get_form_data()
        )
        for item in items_for_inference.items:
            if (
                isinstance(item, runners.DatasetItemForInference)
                and item.frame_filter == "suggested"
            ):
                include_suggestions = True

        # Save dataset with images.
        labels_pkg_filename = str(
            Path(self.labels_filename).with_suffix(".pkg.slp").name
        )
        if gui:
            ret = sleap.gui.commands.export_dataset_gui(
                self.labels,
                tmp_dir.name + "/" + labels_pkg_filename,
                all_labeled=False,
                suggested=include_suggestions,
            )
            if ret == "canceled":
                # Quit if user canceled during export.
                tmp_dir.cleanup()
                return
        else:
            self.labels.save(
                filename=tmp_dir.name + "/" + labels_pkg_filename,
                embed=True,
            )

        # Save config and scripts.
        self.save(tmp_dir.name, labels_filename=labels_pkg_filename)

        # Package everything.
        shutil.make_archive(
            base_name=str(Path(output_path).with_suffix("")),
            format="zip",
            root_dir=tmp_dir.name,
        )

        msg = f"Saved training job package to: {output_path}"
        print(msg)

        # Close training editor.
        self.accept()

        if gui:
            msgBox = QtWidgets.QMessageBox(text="Created training job package.")
            msgBox.setDetailedText(output_path)
            msgBox.setWindowTitle("Training Job Package")
            msgBox.addButton(QtWidgets.QMessageBox.Ok)
            openFolderButton = msgBox.addButton(
                "Open containing folder", QtWidgets.QMessageBox.ActionRole
            )
            colabButton = msgBox.addButton(
                "Go to Colab", QtWidgets.QMessageBox.ActionRole
            )
            msgBox.exec_()

            if msgBox.clickedButton() == openFolderButton:
                sleap.gui.commands.open_file(str(Path(output_path).resolve().parent))
            elif msgBox.clickedButton() == colabButton:
                # TODO: Update this to more workflow-tailored notebook.
                sleap.gui.commands.copy_to_clipboard(output_path)
                sleap.gui.commands.open_website(
                    "https://colab.research.google.com/github/talmolab/sleap/blob/develop/docs/notebooks/Training_and_inference_using_Google_Drive.ipynb"
                )

        tmp_dir.cleanup()

frame_selection property writable

Returns dictionary with frames that user has selected for learning.

add_tab(tab_name)

Add a tab to the dialog, creating the widget lazily if needed.

This method is idempotent - calling it multiple times with the same tab_name will only add the tab once (prevents issues with signal re-entrancy during widget construction).

Source code in sleap/gui/learning/dialog.py
def add_tab(self, tab_name):
    """Add a tab to the dialog, creating the widget lazily if needed.

    This method is idempotent - calling it multiple times with the same
    tab_name will only add the tab once (prevents issues with signal
    re-entrancy during widget construction).
    """
    # Prevent duplicate additions (can happen due to signal re-entrancy)
    if tab_name in self.shown_tab_names:
        return

    tab_labels = {
        "single_instance": "Single Instance Model Configuration",
        "centroid": "Centroid Model Configuration",
        "centered_instance": "Centered Instance Model Configuration",
        "bottomup": "Bottom-Up Model Configuration",
        "multi_class_topdown": "Top-Down-Id Model Configuration",
        "multi_class_bottomup": "Bottom-Up-Id Model Configuration",
    }
    # Mark as shown first to prevent re-entrancy issues
    self.shown_tab_names.append(tab_name)
    # Lazily create the widget if it doesn't exist yet
    widget = self._ensure_tab_initialized(tab_name)
    self.tab_widget.addTab(widget, tab_labels[tab_name])

adjust_initial_size()

Set initial dialog size based on mode and screen size.

V9 Layout: Both modes use single-column layout (no side panel) - Training: 880x900 (more sections, needs more height) - Inference: 880x850

Source code in sleap/gui/learning/dialog.py
def adjust_initial_size(self):
    """Set initial dialog size based on mode and screen size.

    V9 Layout: Both modes use single-column layout (no side panel)
    - Training: 880x900 (more sections, needs more height)
    - Inference: 880x850
    """
    screen = QtGui.QGuiApplication.primaryScreen().availableGeometry()

    if self.mode == "training":
        max_width = 880
        max_height = 900
    else:  # inference
        max_width = 880
        max_height = 850

    margin = 0.05  # 5% margin from screen edge

    # Calculate target width and height
    target_width = min(screen.width() - screen.width() * margin, max_width)
    target_height = min(screen.height() - screen.height() * margin, max_height)
    # Set the dialog's dimensions
    self.resize(int(target_width), int(target_height))

closeEvent(event)

Handle dialog close event.

Saves current form state for all pipeline tabs before closing. This allows values to persist across Cancel operations - when the dialog is reopened, the cached values are restored.

Source code in sleap/gui/learning/dialog.py
def closeEvent(self, event):
    """Handle dialog close event.

    Saves current form state for all pipeline tabs before closing.
    This allows values to persist across Cancel operations - when the
    dialog is reopened, the cached values are restored.
    """
    # Save form state for all initialized tabs
    for tab_name, tab_widget in self.tabs.items():
        cache_key = (self.mode, self.labels_filename, tab_name)
        LearningDialog._cached_tab_state[cache_key] = tab_widget.get_all_form_data()

    super().closeEvent(event)

connect_signals()

Connect valueChanged signals for pipeline and any existing tabs.

Note: With lazy tab creation, tabs may not exist yet at dialog startup. Signals for lazily-created tabs are connected in _ensure_tab_initialized().

Source code in sleap/gui/learning/dialog.py
def connect_signals(self):
    """Connect valueChanged signals for pipeline and any existing tabs.

    Note: With lazy tab creation, tabs may not exist yet at dialog startup.
    Signals for lazily-created tabs are connected in _ensure_tab_initialized().
    """
    self.pipeline_form_widget.valueChanged.connect(self.on_tab_data_change)

    # Only connect signals for tabs that already exist
    for head_name, tab in self.tabs.items():
        tab.valueChanged.connect(lambda n=head_name: self.on_tab_data_change(n))

copy()

Copy scripts and configs to clipboard

Source code in sleap/gui/learning/dialog.py
def copy(self):
    """Copy scripts and configs to clipboard"""

    # Get all info from dialog
    pipeline_form_data = self.pipeline_form_widget.get_form_data()
    config_info_list = self.get_every_head_config_data(pipeline_form_data)

    # Format information for each tab in dialog
    # output = [OmegaConf.to_yaml(pipeline_form_data)] # TODO:cfg:
    output = []
    for config_info in config_info_list:
        config_info = config_info.config
        # convert to sleap-nn cfg (yaml)
        try:
            from sleap_nn.config.training_job_config import verify_training_cfg

            config_info = filter_cfg(config_info)
            cfg = verify_training_cfg(config_info)
            cfg.data_config.train_labels_path = [self.labels_filename]
            output.append(OmegaConf.to_yaml(cfg))
        except ImportError:
            show_sleap_nn_installation_message()
            print(
                "sleap-nn is not installed. This appears to be GUI-only install."
                "To enable training, please install SLEAP with the 'nn' dependency."
                "See the installation guide: https://docs.sleap.ai/latest/installation/"
            )

    output = "\n".join(output)
    # Set the clipboard text
    clipboard = QtWidgets.QApplication.clipboard()
    clipboard.setText(output)

disconnect_signals()

Disconnect valueChanged signals from pipeline and tabs.

Uses try/except to handle cases where signals may not be connected (e.g., with lazy tab creation, some tabs may not exist yet). Warnings are suppressed since Qt prints RuntimeWarning before the exception can be caught.

Source code in sleap/gui/learning/dialog.py
def disconnect_signals(self):
    """Disconnect valueChanged signals from pipeline and tabs.

    Uses try/except to handle cases where signals may not be connected
    (e.g., with lazy tab creation, some tabs may not exist yet).
    Warnings are suppressed since Qt prints RuntimeWarning before the
    exception can be caught.
    """
    import warnings

    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=RuntimeWarning)
        try:
            self.pipeline_form_widget.valueChanged.disconnect()
        except (TypeError, RuntimeError):
            pass  # Signal was not connected

        for head_name, tab in self.tabs.items():
            try:
                tab.valueChanged.disconnect()
            except (TypeError, RuntimeError):
                pass  # Signal was not connected

export_package(output_path=None, gui=True)

Export training job package.

Source code in sleap/gui/learning/dialog.py
def export_package(self, output_path: Optional[str] = None, gui: bool = True):
    """Export training job package."""
    # TODO: Warn if self.mode != "training"?
    if output_path is None or not output_path:
        # Prompt for output path.
        output_path, _ = FileDialog.save(
            caption="Export Training Job Package...",
            dir=f"{self.labels_filename}.training_job.zip",
            filter="Training Job Package (*.zip)",
        )
        if len(output_path) == 0:
            return

    # Create temp dir before packaging.
    tmp_dir = tempfile.TemporaryDirectory()

    # Remove the temp dir when program exits in case something goes wrong.
    # atexit.register(shutil.rmtree, tmp_dir.name, ignore_errors=True)

    # Check if we need to include suggestions.
    include_suggestions = False
    items_for_inference = self.get_items_for_inference(
        self.pipeline_form_widget.get_form_data()
    )
    for item in items_for_inference.items:
        if (
            isinstance(item, runners.DatasetItemForInference)
            and item.frame_filter == "suggested"
        ):
            include_suggestions = True

    # Save dataset with images.
    labels_pkg_filename = str(
        Path(self.labels_filename).with_suffix(".pkg.slp").name
    )
    if gui:
        ret = sleap.gui.commands.export_dataset_gui(
            self.labels,
            tmp_dir.name + "/" + labels_pkg_filename,
            all_labeled=False,
            suggested=include_suggestions,
        )
        if ret == "canceled":
            # Quit if user canceled during export.
            tmp_dir.cleanup()
            return
    else:
        self.labels.save(
            filename=tmp_dir.name + "/" + labels_pkg_filename,
            embed=True,
        )

    # Save config and scripts.
    self.save(tmp_dir.name, labels_filename=labels_pkg_filename)

    # Package everything.
    shutil.make_archive(
        base_name=str(Path(output_path).with_suffix("")),
        format="zip",
        root_dir=tmp_dir.name,
    )

    msg = f"Saved training job package to: {output_path}"
    print(msg)

    # Close training editor.
    self.accept()

    if gui:
        msgBox = QtWidgets.QMessageBox(text="Created training job package.")
        msgBox.setDetailedText(output_path)
        msgBox.setWindowTitle("Training Job Package")
        msgBox.addButton(QtWidgets.QMessageBox.Ok)
        openFolderButton = msgBox.addButton(
            "Open containing folder", QtWidgets.QMessageBox.ActionRole
        )
        colabButton = msgBox.addButton(
            "Go to Colab", QtWidgets.QMessageBox.ActionRole
        )
        msgBox.exec_()

        if msgBox.clickedButton() == openFolderButton:
            sleap.gui.commands.open_file(str(Path(output_path).resolve().parent))
        elif msgBox.clickedButton() == colabButton:
            # TODO: Update this to more workflow-tailored notebook.
            sleap.gui.commands.copy_to_clipboard(output_path)
            sleap.gui.commands.open_website(
                "https://colab.research.google.com/github/talmolab/sleap/blob/develop/docs/notebooks/Training_and_inference_using_Google_Drive.ipynb"
            )

    tmp_dir.cleanup()

get_items_for_inference(pipeline_form_data)

Build inference items from current selection.

Uses the new FrameTargetSelector widget for selection.

Source code in sleap/gui/learning/dialog.py
def get_items_for_inference(self, pipeline_form_data) -> runners.ItemsForInference:
    """Build inference items from current selection.

    Uses the new FrameTargetSelector widget for selection.
    """
    frame_selection = self.get_selected_frames_to_predict(pipeline_form_data)
    frame_count = self.count_total_frames_for_selection_option(frame_selection)

    # Get target key from new widget
    selection = self.frame_target_selector.get_selection()
    target_key = selection.target_key

    if target_key == "user_labeled":
        items_for_inference = runners.ItemsForInference(
            items=[
                runners.DatasetItemForInference(
                    labels_path=self.labels_filename, frame_filter="user"
                )
            ],
            total_frame_count=frame_count,
        )
    elif target_key == "suggestions":
        items_for_inference = runners.ItemsForInference(
            items=[
                runners.DatasetItemForInference(
                    labels_path=self.labels_filename, frame_filter="suggested"
                )
            ],
            total_frame_count=frame_count,
        )
    elif target_key == "predicted":
        items_for_inference = runners.ItemsForInference(
            items=[
                runners.DatasetItemForInference(
                    labels_path=self.labels_filename, frame_filter="predicted"
                )
            ],
            total_frame_count=frame_count,
        )
    else:
        items_for_inference = runners.ItemsForInference.from_video_frames_dict(
            video_frames_dict=frame_selection,
            total_frame_count=frame_count,
            labels_path=self.labels_filename,
            labels=self.labels,
        )
    return items_for_inference

get_selected_frames_to_predict(pipeline_form_data)

Get frames to predict based on user selection.

Uses the new FrameTargetSelector widget for selection.

For random sample options (random, random_video), this method performs the actual sampling based on sample_count and exclude_user_labeled settings.

Source code in sleap/gui/learning/dialog.py
def get_selected_frames_to_predict(
    self, pipeline_form_data
) -> Dict[Video, List[int]]:
    """Get frames to predict based on user selection.

    Uses the new FrameTargetSelector widget for selection.

    For random sample options (random, random_video), this method performs
    the actual sampling based on sample_count and exclude_user_labeled settings.
    """
    import random

    frames_to_predict = dict()

    if self._frame_selection is None:
        return frames_to_predict

    # Get selection from new frame target selector
    selection = self.frame_target_selector.get_selection()
    target_key = selection.target_key

    # Map widget keys to frame_selection keys
    key_map = {
        "frame": "frame",
        "clip": "clip",
        "video": "video",
        "all_videos": "all_videos",
        "random": "random",
        "random_video": "random_video",
        "suggestions": "suggestions",
        "user_labeled": "user",
        "predicted": "predicted",
        "nothing": None,  # No frames to predict
    }

    frame_selection_key = key_map.get(target_key)
    if frame_selection_key and frame_selection_key in self._frame_selection:
        candidate_frames = self._frame_selection[frame_selection_key].copy()

        # For random sample options, perform actual sampling
        if target_key in ("random", "random_video"):
            sample_count = selection.sample_count
            exclude_user_labeled = selection.exclude_user_labeled

            frames_to_predict = {}
            for video, candidates in candidate_frames.items():
                if not candidates:
                    frames_to_predict[video] = []
                    continue

                # Convert to set for efficient filtering
                available = set(candidates)

                # Filter out user-labeled frames if requested
                if exclude_user_labeled:
                    user_labeled = self._get_user_labeled_frame_indices(video)
                    available = available - user_labeled

                # Sample from available frames
                available_list = list(available)
                actual_sample_size = min(sample_count, len(available_list))
                if actual_sample_size > 0:
                    sampled = random.sample(available_list, actual_sample_size)
                    frames_to_predict[video] = sorted(sampled)
                else:
                    frames_to_predict[video] = []
        else:
            frames_to_predict = candidate_frames

    return frames_to_predict

make_tabs()

Initialize tab tracking without creating widgets yet (lazy loading).

TrainingEditorWidget instances are created on-demand when tabs are first shown via add_tab(). This significantly reduces dialog startup time by avoiding creation of ~6 complex widgets upfront (~200-230ms each).

Source code in sleap/gui/learning/dialog.py
def make_tabs(self):
    """Initialize tab tracking without creating widgets yet (lazy loading).

    TrainingEditorWidget instances are created on-demand when tabs are first
    shown via add_tab(). This significantly reduces dialog startup time by
    avoiding creation of ~6 complex widgets upfront (~200-230ms each).
    """
    # Define available head types - widgets created lazily in add_tab()
    self._head_types = (
        "single_instance",
        "centroid",
        "centered_instance",
        "bottomup",
        "multi_class_topdown",
        "multi_class_bottomup",
    )

run()

Run with current dialog settings.

Source code in sleap/gui/learning/dialog.py
def run(self):
    """Run with current dialog settings."""
    # Get selection from new widget
    selection = self.frame_target_selector.get_selection()

    pipeline_form_data = self.pipeline_form_widget.get_form_data()

    # Add prediction mode to pipeline form data for the runner
    pipeline_form_data["_prediction_mode"] = selection.prediction_mode

    items_for_inference = self.get_items_for_inference(pipeline_form_data)

    config_info_list = self.get_every_head_config_data(pipeline_form_data)

    # Close the dialog now that we have the data from it
    self.accept()

    # Run training/learning pipeline using the TrainingJobs
    new_counts = runners.run_learning_pipeline(
        labels_filename=self.labels_filename,
        labels=self.labels,
        config_info_list=config_info_list,
        inference_params=pipeline_form_data,
        items_for_inference=items_for_inference,
    )

    self._handle_learning_finished.emit(new_counts)

save(output_dir=None, labels_filename=None)

Save scripts and configs to run pipeline.

Source code in sleap/gui/learning/dialog.py
def save(
    self, output_dir: Optional[str] = None, labels_filename: Optional[str] = None
):
    """Save scripts and configs to run pipeline."""
    if output_dir is None or not output_dir:
        labels_fn = Path(self.labels_filename)
        models_dir = Path(labels_fn.parent, "models")
        output_dir = FileDialog.openDir(
            None,
            dir=models_dir.as_posix(),
            caption="Select directory to save scripts",
        )

        if not output_dir:
            return

    pipeline_form_data = self.pipeline_form_widget.get_form_data()
    items_for_inference = self.get_items_for_inference(pipeline_form_data)
    config_info_list = self.get_every_head_config_data(pipeline_form_data)

    if labels_filename is None:
        labels_filename = self.labels_filename

    runners.write_pipeline_files(
        output_dir=output_dir,
        labels_filename=labels_filename,
        config_info_list=config_info_list,
        inference_params=pipeline_form_data,
        items_for_inference=items_for_inference,
        num_user_labeled_frames=len(self.labels.user_labeled_frames),
    )

showEvent(event)

Handle dialog show event.

Updates minimum width after the dialog is shown and layout is computed. This ensures accurate size calculations on all platforms.

Source code in sleap/gui/learning/dialog.py
def showEvent(self, event):
    """Handle dialog show event.

    Updates minimum width after the dialog is shown and layout is computed.
    This ensures accurate size calculations on all platforms.
    """
    super().showEvent(event)
    # Defer minimum width update to after event processing completes
    # to ensure layout is fully computed
    QtCore.QTimer.singleShot(0, self._update_minimum_width)

update_file_lists()

Update config file lists for all currently shown tabs.

With lazy tab creation, we only update tabs that are currently visible. Tabs that haven't been created yet will get their file lists updated when they're first initialized in _ensure_tab_initialized().

Source code in sleap/gui/learning/dialog.py
def update_file_lists(self):
    """Update config file lists for all currently shown tabs.

    With lazy tab creation, we only update tabs that are currently visible.
    Tabs that haven't been created yet will get their file lists updated
    when they're first initialized in _ensure_tab_initialized().
    """
    self._cfg_getter.update()
    # Only update tabs that are currently shown (and thus initialized)
    for tab_name in self.shown_tab_names:
        if tab_name in self.tabs:
            self.tabs[tab_name].update_file_list()

update_loaded_config(loaded_cfg, tab_cfg_key_val_dict) staticmethod

Update a loaded preset config with values from the training editor.

Parameters:

Name Type Description Default
loaded_cfg dict

Dict from a yaml file that was loaded from a preset or previous training run.

required
tab_cfg_key_val_dict dict

A dictionary with the values extracted from the training editor GUI tab.

required

Returns:

Type Description

A ScopedKeyDict with the loaded config values overriden by the

corresponding ones from the tab_cfg_key_val_dict.

Source code in sleap/gui/learning/dialog.py
@staticmethod
def update_loaded_config(
    loaded_cfg: dict, tab_cfg_key_val_dict: dict
):  # -> scopedkeydict.ScopedKeyDict:
    """Update a loaded preset config with values from the training editor.

    Args:
        loaded_cfg: Dict from a yaml file that was loaded from a preset or previous
            training run.
        tab_cfg_key_val_dict: A dictionary with the values extracted from the
            training editor GUI tab.

    Returns:
                A `ScopedKeyDict` with the loaded config values overriden by the
    corresponding ones from the `tab_cfg_key_val_dict`.
    """
    # Replace params exposed in GUI with values from GUI
    for param, value in tab_cfg_key_val_dict.items():
        loaded_cfg[param] = value

    return loaded_cfg

TrainingEditorWidget

Bases: QWidget

Dialog for viewing and modifying training profiles (model hyperparameters).

Parameters:

Name Type Description Default
video Optional[Video]

Video to use for receptive field preview

None
skeleton Optional[Skeleton]

Skeleton to use for node option list

None
head Optional[Text]

If given, then only show configs with specified head name

None
cfg_getter Optional[TrainingConfigsGetter]

Object to use for getting list of config files. If given, then menu of config files will be shown so user can either copy hyperameters from another profile/model, or use a model that was already trained.

None
require_trained bool

If True, then only show configs that are trained, and don't allow user to uncheck "use trained" setting. This is set when 🇵🇾class:LearningDialog is in "inference" mode.

False

Methods:

Name Description
get_config_warnings

Return inline warnings about crop size / input scaling.

Attributes:

Name Type Description
resume_training bool

Check if user wants to resume/fine-tune training.

use_trained bool

Check if user wants to use trained model without retraining.

Source code in sleap/gui/learning/dialog.py
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
class TrainingEditorWidget(QtWidgets.QWidget):
    """
    Dialog for viewing and modifying training profiles (model hyperparameters).

    Args:
        video: `Video` to use for receptive field preview
        skeleton: `Skeleton` to use for node option list
        head: If given, then only show configs with specified head name
        cfg_getter: Object to use for getting list of config files.
            If given, then menu of config files will be shown so user can
            either copy hyperameters from another profile/model, or use a model
            that was already trained.
        require_trained: If True, then only show configs that are trained,
            and don't allow user to uncheck "use trained" setting. This is set
            when :py:class:`LearningDialog` is in "inference" mode.
    """

    valueChanged = QtCore.Signal()

    def __init__(
        self,
        video: Optional[Video] = None,
        skeleton: Optional["Skeleton"] = None,
        head: Optional[Text] = None,
        cfg_getter: Optional["TrainingConfigsGetter"] = None,
        require_trained: bool = False,
        labels: Optional[Labels] = None,
        parent_dialog: Optional["LearningDialog"] = None,
        *args,
        **kwargs,
    ):
        super(TrainingEditorWidget, self).__init__()

        self._video = video
        self._labels = labels
        self._parent_dialog = parent_dialog
        self._cfg_getter = cfg_getter
        self._cfg_list_widget = None
        self._receptive_field_widget = None
        self._training_mode_group = None
        self._radio_train_scratch = None
        self._radio_use_trained = None
        self._radio_resume = None
        self._require_trained = require_trained
        self.head = head

        # Cache for the largest labeled instance bounding box (computed lazily and
        # reused across crop-size validations, see `get_config_warnings`).
        self._max_instance_bbox_size: Optional[float] = None

        yaml_name = "training_editor_form"

        self.form_widgets: Dict[str, YamlFormWidget] = dict()

        for key in ("model", "data", "augmentation", "optimization", "outputs"):
            self.form_widgets[key] = YamlFormWidget.from_name(
                yaml_name, which_form=key, title=key.title()
            )
            self.form_widgets[key].valueChanged.connect(self.emitValueChanged)

        self.form_widgets["model"].valueChanged.connect(self.update_receptive_field)
        self.form_widgets["data"].valueChanged.connect(self.update_receptive_field)
        self.form_widgets["augmentation"].valueChanged.connect(
            self.update_receptive_field
        )

        # Connect overfit mode checkbox to disable validation fraction
        self._setup_overfit_mode_toggle()

        # Connect rotation preset dropdown to enable/disable custom angle field
        self._setup_rotation_preset_toggle()

        # Connect augmentation checkboxes to show/hide their parameter fields
        self._setup_augmentation_param_toggles()

        # Connect optimization checkboxes to show/hide their parameter fields
        self._setup_optimization_param_toggles()

        # Hide crop size for non-cropping model types
        self._setup_crop_size_visibility()

        # Hide OHKM fields for centroid models (single-point prediction)
        self._setup_ohkm_visibility()

        # Hide negative-frame fields for model types that ignore them
        self._setup_negative_frames_visibility()

        # Enable the negative loss weight field only when negative frames are on
        self._setup_negative_frames_toggle()

        # Add an info button next to Input Scaling for crop-based (top-down) heads
        self._setup_input_scaling_info()

        if hasattr(skeleton, "node_names"):
            for field_name in NODE_LIST_FIELDS:
                form_name = field_name.split(".")[0]
                self.form_widgets[form_name].set_field_options(
                    ".".join(field_name.split(".")[1:]),
                    skeleton.node_names,
                )

        # crop box should be shown for centered_instance/multi_class_topdown
        show_crop_box = head in ("centered_instance", "multi_class_topdown")
        # Use labeled frame image for topdown pipeline (centroid + centered_instance)
        use_labeled_frame = head in (
            "centroid",
            "centered_instance",
            "multi_class_topdown",
        )

        if self._video or (use_labeled_frame and labels):
            self._receptive_field_widget = receptivefield.ReceptiveFieldWidget(
                self.head, show_crop_box=show_crop_box
            )
            # For topdown heads, use labeled frame image for consistency
            if use_labeled_frame and labels:
                self._receptive_field_widget.setLabels(labels, self._video)
            elif self._video:
                self._receptive_field_widget.setImage(
                    self._video.backend.read_test_frame()
                )

        self._set_head()

        # Layout for header and columns
        layout = QtWidgets.QVBoxLayout()

        # Two column layout: Data+Augmentation+Optimization | Model
        col1_layout = QtWidgets.QVBoxLayout()
        col2_layout = QtWidgets.QVBoxLayout()

        col1_layout.addWidget(self.form_widgets["data"])
        col1_layout.addWidget(self.form_widgets["augmentation"])
        col1_layout.addWidget(self.form_widgets["optimization"])
        col2_layout.addWidget(self.form_widgets["model"])

        if self._receptive_field_widget:
            col0_layout = QtWidgets.QVBoxLayout()
            col0_layout.addWidget(self._receptive_field_widget)

            # Add "Analyze Sizes" button for cropping model types
            # Button is inserted into the receptive field widget (below legend)
            if show_crop_box and labels is not None:
                self._analyze_size_button = QtWidgets.QPushButton("Analyze Sizes...")
                self._analyze_size_button.setToolTip(
                    "View the distribution of instance sizes and identify outliers"
                )
                self._analyze_size_button.clicked.connect(self._open_size_distribution)
                self._receptive_field_widget.addButtonWidget(self._analyze_size_button)
        else:
            col0_layout = None

        col_layout = QtWidgets.QHBoxLayout()
        if col0_layout:
            col_layout.addWidget(
                self._layout_widget(col0_layout),
                stretch=0,
                alignment=QtCore.Qt.AlignTop,
            )
        col_layout.addWidget(
            self._layout_widget(col1_layout), stretch=0, alignment=QtCore.Qt.AlignTop
        )
        col_layout.addWidget(
            self._layout_widget(col2_layout), stretch=0, alignment=QtCore.Qt.AlignTop
        )
        col_layout.addStretch(1)  # Push columns left, absorb extra space

        # If we have an object which gets a list of config files,
        # then we'll show a menu to allow selection from the list.
        if self._cfg_getter is not None:
            self._cfg_list_widget = configs.TrainingConfigFilesWidget(
                cfg_getter=self._cfg_getter,
                head_name=cast(str, head),  # Expect head to be a string
                require_trained=require_trained,
            )
            self._cfg_list_widget.onConfigSelection.connect(
                self.acceptSelectedConfigInfo
            )
            # self._cfg_list_widget.setDataDict.connect(
            # self.set_fields_from_key_val_dict
            # )

            layout.addWidget(self._cfg_list_widget)

        if self._require_trained:
            self._update_use_trained()
        elif self._cfg_list_widget is not None:
            # Add radio buttons for training mode selection
            # Three mutually exclusive options for how to use the selected config
            self._training_mode_group = QtWidgets.QButtonGroup(self)

            self._radio_train_scratch = QtWidgets.QRadioButton(
                "Reuse config (train from scratch)"
            )
            self._radio_resume = QtWidgets.QRadioButton("Resume training (fine-tune)")
            self._radio_use_trained = QtWidgets.QRadioButton(
                "Reuse model (don't retrain)"
            )

            # Set IDs for easier identification
            self._training_mode_group.addButton(self._radio_train_scratch, 0)
            self._training_mode_group.addButton(self._radio_resume, 1)
            self._training_mode_group.addButton(self._radio_use_trained, 2)

            # Default to training from scratch
            self._radio_train_scratch.setChecked(True)

            # Last two options only enabled when trained model is available
            self._radio_resume.setEnabled(False)
            self._radio_use_trained.setEnabled(False)

            # Layout radio buttons horizontally with minimal spacing
            radio_layout = QtWidgets.QHBoxLayout()
            radio_layout.setContentsMargins(0, 0, 0, 0)
            radio_layout.setSpacing(12)
            radio_layout.addWidget(self._radio_train_scratch)
            radio_layout.addWidget(self._radio_resume)
            radio_layout.addWidget(self._radio_use_trained)
            radio_layout.addStretch()

            radio_widget = QtWidgets.QWidget()
            radio_widget.setLayout(radio_layout)
            radio_widget.setSizePolicy(
                QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed
            )

            self._training_mode_group.buttonClicked.connect(self._update_use_trained)

            layout.addWidget(radio_widget)

        layout.addWidget(self._layout_widget(col_layout))
        self.setLayout(layout)

    @classmethod
    def from_trained_config(
        cls, cfg_info: configs.ConfigFileInfo, cfg_getter: configs.TrainingConfigsGetter
    ):
        widget = cls(
            require_trained=True, head=cfg_info.head_name, cfg_getter=cfg_getter
        )
        widget.acceptSelectedConfigInfo(cfg_info)
        widget.setWindowTitle(cfg_info.path_dir)
        return widget

    @staticmethod
    def _layout_widget(layout):
        widget = QtWidgets.QWidget()
        widget.setLayout(layout)
        return widget

    def emitValueChanged(self):
        self.valueChanged.emit()

        # When there's a config getter, we want to inform it that the data
        # has changed so that it can activate/update the "user" config
        # if self._cfg_list_widget:
        #     self._set_user_config()

    def _setup_overfit_mode_toggle(self):
        """Connect overfit mode checkbox to disable validation fraction.

        Follows the same pattern as OptionalSpinWidget.updateState().
        """
        data_form = self.form_widgets["data"]
        overfit_field_name = "data_config.use_same_data_for_val"
        val_frac_field_name = "data_config.validation_fraction"

        overfit_checkbox = data_form.fields.get(overfit_field_name)
        val_frac_widget = data_form.fields.get(val_frac_field_name)

        if overfit_checkbox is not None and val_frac_widget is not None:

            def update_state():
                val_frac_widget.setDisabled(overfit_checkbox.isChecked())

            overfit_checkbox.stateChanged.connect(update_state)
            update_state()

    def _setup_rotation_preset_toggle(self):
        """Connect rotation preset dropdown to show/hide custom angle field.

        When a preset (Off, ±15°, ±180°) is selected, the custom angle field is
        hidden. When "Custom" is selected, the field is shown.
        """
        aug_form = self.form_widgets["augmentation"]
        form_layout = aug_form.form_layout
        preset_field = aug_form.fields.get("_rotation_preset")
        custom_field = aug_form.fields.get("_rotation_custom_angle")

        if preset_field is not None and custom_field is not None:
            # Get the label for the custom field
            custom_label = form_layout.labelForField(custom_field)

            def update_state():
                is_custom = preset_field.value() == "Custom"
                custom_field.setVisible(is_custom)
                if custom_label is not None:
                    custom_label.setVisible(is_custom)

            preset_field.valueChanged.connect(update_state)
            update_state()  # Set initial state

    def _setup_augmentation_param_toggles(self):
        """Connect augmentation checkboxes to show/hide their parameter fields.

        When an augmentation checkbox is unchecked, its parameter fields are hidden
        to reduce visual clutter. The fields are shown when the checkbox is checked.
        """
        aug_form = self.form_widgets["augmentation"]
        form_layout = aug_form.form_layout

        # Define which checkbox controls which parameter fields
        toggle_groups = {
            "_scale_enabled": [
                "data_config.augmentation_config.geometric.scale_min",
                "data_config.augmentation_config.geometric.scale_max",
            ],
            "_uniform_noise_enabled": [
                "data_config.augmentation_config.intensity.uniform_noise_min",
                "data_config.augmentation_config.intensity.uniform_noise_max",
            ],
            "_gaussian_noise_enabled": [
                "data_config.augmentation_config.intensity.gaussian_noise_mean",
                "data_config.augmentation_config.intensity.gaussian_noise_std",
            ],
            "_contrast_enabled": [
                "data_config.augmentation_config.intensity.contrast_min",
                "data_config.augmentation_config.intensity.contrast_max",
            ],
            "_brightness_enabled": [
                "data_config.augmentation_config.intensity.brightness_min",
                "data_config.augmentation_config.intensity.brightness_max",
            ],
        }

        for checkbox_name, param_fields in toggle_groups.items():
            checkbox = aug_form.fields.get(checkbox_name)
            if checkbox is None:
                continue

            # Collect the parameter field widgets and their labels
            param_widgets = []
            for field_name in param_fields:
                field = aug_form.fields.get(field_name)
                if field is not None:
                    # Get the label for this field from the form layout
                    label = form_layout.labelForField(field)
                    param_widgets.append((field, label))

            if not param_widgets:
                continue

            # Create update function that captures the widgets
            def make_update_visibility(widgets):
                def update_visibility(state):
                    visible = bool(state)
                    for field, label in widgets:
                        field.setVisible(visible)
                        if label is not None:
                            label.setVisible(visible)

                return update_visibility

            update_fn = make_update_visibility(param_widgets)
            checkbox.stateChanged.connect(update_fn)
            update_fn(checkbox.isChecked())  # Set initial state

    def _setup_optimization_param_toggles(self):
        """Connect optimization checkboxes to show/hide their parameter fields.

        When a checkbox is unchecked, its parameter fields are hidden to reduce
        visual clutter. This applies to:
        - Early stopping: min_delta and patience fields
        - OHKM: min_hard_keypoints and max_hard_keypoints fields
        """
        opt_form = self.form_widgets["optimization"]
        form_layout = opt_form.form_layout

        # Define which checkbox controls which parameter fields
        toggle_groups = {
            "trainer_config.early_stopping.stop_training_on_plateau": [
                "trainer_config.early_stopping.min_delta",
                "trainer_config.early_stopping.patience",
            ],
            "trainer_config.online_hard_keypoint_mining.online_mining": [
                "trainer_config.online_hard_keypoint_mining.min_hard_keypoints",
                "trainer_config.online_hard_keypoint_mining.max_hard_keypoints",
            ],
        }

        for checkbox_name, param_fields in toggle_groups.items():
            checkbox = opt_form.fields.get(checkbox_name)
            if checkbox is None:
                continue

            # Collect the parameter field widgets and their labels
            param_widgets = []
            for field_name in param_fields:
                field = opt_form.fields.get(field_name)
                if field is not None:
                    # Get the label for this field from the form layout
                    label = form_layout.labelForField(field)
                    param_widgets.append((field, label))

            if not param_widgets:
                continue

            # Create update function that captures the widgets
            def make_update_visibility(widgets):
                def update_visibility(state):
                    visible = bool(state)
                    for field, label in widgets:
                        field.setVisible(visible)
                        if label is not None:
                            label.setVisible(visible)

                return update_visibility

            update_fn = make_update_visibility(param_widgets)
            checkbox.stateChanged.connect(update_fn)
            update_fn(checkbox.isChecked())  # Set initial state

    def _setup_crop_size_visibility(self):
        """Hide crop size field for model types that don't use cropping.

        Crop size is only relevant for centered_instance and multi_class_topdown
        models which crop around detected centroids. Other model types (centroid,
        bottomup, single_instance, multi_class_bottomup) process full images.
        """
        # Only show for models that use instance cropping
        if self.head in ("centered_instance", "multi_class_topdown"):
            return  # Keep visible (default state)

        data_form = self.form_widgets["data"]
        form_layout = data_form.form_layout
        crop_field = data_form.fields.get("data_config.preprocessing.crop_size")

        if crop_field is not None:
            crop_label = form_layout.labelForField(crop_field)
            crop_field.setVisible(False)
            if crop_label is not None:
                crop_label.setVisible(False)

    def _setup_input_scaling_info(self):
        """Add an info button next to Input Scaling for crop-based (top-down) heads.

        Centered instance (and multi-class top-down) models already operate on
        cropped instances, so input scaling can usually be left at 1.0. This adds a
        small clickable info button next to the Input Scaling field on those tabs to
        surface that guidance without disabling the field.
        """
        if self.head not in ("centered_instance", "multi_class_topdown"):
            return

        data_form = self.form_widgets["data"]
        form_layout = data_form.form_layout
        scale_field = data_form.fields.get("data_config.preprocessing.scale")
        if scale_field is None:
            return

        row, role = form_layout.getWidgetPosition(scale_field)
        if row < 0:
            return

        note = (
            "Centered instance models already operate on cropped instances, so "
            "input scaling can usually be left at 1.0."
        )

        info_button = QtWidgets.QToolButton()
        info_button.setIcon(
            self.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxInformation)
        )
        info_button.setAutoRaise(True)
        info_button.setToolTip(note)
        info_button.setCursor(QtCore.Qt.WhatsThisCursor)
        info_button.clicked.connect(
            lambda: QtWidgets.QMessageBox.information(self, "Input Scaling", note)
        )

        # Wrap the existing field and the info button in a horizontal container so
        # the button sits immediately to the right of the Input Scaling field.
        container = QtWidgets.QWidget()
        hbox = QtWidgets.QHBoxLayout(container)
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.setSpacing(4)
        form_layout.removeWidget(scale_field)
        hbox.addWidget(scale_field)
        hbox.addWidget(info_button)
        hbox.addStretch(1)
        form_layout.setWidget(row, role, container)

    def _get_max_instance_bbox_size(self) -> Optional[float]:
        """Return the largest labeled-instance bbox dimension (px), cached.

        Labels do not change over the dialog's lifetime, so the (potentially
        expensive) scan over all instances is computed once and reused.
        """
        if self._labels is None:
            return None
        if self._max_instance_bbox_size is None:
            try:
                self._max_instance_bbox_size = (
                    receptivefield.find_max_instance_bbox_size(self._labels)
                )
            except Exception:
                self._max_instance_bbox_size = None
        return self._max_instance_bbox_size

    def get_config_warnings(self) -> List[str]:
        """Return inline warnings about crop size / input scaling.

        Only crop-based (top-down) heads are checked. Warns when:
          - the model's effective (post-scale) input crop would be < 100px, since
            centered instance models perform poorly below that size; and
          - an explicit crop size is smaller than the largest labeled instance, in
            which case instances would be clipped by the crop.
        """
        warnings: List[str] = []
        if self.head not in ("centered_instance", "multi_class_topdown"):
            return warnings
        if self._labels is None:
            return warnings

        try:
            data_cfg = get_omegaconf_from_gui_form(
                self.form_widgets["data"].get_form_data()
            )
            model_cfg = get_omegaconf_from_gui_form(
                self.form_widgets["model"].get_form_data()
            )
            aug_form_data = self.form_widgets["augmentation"].get_form_data()
        except Exception:
            return warnings

        # Effective (post-scale) crop size too small for the centered instance model.
        try:
            effective_crop = receptivefield.compute_crop_size_from_cfg(
                data_cfg, model_cfg, self._labels, aug_form_data
            )
        except Exception:
            effective_crop = None
        if effective_crop is not None and effective_crop < 100:
            warnings.append(
                f"The centered instance model's input crop will be only "
                f"{int(effective_crop)}px after input scaling, but these models "
                "perform poorly below 100px. Set Input Scaling to 1.0 and Crop Size "
                "to Auto."
            )

        # Explicit crop size smaller than the largest labeled instance (clipping).
        crop_size = OmegaConf.select(
            data_cfg, "data_config.preprocessing.crop_size", default=None
        )
        if crop_size is not None:
            max_bbox = self._get_max_instance_bbox_size()
            if max_bbox is not None and crop_size < max_bbox:
                warnings.append(
                    f"Crop size ({int(crop_size)}px) is smaller than the largest "
                    f"labeled instance ({int(round(max_bbox))}px), so instances will "
                    "be clipped. Increase the crop size or set it to Auto."
                )

        return warnings

    def _setup_ohkm_visibility(self):
        """Hide OHKM fields for centroid models.

        Online Hard Keypoint Mining (OHKM) is only relevant for models that predict
        multiple keypoints. Centroid models predict a single point per instance,
        so the concept of "hard vs easy keypoints" doesn't apply.
        """
        if self.head != "centroid":
            return  # Keep visible for all other model types

        opt_form = self.form_widgets["optimization"]
        form_layout = opt_form.form_layout

        ohkm_fields = [
            "trainer_config.online_hard_keypoint_mining.online_mining",
            "trainer_config.online_hard_keypoint_mining.min_hard_keypoints",
            "trainer_config.online_hard_keypoint_mining.max_hard_keypoints",
        ]

        for field_name in ohkm_fields:
            field = opt_form.fields.get(field_name)
            if field is not None:
                label = form_layout.labelForField(field)
                field.setVisible(False)
                if label is not None:
                    label.setVisible(False)

    def _setup_negative_frames_visibility(self):
        """Hide negative-frame fields for model types that ignore them.

        Negative (background) frames are only used by single_instance, centroid,
        bottomup, and multi_class_bottomup models. The centered_instance and
        multi_class_topdown heads ignore them, so the fields are hidden on those
        tabs to avoid implying an effect that will not happen.
        """
        if self.head not in ("centered_instance", "multi_class_topdown"):
            return  # Keep visible for model types that use negative frames.

        data_form = self.form_widgets["data"]
        form_layout = data_form.form_layout

        for field_name in (
            "data_config.use_negative_frames",
            "data_config.negative_loss_weight",
        ):
            field = data_form.fields.get(field_name)
            if field is not None:
                label = form_layout.labelForField(field)
                field.setVisible(False)
                if label is not None:
                    label.setVisible(False)

    def _setup_negative_frames_toggle(self):
        """Enable the negative loss weight field only when negatives are enabled.

        Follows the same pattern as `_setup_overfit_mode_toggle`.
        """
        data_form = self.form_widgets["data"]
        form_layout = data_form.form_layout
        use_field_name = "data_config.use_negative_frames"
        weight_field_name = "data_config.negative_loss_weight"

        use_checkbox = data_form.fields.get(use_field_name)
        weight_widget = data_form.fields.get(weight_field_name)

        if use_checkbox is not None and weight_widget is not None:
            weight_label = form_layout.labelForField(weight_widget)

            def update_state():
                enabled = use_checkbox.isChecked()
                weight_widget.setEnabled(enabled)
                if weight_label is not None:
                    weight_label.setEnabled(enabled)

            use_checkbox.stateChanged.connect(update_state)
            update_state()

    def acceptSelectedConfigInfo(self, cfg_info: configs.ConfigFileInfo):
        self._load_config(cfg_info)

        has_trained_model = cfg_info.has_trained_model

        # Update radio button states based on whether selected config has trained model
        if self._radio_use_trained is not None:
            # Enable/disable trained model options based on availability
            self._radio_use_trained.setEnabled(has_trained_model)
            self._radio_resume.setEnabled(has_trained_model)

            # If no trained model available, reset to "train from scratch"
            if not has_trained_model:
                self._radio_train_scratch.setChecked(True)

        self.update_receptive_field()

    def update_receptive_field(self):
        data_form_data = get_omegaconf_from_gui_form(
            self.form_widgets["data"].get_form_data()
        )

        model_cfg = get_omegaconf_from_gui_form(
            self.form_widgets["model"].get_form_data()
        )

        rf_image_scale = OmegaConf.select(
            data_form_data, "data_config.preprocessing.scale", default=1.0
        )

        if self._receptive_field_widget:
            self._receptive_field_widget.setModelConfig(model_cfg, scale=rf_image_scale)

            # Update crop box for centered_instance/multi_class_topdown heads
            if (
                self.head in ("centered_instance", "multi_class_topdown")
                and self._labels
            ):
                aug_form_data = self.form_widgets["augmentation"].get_form_data()
                crop_size = receptivefield.compute_crop_size_from_cfg(
                    data_form_data, model_cfg, self._labels, aug_form_data
                )

                # Get anchor part from the model form data
                anchor_part = None
                if self.head == "centered_instance":
                    anchor_part = OmegaConf.select(
                        model_cfg,
                        "model_config.head_configs.centered_instance.confmaps.anchor_part",
                        default=None,
                    )
                elif self.head == "multi_class_topdown":
                    anchor_part = OmegaConf.select(
                        model_cfg,
                        "model_config.head_configs.multi_class_topdown.confmaps.anchor_part",
                        default=None,
                    )

                self._receptive_field_widget.setCropConfig(
                    crop_size=crop_size,
                    scale=rf_image_scale,
                    anchor_part=anchor_part,
                )

            self._receptive_field_widget.repaint()

    def update_file_list(self):
        self._cfg_list_widget.update()

    def _load_config_or_key_val_dict(self, cfg_data):
        if type(cfg_data) != dict:
            self._load_config(cfg_data)
        else:
            self.set_fields_from_key_val_dict(cfg_data)

    def _load_config(self, cfg_info: configs.ConfigFileInfo):
        if cfg_info is None:
            return

        cfg = cfg_info.config
        key_val_dict = get_keyval_dict_from_omegaconf(cfg)

        # Filter out system-specific settings that should come from preferences,
        # not from the training profile. These are machine-specific (GPU count,
        # accelerator, workers) and should default to "auto" regardless of what
        # the profile says. Without this, a profile trained on one machine (e.g.
        # `trainer_accelerator: mps` from a Mac) would silently carry that stale,
        # possibly-unavailable value over when reloaded on a different machine.
        system_specific_keys = [
            "trainer_config.trainer_devices",
            "trainer_config.trainer_accelerator",
            "trainer_config.train_data_loader.num_workers",
        ]
        for key in system_specific_keys:
            key_val_dict.pop(key, None)

        # Clear run_name - it should be auto-generated for new training runs.
        # This prevents old run_name from base config from leaking through.
        key_val_dict["trainer_config.run_name"] = None

        # Reverse-map rotation_min/rotation_max to _rotation_preset dropdown
        rot_min = key_val_dict.get(
            "data_config.augmentation_config.geometric.rotation_min"
        )
        rot_max = key_val_dict.get(
            "data_config.augmentation_config.geometric.rotation_max"
        )
        rot_p = key_val_dict.get("data_config.augmentation_config.geometric.rotation_p")
        affine_p = key_val_dict.get(
            "data_config.augmentation_config.geometric.affine_p"
        )

        # Check rotation_p first, fall back to affine_p for legacy configs
        effective_rot_p = rot_p if rot_p is not None else affine_p

        if effective_rot_p is None or effective_rot_p == 0:
            key_val_dict["_rotation_preset"] = "Off"
        elif rot_min is not None and rot_max is not None:
            # Check for symmetric presets
            if rot_min == -15 and rot_max == 15:
                key_val_dict["_rotation_preset"] = "±15°"
            elif rot_min == -180 and rot_max == 180:
                key_val_dict["_rotation_preset"] = "±180°"
            elif rot_min == -rot_max:
                # Symmetric but custom angle
                key_val_dict["_rotation_preset"] = "Custom"
                key_val_dict["_rotation_custom_angle"] = rot_max
            else:
                # Asymmetric (rare) - use Custom with max as angle
                key_val_dict["_rotation_preset"] = "Custom"
                key_val_dict["_rotation_custom_angle"] = max(abs(rot_min), abs(rot_max))

        # Reverse-map scale settings to _scale_enabled checkbox
        scale_p = key_val_dict.get("data_config.augmentation_config.geometric.scale_p")
        scale_min = key_val_dict.get(
            "data_config.augmentation_config.geometric.scale_min"
        )
        scale_max = key_val_dict.get(
            "data_config.augmentation_config.geometric.scale_max"
        )

        # Check scale_p first, fall back to affine_p for legacy configs
        effective_scale_p = scale_p if scale_p is not None else affine_p

        # Scale is enabled if probability > 0 AND min != max (actual scaling occurs)
        scale_enabled = (
            effective_scale_p is not None
            and effective_scale_p > 0
            and scale_min is not None
            and scale_max is not None
            and scale_min != scale_max
        )
        key_val_dict["_scale_enabled"] = scale_enabled

        self.set_fields_from_key_val_dict(key_val_dict)

    # def _set_user_config(self):
    #     cfg_form_data_dict = self.get_all_form_data()
    #     self._cfg_list_widget.setUserConfigData(cfg_form_data_dict)

    def _update_use_trained(self, button=None):
        """Update config GUI based on training mode radio button selection.

        This function is called when a radio button is clicked or when
        _require_trained is set (inference mode).

        Training modes:
        - Train from scratch: All forms editable, train new model
        - Use same model (don't retrain): All forms disabled, use trained model as-is
        - Resume training (fine-tune): Model form disabled, other forms editable

        Args:
            button: The clicked radio button (unused, we check button group state).

        Returns:
            None

        Side Effects:
            Disables/Enables fields based on selected training mode.
        """
        # Get current training mode
        use_trained_params = self.use_trained
        resume_training_params = self.resume_training

        # Enable/disable all form widgets based on mode
        for form in self.form_widgets.values():
            form.set_enabled(not use_trained_params)

        # Get config info if we need to load trained config/model
        cfg_info = None
        if use_trained_params or resume_training_params:
            if self._cfg_list_widget is not None:
                cfg_info = self._cfg_list_widget.getSelectedConfigInfo()

        # Resume training: model form disabled, load model config
        if resume_training_params and cfg_info is not None:
            self.form_widgets["model"].set_enabled(False)

            # Set model form to match config
            cfg = cfg_info.config
            key_val_dict = get_keyval_dict_from_omegaconf(cfg)
            self.set_fields_from_key_val_dict({"model": key_val_dict})

        # Use trained model: all forms disabled, load full config
        if use_trained_params and cfg_info is not None:
            self._load_config(cfg_info)

        self._set_head()

    def _set_head(self):
        if self.head:
            self.set_fields_from_key_val_dict(
                {
                    "_heads_name": self.head,
                }
            )

            self.form_widgets["model"].set_field_enabled("_heads_name", False)

    def set_fields_from_key_val_dict(self, cfg_key_val_dict):
        for form in self.form_widgets.values():
            form.set_form_data(cfg_key_val_dict)

        self._set_backbone_from_key_val_dict(cfg_key_val_dict)

    def _set_backbone_from_key_val_dict(self, cfg_key_val_dict):
        for key, val in cfg_key_val_dict.items():
            if (
                key.startswith("model.model_config.backbone_config.")
                and val is not None
            ):
                backbone_name = key.split(".")[3]
                self.set_fields_from_key_val_dict(dict(_backbone_name=backbone_name))
                break

    @property
    def use_trained(self) -> bool:
        """Check if user wants to use trained model without retraining.

        Returns True when:
        - _require_trained is True (inference mode), OR
        - "Use same model (don't retrain)" radio button is selected
        """
        if self._require_trained:
            return True

        if self._radio_use_trained is not None and self._radio_use_trained.isChecked():
            return True

        return False

    @property
    def resume_training(self) -> bool:
        """Check if user wants to resume/fine-tune training.

        Returns True when "Resume training (fine-tune)" radio button is selected.
        """
        if self._radio_resume is not None and self._radio_resume.isChecked():
            return True
        return False

    @property
    def trained_config_info_to_use(self) -> Optional[configs.ConfigFileInfo]:
        # If `TrainingEditorWidget` was initialized with a config getter, then
        # we expect to have a list of config files
        if self._cfg_list_widget is None:
            return None

        selected_config_info: Optional[configs.ConfigFileInfo] = (
            self._cfg_list_widget.getSelectedConfigInfo()
        )
        if (selected_config_info is None) or (
            not selected_config_info.has_trained_model
        ):
            return None

        trained_config_info = configs.ConfigFileInfo.from_config_file(
            selected_config_info.path
        )
        if self.use_trained:
            trained_config_info.dont_retrain = True
        else:
            # Set certain parameters to defaults
            trained_config = trained_config_info.config
            trained_config.data_config.val_labels_path = None
            trained_config.data_config.test_file_path = None
            trained_config.data_config.skeletons = []
            trained_config.trainer_config.ckpt_dir = None
            trained_config.trainer_config.run_name = None

        if self.resume_training:
            # Get the folder path of trained config and find checkpoint file
            model_dir = Path(cast(str, trained_config_info.path)).parent
            file_list = list(model_dir.iterdir())
            ckpt = None
            if (model_dir / "best.ckpt") in file_list:
                ckpt = "best.ckpt"
            elif (model_dir / "best_model.h5") in file_list:
                ckpt = "best_model.h5"

            if ckpt is not None:
                trained_config_info.config.model_config.pretrained_backbone_weights = (
                    model_dir / ckpt
                ).as_posix()
                trained_config_info.config.model_config.pretrained_head_weights = (
                    trained_config_info.config.model_config.pretrained_backbone_weights
                )
            else:
                # No checkpoint found - proceed without pretrained weights
                trained_config_info.config.model_config.pretrained_backbone_weights = (
                    None
                )
                trained_config_info.config.model_config.pretrained_head_weights = None
        else:
            trained_config_info.config.model_config.pretrained_backbone_weights = None
            trained_config_info.config.model_config.pretrained_head_weights = None

        # Always clear wandb.name so sleap-nn will default it to the new run_name.
        # "Use Trained Model Weights" means use pretrained weights for initialization,
        # not resume the same wandb logging run.
        trained_config_info.config.trainer_config.wandb.name = None

        return trained_config_info

    @property
    def has_trained_config_selected(self) -> bool:
        if self._cfg_list_widget is None:
            return False

        cfg_info = self._cfg_list_widget.getSelectedConfigInfo()
        if cfg_info and cfg_info.has_trained_model:
            return True

        return False

    def get_all_form_data(self) -> dict:
        form_data = dict()
        for form in self.form_widgets.values():
            form_data.update(form.get_form_data())
        return form_data

    def _open_size_distribution(self):
        """Opens the instance size distribution analysis dialog."""
        if self._labels is None:
            return

        from sleap.gui.dialogs.size_distribution import SizeDistributionDialog

        # Create navigate callback that emits signal to parent LearningDialog
        navigate_callback = None
        if self._parent_dialog is not None:

            def navigate_callback(video_idx: int, frame_idx: int, instance_idx: int):
                self._parent_dialog.navigate_to_instance.emit(
                    video_idx, frame_idx, instance_idx
                )

        dialog = SizeDistributionDialog(
            labels=self._labels,
            navigate_callback=navigate_callback,
            parent=self,
        )

        # Sync rotation preset with augmentation settings
        try:
            aug_data = self.form_widgets["augmentation"].get_form_data()
            rotation_preset = aug_data.get("_rotation_preset", "Off")

            # Map form values to widget values
            # Form uses: "Off", "±15°", "±180°", "Custom"
            # Widget expects: "Off", "+/-15", "+/-180", "Custom"
            preset_map = {
                "Off": "Off",
                "±15°": "+/-15",
                "±180°": "+/-180",
                "Custom": "Custom",
            }
            widget_preset = preset_map.get(rotation_preset, "Off")
            dialog.set_rotation_preset(widget_preset)

            # Also sync custom angle if applicable
            if widget_preset == "Custom":
                custom_angle = aug_data.get("_rotation_custom_angle")
                if custom_angle is not None:
                    dialog.set_custom_angle(int(custom_angle))
        except Exception:
            pass  # Use default if we can't read augmentation settings

        # Use show() for non-modal dialog so user can interact with main window
        dialog.show()

resume_training property

Check if user wants to resume/fine-tune training.

Returns True when "Resume training (fine-tune)" radio button is selected.

use_trained property

Check if user wants to use trained model without retraining.

Returns True when: - _require_trained is True (inference mode), OR - "Use same model (don't retrain)" radio button is selected

get_config_warnings()

Return inline warnings about crop size / input scaling.

Only crop-based (top-down) heads are checked. Warns when: - the model's effective (post-scale) input crop would be < 100px, since centered instance models perform poorly below that size; and - an explicit crop size is smaller than the largest labeled instance, in which case instances would be clipped by the crop.

Source code in sleap/gui/learning/dialog.py
def get_config_warnings(self) -> List[str]:
    """Return inline warnings about crop size / input scaling.

    Only crop-based (top-down) heads are checked. Warns when:
      - the model's effective (post-scale) input crop would be < 100px, since
        centered instance models perform poorly below that size; and
      - an explicit crop size is smaller than the largest labeled instance, in
        which case instances would be clipped by the crop.
    """
    warnings: List[str] = []
    if self.head not in ("centered_instance", "multi_class_topdown"):
        return warnings
    if self._labels is None:
        return warnings

    try:
        data_cfg = get_omegaconf_from_gui_form(
            self.form_widgets["data"].get_form_data()
        )
        model_cfg = get_omegaconf_from_gui_form(
            self.form_widgets["model"].get_form_data()
        )
        aug_form_data = self.form_widgets["augmentation"].get_form_data()
    except Exception:
        return warnings

    # Effective (post-scale) crop size too small for the centered instance model.
    try:
        effective_crop = receptivefield.compute_crop_size_from_cfg(
            data_cfg, model_cfg, self._labels, aug_form_data
        )
    except Exception:
        effective_crop = None
    if effective_crop is not None and effective_crop < 100:
        warnings.append(
            f"The centered instance model's input crop will be only "
            f"{int(effective_crop)}px after input scaling, but these models "
            "perform poorly below 100px. Set Input Scaling to 1.0 and Crop Size "
            "to Auto."
        )

    # Explicit crop size smaller than the largest labeled instance (clipping).
    crop_size = OmegaConf.select(
        data_cfg, "data_config.preprocessing.crop_size", default=None
    )
    if crop_size is not None:
        max_bbox = self._get_max_instance_bbox_size()
        if max_bbox is not None and crop_size < max_bbox:
            warnings.append(
                f"Crop size ({int(crop_size)}px) is smaller than the largest "
                f"labeled instance ({int(round(max_bbox))}px), so instances will "
                "be clipped. Increase the crop size or set it to Auto."
            )

    return warnings