Skip to content

screens

sleap_nn.config_generator.tui.screens

TUI screens for config generator.

This module exports all screen components used in the config generator TUI.

Modules:

Name Description
configure_screen

Configuration screen for the config generator TUI.

export_screen

Export configuration screen.

load_screen

Load data screen for the config generator TUI.

model_select_screen

Model selection screen for the config generator TUI.

Classes:

Name Description
ConfigureScreen

Screen for configuring training parameters.

ExportScreen

Export configuration screen component.

LoadScreen

Screen for loading and analyzing SLP files.

ModelSelectScreen

Screen for selecting model type.

TopDownExportScreen

Specialized export screen for top-down pipelines.

ConfigureScreen

Bases: Widget

Screen for configuring training parameters.

Methods:

Name Description
__init__

Initialize the configure screen.

action_goto_tab_1

Switch to the Shared Settings tab.

action_goto_tab_2

Switch to the Centroid Model tab.

action_goto_tab_3

Switch to the Instance Model tab.

action_next_tab

Switch to the next tab (for top-down models).

action_prev_tab

Switch to the previous tab (for top-down models).

compose

Compose the screen layout.

handle_accelerator_change

Handle accelerator changes.

handle_anchor_change

Handle anchor changes.

handle_backbone_change

Handle backbone changes.

handle_batch_change

Handle batch changes.

handle_brightness_change

Handle brightness changes.

handle_brightness_checkbox_change

Handle brightness changes.

handle_cache_path_change

Handle cache path changes.

handle_cache_workers_change

Handle cache workers changes.

handle_centroid_accelerator_change

Handle centroid accelerator changes.

handle_centroid_backbone_change

Handle centroid backbone changes.

handle_centroid_batch_change

Handle centroid batch changes.

handle_centroid_brightness_change

Handle centroid brightness changes.

handle_centroid_brightness_checkbox_change

Handle centroid brightness changes.

handle_centroid_channels_change

Handle centroid channels changes.

handle_centroid_ckpt_dir_change

Handle centroid ckpt dir changes.

handle_centroid_contrast_change

Handle centroid contrast changes.

handle_centroid_contrast_checkbox_change

Handle centroid contrast changes.

handle_centroid_data_pipeline_change

Handle centroid data pipeline changes.

handle_centroid_devices_change

Handle centroid devices changes.

handle_centroid_early_stopping_change

Handle centroid early stopping changes.

handle_centroid_epochs_change

Handle centroid epochs changes.

handle_centroid_es_min_delta_change

Handle centroid es min delta changes.

handle_centroid_es_patience_change

Handle centroid es patience changes.

handle_centroid_eval_change

Handle centroid eval changes.

handle_centroid_eval_frequency_change

Handle centroid eval frequency changes.

handle_centroid_eval_oks_change

Handle centroid eval oks changes.

handle_centroid_filters_change

Handle centroid filters changes.

handle_centroid_filters_rate_change

Handle centroid filters rate changes.

handle_centroid_imagenet_change

Handle centroid imagenet changes.

handle_centroid_lr_change

Handle centroid lr changes.

handle_centroid_lr_factor_change

Handle centroid lr factor changes.

handle_centroid_lr_patience_change

Handle centroid lr patience changes.

handle_centroid_max_height_change

Handle centroid max height changes.

handle_centroid_max_stride_change

Handle centroid max stride changes.

handle_centroid_max_width_change

Handle centroid max width changes.

handle_centroid_min_steps_change

Handle centroid min steps changes.

handle_centroid_num_workers_change

Handle centroid num workers changes.

handle_centroid_num_workers_input_change

Handle centroid num workers changes.

handle_centroid_optimizer_change

Handle centroid optimizer changes.

handle_centroid_output_stride_change

Handle centroid output stride changes.

handle_centroid_pretrained_backbone_change

Handle centroid pretrained backbone changes.

handle_centroid_pretrained_head_change

Handle centroid pretrained head changes.

handle_centroid_random_seed_change

Handle centroid random seed changes.

handle_centroid_resume_ckpt_change

Handle centroid resume ckpt changes.

handle_centroid_rotation_change

Handle centroid rotation changes.

handle_centroid_rotation_checkbox_change

Handle centroid rotation changes.

handle_centroid_run_name_change

Handle centroid run name changes.

handle_centroid_save_ckpt_change

Handle centroid save ckpt changes.

handle_centroid_save_top_k_change

Handle centroid save top k changes.

handle_centroid_save_viz_change

Handle centroid save viz changes.

handle_centroid_scale_change

Handle centroid scale changes.

handle_centroid_scale_checkbox_change

Handle centroid scale changes.

handle_centroid_scale_max_change

Handle centroid scale max changes.

handle_centroid_scale_min_change

Handle centroid scale min changes.

handle_centroid_scheduler_change

Handle centroid scheduler changes.

handle_centroid_sigma_change

Handle centroid sigma changes.

handle_centroid_translate_change

Handle centroid translate changes.

handle_centroid_translate_checkbox_change

Handle centroid translate changes.

handle_centroid_val_fraction_change

Handle centroid val fraction changes.

handle_centroid_viz_keep_folder_change

Handle centroid viz keep folder changes.

handle_centroid_wandb_change

Handle centroid wandb changes.

handle_centroid_wandb_project_change

Handle centroid wandb project changes.

handle_channels_change

Handle channels changes.

handle_ckpt_dir_change

Handle ckpt dir changes.

handle_class_loss_weight_change

Handle class loss weight changes.

handle_contrast_change

Handle contrast changes.

handle_contrast_checkbox_change

Handle contrast changes.

handle_crop_size_change

Handle crop size changes.

handle_data_pipeline_change

Handle data pipeline changes.

handle_delete_cache_change

Handle delete cache changes.

handle_devices_change

Handle devices changes.

handle_early_stopping_change

Handle early stopping changes.

handle_epochs_change

Handle epochs changes.

handle_es_patience_change

Handle es patience changes.

handle_eval_checkbox_change

Handle eval changes.

handle_eval_frequency_change

Handle eval frequency changes.

handle_eval_oks_change

Handle eval oks changes.

handle_evaluation_change

Handle evaluation changes.

handle_fc_layers_change

Handle fc layers changes.

handle_fc_units_change

Handle fc units changes.

handle_filters_change

Handle filters changes.

handle_filters_rate_change

Handle filters rate changes.

handle_instance_accelerator_change

Handle instance accelerator changes.

handle_instance_backbone_change

Handle instance backbone changes.

handle_instance_batch_change

Handle instance batch changes.

handle_instance_brightness_change

Handle instance brightness changes.

handle_instance_brightness_checkbox_change

Handle instance brightness changes.

handle_instance_cache_path_change

Handle instance cache path changes.

handle_instance_cache_workers_change

Handle instance cache workers changes.

handle_instance_channels_change

Handle instance channels changes.

handle_instance_ckpt_dir_change

Handle instance ckpt dir changes.

handle_instance_contrast_change

Handle instance contrast changes.

handle_instance_contrast_checkbox_change

Handle instance contrast changes.

handle_instance_data_pipeline_change

Handle instance data pipeline changes.

handle_instance_delete_cache_change

Handle instance delete cache changes.

handle_instance_devices_change

Handle instance devices changes.

handle_instance_early_stopping_change

Handle instance early stopping changes.

handle_instance_epochs_change

Handle instance epochs changes.

handle_instance_es_min_delta_change

Handle instance es min delta changes.

handle_instance_es_patience_change

Handle instance es patience changes.

handle_instance_eval_change

Handle instance eval changes.

handle_instance_eval_frequency_change

Handle instance eval frequency changes.

handle_instance_eval_oks_change

Handle instance eval oks changes.

handle_instance_filters_change

Handle instance filters changes.

handle_instance_filters_rate_change

Handle instance filters rate changes.

handle_instance_imagenet_change

Handle instance imagenet changes.

handle_instance_lr_change

Handle instance lr changes.

handle_instance_lr_factor_change

Handle instance lr factor changes.

handle_instance_lr_patience_change

Handle instance lr patience changes.

handle_instance_lr_select_change

Handle instance lr changes.

handle_instance_max_stride_change

Handle instance max stride changes.

handle_instance_min_steps_change

Handle instance min steps changes.

handle_instance_num_workers_select_change

Handle instance num workers changes.

handle_instance_ohkm_change

Handle instance ohkm changes.

handle_instance_ohkm_max_change

Handle instance ohkm max changes.

handle_instance_ohkm_min_change

Handle instance ohkm min changes.

handle_instance_ohkm_ratio_change

Handle instance ohkm ratio changes.

handle_instance_ohkm_scale_change

Handle instance ohkm scale changes.

handle_instance_optimizer_change

Handle instance optimizer changes.

handle_instance_output_stride_change

Handle instance output stride changes.

handle_instance_parallel_caching_change

Handle instance parallel caching changes.

handle_instance_pretrained_backbone_change

Handle instance pretrained backbone changes.

handle_instance_pretrained_head_change

Handle instance pretrained head changes.

handle_instance_random_seed_change

Handle instance random seed changes.

handle_instance_rotation_change

Handle instance rotation changes.

handle_instance_rotation_checkbox_change

Handle instance rotation changes.

handle_instance_run_name_change

Handle instance run name changes.

handle_instance_save_ckpt_change

Handle instance save ckpt changes.

handle_instance_save_last_change

Handle instance save last changes.

handle_instance_save_top_k_change

Handle instance save top k changes.

handle_instance_save_viz_change

Handle instance save viz changes.

handle_instance_scale_change

Handle instance scale changes.

handle_instance_scale_checkbox_change

Handle instance scale changes.

handle_instance_scale_max_change

Handle instance scale max changes.

handle_instance_scale_min_change

Handle instance scale min changes.

handle_instance_scheduler_change

Handle instance scheduler changes.

handle_instance_sigma_change

Handle instance sigma changes.

handle_instance_use_existing_change

Handle instance use existing changes.

handle_instance_viz_keep_folder_change

Handle instance viz keep folder changes.

handle_instance_wandb_change

Handle instance wandb changes.

handle_instance_wandb_entity_change

Handle instance wandb entity changes.

handle_instance_wandb_project_change

Handle instance wandb project changes.

handle_keep_viz_change

Handle keep viz changes.

handle_lr_change

Handle lr changes.

handle_max_height_change

Handle max height changes.

handle_max_width_change

Handle max width changes.

handle_min_crop_size_change

Handle min crop size changes.

handle_min_steps_change

Handle min steps changes.

handle_num_workers_select_change

Handle num workers changes.

handle_ohkm_change

Handle ohkm changes.

handle_ohkm_ratio_change

Handle ohkm ratio changes.

handle_ohkm_scale_change

Handle ohkm scale changes.

handle_oks_stddev_change

Handle oks stddev changes.

handle_optimizer_change

Handle optimizer changes.

handle_output_stride_change

Handle output stride changes.

handle_paf_loss_weight_change

Handle paf loss weight changes.

handle_paf_output_stride_change

Handle paf output stride changes.

handle_paf_sigma_change

Handle paf sigma changes.

handle_parallel_caching_change

Handle parallel caching changes.

handle_pretrained_backbone_change

Handle pretrained backbone changes.

handle_pretrained_head_change

Handle pretrained head changes.

handle_progress_bar_change

Handle progress bar changes.

handle_random_seed_change

Handle random seed changes.

handle_resume_ckpt_change

Handle resume ckpt changes.

handle_rotation_change

Handle rotation changes.

handle_rotation_checkbox_change

Handle rotation changes.

handle_run_name_change

Handle run name changes.

handle_save_last_change

Handle save last changes.

handle_save_top_k_change

Handle save top k changes.

handle_save_viz_change

Handle save viz changes.

handle_scale_change

Handle scale changes.

handle_scale_checkbox_change

Handle scale changes.

handle_scale_max_change

Handle scale max changes.

handle_scale_min_change

Handle scale min changes.

handle_scheduler_change

Handle scheduler changes.

handle_scheduler_cooldown_change

Handle scheduler cooldown changes.

handle_scheduler_end_lr_change

Handle scheduler end lr changes.

handle_scheduler_eta_min_change

Handle scheduler eta min changes.

handle_scheduler_factor_change

Handle scheduler factor changes.

handle_scheduler_gamma_change

Handle scheduler gamma changes.

handle_scheduler_linear_warmup_epochs_change

Handle scheduler linear warmup epochs changes.

handle_scheduler_linear_warmup_start_lr_change

Handle scheduler linear warmup start lr changes.

handle_scheduler_min_lr_change

Handle scheduler min lr changes.

handle_scheduler_patience_change

Handle scheduler patience changes.

handle_scheduler_step_size_change

Handle scheduler step size changes.

handle_scheduler_warmup_epochs_change

Handle scheduler warmup epochs changes.

handle_scheduler_warmup_start_lr_change

Handle scheduler warmup start lr changes.

handle_sigma_change

Handle sigma changes.

handle_stride_change

Handle stride changes.

handle_use_existing_change

Handle use existing changes.

handle_val_fraction_change

Handle val fraction changes.

handle_visualize_preds_change

Handle visualize preds changes.

handle_viz_keep_folder_change

Handle viz keep folder changes.

handle_wandb_change

Handle wandb changes.

handle_wandb_entity_change

Handle wandb entity changes.

handle_wandb_project_change

Handle wandb project changes.

handle_wandb_save_viz_change

Handle wandb save viz changes.

handle_wandb_viz_change

Handle wandb viz changes.

on_mount

Initialize displays when widget is mounted.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
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
1593
1594
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
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
class ConfigureScreen(Widget):
    """Screen for configuring training parameters."""

    BINDINGS = [
        Binding("bracketleft", "prev_tab", "Previous Tab", show=False),
        Binding("bracketright", "next_tab", "Next Tab", show=False),
        Binding("1", "goto_tab_1", "Shared Settings", show=False),
        Binding("2", "goto_tab_2", "Centroid Model", show=False),
        Binding("3", "goto_tab_3", "Instance Model", show=False),
    ]

    DEFAULT_CSS = """
    ConfigureScreen {
        width: 100%;
        height: 100%;
        padding: 1;
    }

    #config-container {
        width: 100%;
        height: 100%;
    }

    #config-scroll {
        width: 100%;
        height: 1fr;
        padding: 0 1;
    }

    /* Section boxes with consistent spacing */
    .section-box {
        background: $panel;
        border: solid $primary;
        padding: 1 2;
        margin-bottom: 1;
        width: 100%;
        height: auto;
        layout: vertical;
    }

    .section-header {
        text-style: bold;
        padding-bottom: 1;
        border-bottom: solid $primary;
        margin-bottom: 1;
        width: 100%;
    }

    .subsection-header {
        text-style: bold;
        color: $text-muted;
        height: 2;
        margin-top: 1;
    }

    /* Parameter rows */
    .param-row {
        height: 3;
        margin-bottom: 0;
        width: 100%;
    }

    .param-label {
        width: 18;
        text-align: right;
        padding-right: 1;
    }

    .param-input {
        width: 12;
    }

    .param-input-wide {
        width: 28;
    }

    .param-hint {
        width: 1fr;
        padding-left: 1;
        color: $text-muted;
        text-style: italic;
    }

    /* Memory estimate */
    #memory-estimate {
        background: $panel;
        border: solid $warning;
        padding: 1 2;
        margin-top: 1;
    }

    /* Collapsible sections */
    .collapsible-section {
        margin-bottom: 1;
        width: 100%;
    }

    Collapsible {
        padding: 0;
        margin-bottom: 1;
    }

    Collapsible > Contents {
        padding: 1 2;
    }

    /* Tabs styling */
    #topdown-tabs {
        width: 100%;
        height: auto;
    }

    TabPane {
        padding: 1;
    }

    /* Model-specific sections */
    .model-specific-section {
        background: $warning-darken-3;
        border: solid $warning;
        padding: 1 2;
        margin-bottom: 1;
    }

    .hidden {
        display: none;
    }

    /* Input and Select styling */
    Input {
        width: 12;
    }

    Select {
        width: 18;
    }

    Checkbox {
        width: auto;
        padding-right: 1;
    }

    /* Shape info display */
    .shape-info {
        background: $surface;
        border: solid $primary-darken-2;
        padding: 1 2;
        margin: 1 0;
        width: 100%;
    }

    /* Memory estimate display */
    .memory-info {
        background: $surface;
        border: solid $success-darken-2;
        padding: 1 2;
        margin: 1 0;
        width: 100%;
    }

    .memory-warning {
        border: solid $warning;
    }

    .memory-danger {
        border: solid $error;
    }

    /* Info boxes (for tips, warnings) */
    .info-box {
        background: rgba(16, 185, 129, 0.1);
        border: solid $success;
        padding: 1 2;
        margin-bottom: 1;
        width: 100%;
    }

    .speed-tip {
        background: rgba(16, 185, 129, 0.15);
        border: solid $success;
    }
    """

    def __init__(self, state: Optional[ConfigState] = None, **kwargs):
        """Initialize the configure screen.

        Args:
            state: ConfigState with current configuration.
            **kwargs: Additional keyword arguments passed to parent.
        """
        super().__init__(**kwargs)
        self._state = state

    def compose(self) -> ComposeResult:
        """Compose the screen layout."""
        with Vertical(id="config-container"):
            yield Label(
                "[bold]Step 3: Configure Training[/bold]", classes="section-title"
            )

            if self._state and self._state.is_topdown:
                yield Label(
                    "[yellow]Top-down model selected - configuring 2 models[/yellow]",
                    classes="hint",
                )

            with VerticalScroll(id="config-scroll"):
                # For top-down, show tabbed interface
                if self._state and self._state.is_topdown:
                    yield from self._compose_topdown_config()
                else:
                    yield from self._compose_standard_config()
                    # Memory estimate only for non-topdown (topdown has per-model estimates)
                    yield from self._compose_memory_estimate()

    def on_mount(self) -> None:
        """Initialize displays when widget is mounted."""
        self._update_shape_display()
        self._update_memory_display()
        self._update_model_info_display()
        self._update_cache_memory_display()
        self._update_cache_options_visibility()
        self._update_imagenet_visibility()
        self._update_wandb_options_visibility()
        self._update_viz_options_visibility()
        self._update_eval_options_visibility()
        # For top-down models, also update centroid and instance-specific displays
        if self._state and self._state.is_topdown:
            self._update_centroid_shape_display()
            self._update_centroid_model_info_display()
            self._update_centroid_cache_memory_display()
            self._update_centroid_cache_options_visibility()
            self._update_instance_cache_memory_display()
            self._update_instance_cache_options_visibility()

    # ==================== TAB NAVIGATION ====================

    def action_prev_tab(self) -> None:
        """Switch to the previous tab (for top-down models)."""
        if not self._state or not self._state.is_topdown:
            return
        try:
            tabs = self.query_one("#topdown-tabs", TabbedContent)
            # Get current tab index and switch to previous
            tab_ids = ["shared-tab", "centroid-tab", "instance-tab"]
            current = tabs.active
            if current in tab_ids:
                idx = tab_ids.index(current)
                new_idx = (idx - 1) % len(tab_ids)
                tabs.active = tab_ids[new_idx]
        except Exception:
            pass

    def action_next_tab(self) -> None:
        """Switch to the next tab (for top-down models)."""
        if not self._state or not self._state.is_topdown:
            return
        try:
            tabs = self.query_one("#topdown-tabs", TabbedContent)
            # Get current tab index and switch to next
            tab_ids = ["shared-tab", "centroid-tab", "instance-tab"]
            current = tabs.active
            if current in tab_ids:
                idx = tab_ids.index(current)
                new_idx = (idx + 1) % len(tab_ids)
                tabs.active = tab_ids[new_idx]
        except Exception:
            pass

    def action_goto_tab_1(self) -> None:
        """Switch to the Shared Settings tab."""
        if not self._state or not self._state.is_topdown:
            return
        try:
            tabs = self.query_one("#topdown-tabs", TabbedContent)
            tabs.active = "shared-tab"
        except Exception:
            pass

    def action_goto_tab_2(self) -> None:
        """Switch to the Centroid Model tab."""
        if not self._state or not self._state.is_topdown:
            return
        try:
            tabs = self.query_one("#topdown-tabs", TabbedContent)
            tabs.active = "centroid-tab"
        except Exception:
            pass

    def action_goto_tab_3(self) -> None:
        """Switch to the Instance Model tab."""
        if not self._state or not self._state.is_topdown:
            return
        try:
            tabs = self.query_one("#topdown-tabs", TabbedContent)
            tabs.active = "instance-tab"
        except Exception:
            pass

    def _update_centroid_shape_display(self) -> None:
        """Update the centroid shape info display."""
        try:
            shape_widget = self.query_one("#centroid-shape-info-display", Static)
        except Exception:
            return

        if not self._state:
            shape_widget.update("[dim]Load SLP file to see shape info[/dim]")
            return

        import math

        # Get dimensions
        orig_h, orig_w = self._state.stats.max_height, self._state.stats.max_width
        eff_h = int(orig_h * self._state._input_scale)
        eff_w = int(orig_w * self._state._input_scale)
        out_h = eff_h // self._state._output_stride
        out_w = eff_w // self._state._output_stride

        # Get channels
        in_channels = 3 if self._state._ensure_rgb else 1

        # Build display text
        text = (
            f"[bold]Shape Pipeline:[/bold]\n"
            f"  Original: [cyan]{orig_w}×{orig_h}[/cyan]\n"
            f"  → Input:  [green]{eff_w}×{eff_h}×{in_channels}[/green] (H×W×C)\n"
            f"  → Output: [yellow]{out_w}×{out_h}×1[/yellow] (centroid confmap)"
        )

        shape_widget.update(text)

    def _update_centroid_model_info_display(self) -> None:
        """Update the centroid model info display (RF, params, encoder/decoder, sigma)."""
        try:
            model_widget = self.query_one("#centroid-model-info-display", Static)
        except Exception:
            return

        if not self._state:
            model_widget.update("[dim]Load SLP file to see model info[/dim]")
            return

        # Get max animal size from stats
        max_animal_size = self._state.stats.max_bbox_size

        # Receptive field of the deepest encoder layer (UNet).
        rf_pixels = compute_receptive_field(self._state._max_stride)

        # Scale RF by input scale to get effective RF in original image space
        effective_rf = (
            rf_pixels / self._state._input_scale
            if self._state._input_scale > 0
            else rf_pixels
        )

        # Get parameter estimate
        params = self._state.model_params_estimate
        params_str = f"{params / 1e6:.1f}M" if params >= 1e6 else f"{params / 1e3:.0f}K"

        # Encoder / decoder block counts
        encoder_blocks = _encoder_blocks(self._state._max_stride)
        decoder_blocks = _decoder_blocks(
            self._state._max_stride, self._state._output_stride
        )

        # Compute effective Gaussian radius: sigma * output_stride * 2
        effective_sigma_radius = self._state._sigma * self._state._output_stride * 2

        # Check if RF covers the animal
        rf_status = "green" if effective_rf >= max_animal_size else "yellow"
        rf_note = "✓" if effective_rf >= max_animal_size else "⚠ RF < animal"

        # Build display text
        text = (
            f"[bold]Model Architecture:[/bold]\n"
            f"  Parameters: [cyan]~{params_str}[/cyan] | "
            f"Encoder: [yellow]{encoder_blocks} blocks[/yellow] | "
            f"Decoder: [yellow]{decoder_blocks} blocks[/yellow]\n"
            f"  Max Animal Size: [magenta]~{max_animal_size:.0f}px[/magenta] | "
            f"Receptive Field: [{rf_status}]{rf_pixels}px ({effective_rf:.0f}px scaled) {rf_note}[/{rf_status}]\n"
            f"  Gaussian Radius: [blue]{effective_sigma_radius:.0f}px[/blue] (2σ covers 95%)"
        )

        model_widget.update(text)

    def _update_centroid_cache_memory_display(self) -> None:
        """Update the centroid cache memory display (shown when caching is enabled)."""
        try:
            cache_widget = self.query_one("#centroid-cache-memory-display", Static)
        except Exception:
            return

        if not self._state:
            cache_widget.update("")
            return

        from sleap_nn.config_generator.tui.state import DataPipelineType

        # Hide if not caching
        if self._state._data_pipeline == DataPipelineType.TORCH_DATASET:
            cache_widget.update("")
            return

        # Calculate cache memory
        bytes_per_frame = (
            self._state.stats.max_height
            * self._state.stats.max_width
            * self._state.stats.num_channels
        )
        raw_cache_mb = (bytes_per_frame * self._state.stats.num_labeled_frames) / 1e6
        cache_with_overhead = raw_cache_mb * 1.2

        # Check if memory caching with workers > 0
        num_workers = self._state._num_workers
        is_memory_cache = self._state._data_pipeline == DataPipelineType.MEMORY_CACHE
        total_cache_mb = cache_with_overhead

        if is_memory_cache and num_workers > 0:
            # Each worker gets a copy
            total_cache_mb = cache_with_overhead * (1 + num_workers)

        # Format display
        cache_type = "Memory" if is_memory_cache else "Disk"

        # Status color
        if total_cache_mb < 4000:
            status_color = "green"
            status = "OK"
        elif total_cache_mb < 8000:
            status_color = "yellow"
            status = "Large"
        else:
            status_color = "red"
            status = "Very Large"

        text = (
            f"[bold]💾 Image Cache ({cache_type}):[/bold] [{status_color}]{status}[/{status_color}]\n"
            f"  Raw data: {raw_cache_mb:.1f} MB\n"
            f"  With overhead (1.2×): {cache_with_overhead:.1f} MB"
        )

        if is_memory_cache and num_workers > 0:
            text += (
                f"\n  [yellow]⚠ With {num_workers} workers: {total_cache_mb:.1f} MB (×{1 + num_workers})[/yellow]\n"
                f"  [dim]Each worker gets a copy of the cache[/dim]"
            )

        cache_widget.update(text)

    def _update_centroid_cache_options_visibility(self) -> None:
        """Show/hide centroid cache options based on data pipeline selection."""
        if not self._state:
            return

        from sleap_nn.config_generator.tui.state import DataPipelineType

        is_caching = self._state._data_pipeline != DataPipelineType.TORCH_DATASET
        is_disk_cache = self._state._data_pipeline == DataPipelineType.DISK_CACHE

        # Cache options (shown when any caching is enabled)
        cache_option_ids = [
            "centroid-parallel-caching-row",
            "centroid-cache-workers-row",
        ]
        for widget_id in cache_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if is_caching:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

        # Disk-specific options (shown only for disk cache)
        disk_option_ids = [
            "centroid-disk-cache-header",
            "centroid-cache-path-row",
            "centroid-use-existing-row",
            "centroid-delete-cache-row",
        ]
        for widget_id in disk_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if is_disk_cache:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

    def _update_shape_display(self) -> None:
        """Update the shape info display with current configuration."""
        try:
            shape_widget = self.query_one("#shape-info-display", Static)
        except Exception:
            return

        if not self._state:
            shape_widget.update("[dim]Load SLP file to see shape info[/dim]")
            return

        # Get dimensions
        orig_h, orig_w = self._state.stats.max_height, self._state.stats.max_width
        eff_h, eff_w = self._state.effective_height, self._state.effective_width
        out_h, out_w = self._state.output_height, self._state.output_width

        # Get channels
        in_channels = 3 if self._state._ensure_rgb else 1
        num_keypoints = len(self._state.skeleton_nodes)

        # Determine output channels based on model type
        if self._state.is_topdown:
            out_channels = 1  # Centroid outputs 1 channel
        elif self._state.is_bottomup:
            num_edges = (
                len(self._state.stats.edges)
                if hasattr(self._state.stats, "edges")
                else 0
            )
            out_channels = f"{num_keypoints} + {num_edges * 2}"  # confmaps + PAFs
        else:
            out_channels = num_keypoints

        # Build display text
        text = (
            f"[bold]Shape Pipeline:[/bold]\n"
            f"  Original: [cyan]{orig_w}×{orig_h}[/cyan]\n"
            f"  → Input:  [green]{eff_w}×{eff_h}×{in_channels}[/green] (H×W×C)\n"
            f"  → Output: [yellow]{out_w}×{out_h}×{out_channels}[/yellow] (confmaps)"
        )

        shape_widget.update(text)

    def _update_memory_display(self) -> None:
        """Update the memory estimate display(s)."""
        if not self._state:
            return

        if self._state.is_topdown:
            # Update centroid memory display
            self._update_centroid_memory_display()
            # Update instance memory display
            self._update_instance_memory_display()
        else:
            # Update single memory display
            self._update_single_memory_display()

    def _update_single_memory_display(self) -> None:
        """Update the single model memory display."""
        try:
            mem_widget = self.query_one("#memory-info-display", Static)
        except Exception:
            return

        if not self._state:
            mem_widget.update("[dim]Load SLP file to see memory estimate[/dim]")
            return

        try:
            mem = self._state.memory_estimate()
        except Exception:
            mem_widget.update("[dim]Unable to estimate memory[/dim]")
            return

        # Build display text
        status_color = mem.gpu_status
        text = (
            f"[bold]GPU Memory Estimate:[/bold] [{status_color}]~{mem.total_gpu_gb:.1f} GB[/{status_color}]\n"
            f"  Model weights: {mem.model_weights_mb:.0f} MB\n"
            f"  Batch images: {mem.batch_images_mb:.0f} MB\n"
            f"  Activations: {mem.activations_mb:.0f} MB\n"
            f"  Gradients: {mem.gradients_mb:.0f} MB\n"
            f"  [dim]{mem.gpu_message}[/dim]"
        )

        # Add cache memory estimate if caching is enabled
        from sleap_nn.config_generator.tui.state import DataPipelineType

        if self._state._data_pipeline != DataPipelineType.TORCH_DATASET:
            cache_gb = mem.cache_memory_gb
            cache_type = (
                "disk"
                if self._state._data_pipeline == DataPipelineType.DISK_CACHE
                else "RAM"
            )
            # Status color for cache
            if cache_gb < 4:
                cache_color = "green"
            elif cache_gb < 8:
                cache_color = "yellow"
            else:
                cache_color = "red"
            text += (
                f"\n\n[bold]Image Cache ({cache_type}):[/bold] [{cache_color}]~{cache_gb:.1f} GB[/{cache_color}]\n"
                f"  [dim]{mem.cpu_message}[/dim]"
            )

        mem_widget.update(text)

        # Update CSS class for border color
        mem_widget.remove_class("memory-warning", "memory-danger")
        if status_color == "yellow":
            mem_widget.add_class("memory-warning")
        elif status_color == "red":
            mem_widget.add_class("memory-danger")

    def _update_centroid_memory_display(self) -> None:
        """Update the centroid model memory display."""
        try:
            mem_widget = self.query_one("#centroid-memory-display", Static)
        except Exception:
            return

        if not self._state:
            mem_widget.update("[dim]Load SLP file to see memory estimate[/dim]")
            return

        try:
            # Estimate for centroid model (uses main model params with centroid-specific settings)
            from sleap_nn.config_generator.memory import estimate_memory

            mem = estimate_memory(
                self._state.stats,
                self._state._backbone,  # Centroid uses main backbone
                self._state._batch_size,
                self._state._input_scale,
                self._state._output_stride,
                filters=self._state._filters,
                filters_rate=self._state._filters_rate,
                max_stride=self._state._max_stride,
                num_keypoints=len(self._state.skeleton_nodes),
            )
        except Exception:
            mem_widget.update("[dim]Unable to estimate memory[/dim]")
            return

        status_color = mem.gpu_status
        text = (
            f"[bold]Centroid GPU Memory:[/bold] [{status_color}]~{mem.total_gpu_gb:.1f} GB[/{status_color}]\n"
            f"  [dim]{mem.gpu_message}[/dim]"
        )

        # Add cache memory estimate if caching is enabled
        from sleap_nn.config_generator.tui.state import DataPipelineType

        if self._state._data_pipeline != DataPipelineType.TORCH_DATASET:
            cache_gb = mem.cache_memory_gb
            cache_type = (
                "disk"
                if self._state._data_pipeline == DataPipelineType.DISK_CACHE
                else "RAM"
            )
            if cache_gb < 4:
                cache_color = "green"
            elif cache_gb < 8:
                cache_color = "yellow"
            else:
                cache_color = "red"
            text += f"\n[bold]Cache ({cache_type}):[/bold] [{cache_color}]~{cache_gb:.1f} GB[/{cache_color}]"

        mem_widget.update(text)
        mem_widget.remove_class("memory-warning", "memory-danger")
        if status_color == "yellow":
            mem_widget.add_class("memory-warning")
        elif status_color == "red":
            mem_widget.add_class("memory-danger")

    def _update_instance_memory_display(self) -> None:
        """Update the centered instance model memory display."""
        try:
            mem_widget = self.query_one("#instance-memory-display", Static)
        except Exception:
            return

        if not self._state:
            mem_widget.update("[dim]Load SLP file to see memory estimate[/dim]")
            return

        try:
            # Estimate for instance model (uses CI-specific params)
            from sleap_nn.config_generator.memory import estimate_memory

            # Get crop size with fallback
            try:
                crop_size = self._state._crop_size
                if crop_size is None:
                    crop_size = self._state._compute_auto_crop_size()
            except Exception:
                crop_size = 256  # Fallback default

            # Get state attributes with defaults
            ci_backbone = getattr(self._state, "_ci_backbone", "unet_medium_rf")
            ci_batch_size = getattr(self._state, "_ci_batch_size", 4)
            ci_input_scale = getattr(self._state, "_ci_input_scale", 1.0)
            ci_output_stride = getattr(self._state, "_ci_output_stride", 2)
            ci_filters = getattr(self._state, "_ci_filters", 32)
            ci_filters_rate = getattr(self._state, "_ci_filters_rate", 1.5)
            ci_max_stride = getattr(self._state, "_ci_max_stride", 16)

            # Get stats with validation
            stats = self._state.stats
            if stats is None:
                mem_widget.update("[dim]Loading stats...[/dim]")
                return

            # Create modified stats for instance model with all required attributes
            class CropStats:
                def __init__(self, orig_stats, crop_size):
                    self.max_width = crop_size
                    self.max_height = crop_size
                    self.num_frames = getattr(
                        orig_stats, "num_frames", orig_stats.num_labeled_frames
                    )
                    self.num_labeled_frames = orig_stats.num_labeled_frames
                    self.is_rgb = getattr(
                        orig_stats, "is_rgb", orig_stats.num_channels == 3
                    )
                    self.num_channels = orig_stats.num_channels
                    self.num_nodes = getattr(
                        orig_stats,
                        "num_nodes",
                        len(getattr(orig_stats, "node_names", [])),
                    )
                    self.node_names = getattr(orig_stats, "node_names", [])
                    self.nodes = getattr(orig_stats, "nodes", self.node_names)

            crop_stats = CropStats(stats, crop_size)

            # Get num_keypoints safely
            skeleton_nodes = getattr(self._state, "skeleton_nodes", [])
            num_keypoints = (
                len(skeleton_nodes) if skeleton_nodes else crop_stats.num_nodes
            )
            if num_keypoints == 0:
                num_keypoints = 13  # Fallback default

            mem = estimate_memory(
                crop_stats,
                ci_backbone,
                ci_batch_size,
                ci_input_scale,
                ci_output_stride,
                filters=ci_filters,
                filters_rate=ci_filters_rate,
                max_stride=ci_max_stride,
                num_keypoints=num_keypoints,
            )
        except Exception as e:
            # Show more informative error for debugging
            err_msg = str(e) if str(e) else type(e).__name__
            mem_widget.update(f"[dim]Unable to estimate memory: {err_msg}[/dim]")
            return

        status_color = mem.gpu_status
        text = (
            f"[bold]Instance GPU Memory:[/bold] [{status_color}]~{mem.total_gpu_gb:.1f} GB[/{status_color}]\n"
            f"  [dim]{mem.gpu_message}[/dim]"
        )

        # Add cache memory estimate if caching is enabled
        # Note: Instance model caches full-frame images, same as centroid
        from sleap_nn.config_generator.tui.state import DataPipelineType

        if self._state._data_pipeline != DataPipelineType.TORCH_DATASET:
            # Calculate cache based on original image size, not crop
            full_mem = self._state.memory_estimate()
            cache_gb = full_mem.cache_memory_gb
            cache_type = (
                "disk"
                if self._state._data_pipeline == DataPipelineType.DISK_CACHE
                else "RAM"
            )
            if cache_gb < 4:
                cache_color = "green"
            elif cache_gb < 8:
                cache_color = "yellow"
            else:
                cache_color = "red"
            text += f"\n[bold]Cache ({cache_type}):[/bold] [{cache_color}]~{cache_gb:.1f} GB[/{cache_color}]"

        mem_widget.update(text)
        mem_widget.remove_class("memory-warning", "memory-danger")
        if status_color == "yellow":
            mem_widget.add_class("memory-warning")
        elif status_color == "red":
            mem_widget.add_class("memory-danger")

    def _update_cache_memory_display(self) -> None:
        """Update the cache memory display (shown when caching is enabled)."""
        try:
            cache_widget = self.query_one("#cache-memory-display", Static)
        except Exception:
            return

        if not self._state:
            cache_widget.update("")
            return

        from sleap_nn.config_generator.tui.state import DataPipelineType

        # Hide if not caching
        if self._state._data_pipeline == DataPipelineType.TORCH_DATASET:
            cache_widget.update("")
            return

        # Calculate cache memory
        bytes_per_frame = (
            self._state.stats.max_height
            * self._state.stats.max_width
            * self._state.stats.num_channels
        )
        raw_cache_mb = (bytes_per_frame * self._state.stats.num_labeled_frames) / 1e6
        cache_with_overhead = raw_cache_mb * 1.2

        # Check if memory caching with workers > 0
        num_workers = self._state._num_workers
        is_memory_cache = self._state._data_pipeline == DataPipelineType.MEMORY_CACHE
        total_cache_mb = cache_with_overhead

        if is_memory_cache and num_workers > 0:
            # Each worker gets a copy
            total_cache_mb = cache_with_overhead * (1 + num_workers)

        # Format display
        cache_type = "Memory" if is_memory_cache else "Disk"

        # Status color
        if total_cache_mb < 4000:
            status_color = "green"
            status = "OK"
        elif total_cache_mb < 8000:
            status_color = "yellow"
            status = "Large"
        else:
            status_color = "red"
            status = "Very Large"

        text = (
            f"[bold]💾 Image Cache ({cache_type}):[/bold] [{status_color}]{status}[/{status_color}]\n"
            f"  Raw data: {raw_cache_mb:.1f} MB\n"
            f"  With overhead (1.2×): {cache_with_overhead:.1f} MB"
        )

        if is_memory_cache and num_workers > 0:
            text += (
                f"\n  [yellow]⚠ With {num_workers} workers: {total_cache_mb:.1f} MB (×{1 + num_workers})[/yellow]\n"
                f"  [dim]Each worker gets a copy of the cache[/dim]"
            )

        cache_widget.update(text)

    def _update_cache_options_visibility(self) -> None:
        """Show/hide cache options based on data pipeline selection."""
        if not self._state:
            return

        from sleap_nn.config_generator.tui.state import DataPipelineType

        is_caching = self._state._data_pipeline != DataPipelineType.TORCH_DATASET
        is_disk_cache = self._state._data_pipeline == DataPipelineType.DISK_CACHE

        # Cache options (shown when any caching is enabled)
        cache_option_ids = ["parallel-caching-row", "cache-workers-row"]
        for widget_id in cache_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if is_caching:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

        # Disk-specific options (shown only for disk cache)
        disk_option_ids = [
            "disk-cache-header",
            "cache-path-row",
            "use-existing-row",
            "delete-cache-row",
        ]
        for widget_id in disk_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if is_disk_cache:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

    def _update_imagenet_visibility(self) -> None:
        """Show/hide ImageNet weights option based on backbone selection.

        ImageNet pretrained weights are only available for ConvNeXt and SwinT,
        not for UNet backbones.
        """
        if not self._state:
            return

        # Check if backbone supports ImageNet pretrained weights
        backbone = self._state._backbone
        is_pretrained_backbone = backbone.startswith("convnext") or backbone.startswith(
            "swint"
        )

        # Standard model ImageNet row
        try:
            widget = self.query_one("#imagenet-pretrained-row")
            if is_pretrained_backbone:
                widget.remove_class("hidden")
            else:
                widget.add_class("hidden")
        except Exception:
            pass

        # Centroid model ImageNet row
        try:
            widget = self.query_one("#centroid-imagenet-row")
            if is_pretrained_backbone:
                widget.remove_class("hidden")
            else:
                widget.add_class("hidden")
        except Exception:
            pass

        # Instance model ImageNet row
        try:
            widget = self.query_one("#instance-imagenet-row")
            if is_pretrained_backbone:
                widget.remove_class("hidden")
            else:
                widget.add_class("hidden")
        except Exception:
            pass

    def _update_instance_cache_options_visibility(self) -> None:
        """Show/hide instance cache options based on data pipeline selection."""
        if not self._state:
            return

        from sleap_nn.config_generator.tui.state import DataPipelineType

        is_caching = self._state._data_pipeline != DataPipelineType.TORCH_DATASET
        is_disk_cache = self._state._data_pipeline == DataPipelineType.DISK_CACHE

        # Cache options (shown when any caching is enabled)
        cache_option_ids = [
            "instance-parallel-caching-row",
            "instance-cache-workers-row",
        ]
        for widget_id in cache_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if is_caching:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

        # Disk-specific options (shown only for disk cache)
        disk_option_ids = [
            "instance-disk-cache-header",
            "instance-cache-path-row",
            "instance-use-existing-row",
            "instance-delete-cache-row",
        ]
        for widget_id in disk_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if is_disk_cache:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

    def _update_instance_cache_memory_display(self) -> None:
        """Update the instance cache memory display.

        Note: Both centroid and instance models cache the same full-frame images.
        Cropping happens after loading from cache, so the cache size is identical.
        """
        try:
            cache_widget = self.query_one("#instance-cache-memory-display", Static)
        except Exception:
            return

        if not self._state:
            cache_widget.update("")
            return

        from sleap_nn.config_generator.tui.state import DataPipelineType

        # Hide if not caching
        if self._state._data_pipeline == DataPipelineType.TORCH_DATASET:
            cache_widget.update("")
            return

        # Cache is based on FULL FRAME size (same as centroid) - cropping happens after loading
        bytes_per_frame = (
            self._state.stats.max_height
            * self._state.stats.max_width
            * self._state.stats.num_channels
        )
        raw_cache_mb = (bytes_per_frame * self._state.stats.num_labeled_frames) / 1e6
        cache_with_overhead = raw_cache_mb * 1.2

        num_workers = self._state._num_workers
        is_memory_cache = self._state._data_pipeline == DataPipelineType.MEMORY_CACHE
        total_cache_mb = cache_with_overhead

        if is_memory_cache and num_workers > 0:
            # Each worker gets a copy
            total_cache_mb = cache_with_overhead * (1 + num_workers)

        cache_type = "Memory" if is_memory_cache else "Disk"

        if total_cache_mb < 4000:
            status_color = "green"
            status = "OK"
        elif total_cache_mb < 8000:
            status_color = "yellow"
            status = "Large"
        else:
            status_color = "red"
            status = "Very Large"

        text = (
            f"[bold]💾 Image Cache ({cache_type}):[/bold] [{status_color}]{status}[/{status_color}]\n"
            f"  Raw data: {raw_cache_mb:.1f} MB\n"
            f"  With overhead (1.2×): {cache_with_overhead:.1f} MB"
        )

        if is_memory_cache and num_workers > 0:
            text += (
                f"\n  [yellow]⚠ With {num_workers} workers: {total_cache_mb:.1f} MB (×{1 + num_workers})[/yellow]\n"
                f"  [dim]Each worker gets a copy of the cache[/dim]"
            )

        cache_widget.update(text)

    def _update_wandb_options_visibility(self) -> None:
        """Show/hide WandB options based on Enable WandB checkbox.

        WandB configuration options are only shown when WandB logging is enabled.
        """
        if not self._state:
            return

        wandb_enabled = self._state._wandb.enabled if self._state._wandb else False

        # Standard model WandB options
        wandb_option_ids = [
            "wandb-project-row",
            "wandb-entity-row",
            "wandb-name-row",
            "wandb-api-key-row",
            "wandb-mode-row",
            "wandb-viz-row",
            "wandb-save-viz-row",
        ]
        for widget_id in wandb_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if wandb_enabled:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

        # Centroid model WandB options
        centroid_wandb_ids = [
            "centroid-wandb-project-row",
            "centroid-wandb-entity-row",
            "centroid-wandb-name-row",
            "centroid-wandb-api-key-row",
            "centroid-wandb-mode-row",
            "centroid-wandb-viz-row",
            "centroid-wandb-save-viz-row",
        ]
        for widget_id in centroid_wandb_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if wandb_enabled:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

        # Instance model WandB options
        instance_wandb_ids = ["instance-wandb-project-row", "instance-wandb-entity-row"]
        for widget_id in instance_wandb_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if wandb_enabled:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

    def _update_viz_options_visibility(self) -> None:
        """Show/hide viz options based on Save Visualizations checkbox."""
        if not self._state:
            return

        viz_enabled = self._state._visualize_preds

        # All model viz options (standard, centroid, instance)
        viz_option_ids = [
            "viz-keep-folder-row",
            "centroid-viz-keep-folder-row",
            "instance-viz-keep-folder-row",
        ]
        for widget_id in viz_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if viz_enabled:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

    def _update_eval_options_visibility(self) -> None:
        """Show/hide evaluation options based on Enable Evaluation checkbox."""
        if not self._state:
            return

        eval_enabled = (
            self._state._evaluation.enabled if self._state._evaluation else False
        )

        # All model eval options (standard, centroid, instance)
        eval_option_ids = [
            "eval-frequency-row",
            "eval-oks-row",
            "centroid-eval-frequency-row",
            "centroid-eval-oks-row",
            "instance-eval-frequency-row",
            "instance-eval-oks-row",
        ]
        for widget_id in eval_option_ids:
            try:
                widget = self.query_one(f"#{widget_id}")
                if eval_enabled:
                    widget.remove_class("hidden")
                else:
                    widget.add_class("hidden")
            except Exception:
                pass

    def _update_model_info_display(self) -> None:
        """Update the model info display (RF, params, animal size, effective sigma)."""
        try:
            model_widget = self.query_one("#model-info-display", Static)
        except Exception:
            return

        if not self._state:
            model_widget.update("[dim]Load SLP file to see model info[/dim]")
            return

        import math

        # Get max animal size from stats
        max_animal_size = self._state.stats.max_bbox_size

        # Compute receptive field based on max_stride
        # RF = 1 + sum((kernel[l] - 1) * prod(strides[:l]))
        # Pre-computed values for UNet: stride 8->36, 16->76, 32->156, 64->316
        rf_table = {8: 36, 16: 76, 32: 156, 64: 316, 128: 636}
        rf_pixels = rf_table.get(self._state._max_stride, 76)

        # Scale RF by input scale to get effective RF in original image space
        effective_rf = (
            rf_pixels / self._state._input_scale
            if self._state._input_scale > 0
            else rf_pixels
        )

        # Get parameter estimate
        params = self._state.model_params_estimate
        params_str = f"{params / 1e6:.1f}M" if params >= 1e6 else f"{params / 1e3:.0f}K"

        # Get encoder/decoder blocks
        encoder_blocks = int(math.log2(self._state._max_stride))
        decoder_blocks = (
            int(math.log2(self._state._max_stride / self._state._output_stride))
            if self._state._output_stride > 0
            else encoder_blocks
        )

        # Compute effective Gaussian radius: sigma * output_stride * 2
        effective_sigma_radius = self._state._sigma * self._state._output_stride * 2

        # Check if RF covers the animal
        rf_status = "green" if effective_rf >= max_animal_size else "yellow"
        rf_note = "✓" if effective_rf >= max_animal_size else "⚠ RF < animal"

        # Build display text
        text = (
            f"[bold]Model Architecture:[/bold]\n"
            f"  Parameters: [cyan]~{params_str}[/cyan] | "
            f"Encoder: [yellow]{encoder_blocks} blocks[/yellow] | "
            f"Decoder: [yellow]{decoder_blocks} blocks[/yellow]\n"
            f"  Max Animal Size: [magenta]~{max_animal_size:.0f}px[/magenta] | "
            f"Receptive Field: [{rf_status}]{rf_pixels}px ({effective_rf:.0f}px scaled) {rf_note}[/{rf_status}]\n"
            f"  Gaussian Radius: [blue]{effective_sigma_radius:.0f}px[/blue] (2σ covers 95%)"
        )

        model_widget.update(text)

    def _compose_standard_config(self) -> ComposeResult:
        """Compose standard (non-topdown) configuration sections."""
        # Data section - main params
        with Container(classes="section-box"):
            yield Static("[bold]Data Configuration[/bold]", classes="section-header")
            yield from self._compose_data_params()

        # Data Augmentation section
        with Container(classes="section-box"):
            yield Static("[bold]Data Augmentation[/bold]", classes="section-header")
            yield from self._compose_data_augmentation_params()

        # Data Pipeline section (visible - NOT collapsible per webapp design)
        with Container(classes="section-box"):
            yield Static("[bold]Data Pipeline[/bold]", classes="section-header")
            yield from self._compose_data_pipeline_section()

        # Additional Data Parameters (collapsible)
        with Collapsible(
            title="Additional Data Parameters", classes="collapsible-section"
        ):
            yield from self._compose_additional_data_params()

        # Model section
        with Container(classes="section-box"):
            yield Static("[bold]Model Architecture[/bold]", classes="section-header")
            yield from self._compose_model_params()

        # Model-specific sections (PAF for bottom-up, class vector for multi-class)
        if self._state and self._state.is_bottomup:
            with Container(classes="model-specific-section"):
                yield Static(
                    "[bold]Part Affinity Fields (PAF)[/bold]", classes="section-header"
                )
                yield from self._compose_paf_params()

        if self._state and self._state.is_multiclass:
            with Container(classes="model-specific-section"):
                yield Static(
                    "[bold]Identity Classification[/bold]", classes="section-header"
                )
                yield from self._compose_class_vector_params()

        # Training section
        with Container(classes="section-box"):
            yield Static("[bold]Training[/bold]", classes="section-header")
            yield from self._compose_training_params()

        # Checkpoint section (collapsible)
        with Collapsible(title="Checkpoints & Logging", classes="collapsible-section"):
            yield from self._compose_checkpoint_params()

        # Advanced section (collapsible)
        with Collapsible(title="Advanced Settings", classes="collapsible-section"):
            yield from self._compose_advanced_params()

    def _compose_topdown_config(self) -> ComposeResult:
        """Compose top-down specific configuration with tabs."""
        with TabbedContent(id="topdown-tabs"):
            with TabPane("Shared Settings", id="shared-tab"):
                yield from self._compose_shared_topdown_params()

            with TabPane("Centroid Model", id="centroid-tab"):
                yield from self._compose_centroid_params()

            with TabPane("Instance Model", id="instance-tab"):
                yield from self._compose_instance_params()

    # ==================== DATA PARAMETERS ====================

    def _compose_data_params(self) -> ComposeResult:
        """Compose data configuration parameters (main section only)."""
        # Input Scale (prominent - main parameter)
        with Horizontal(classes="param-row"):
            yield Label("Input Scale:", classes="param-label")
            yield Input(
                value=str(self._state._input_scale if self._state else 1.0),
                id="scale-input",
                classes="param-input",
                type="number",
            )
            yield Label(
                "Resize factor (0.125-1.0) - lower = faster training",
                classes="param-hint",
            )

        # Show shape pipeline info
        if self._state:
            yield Static(id="shape-info-display", classes="shape-info")
            # Initial content will be set by _update_shape_display()

    def _compose_data_augmentation_params(self) -> ComposeResult:
        """Compose data augmentation parameters section."""
        aug = self._state._augmentation if self._state else None

        # Geometric augmentations
        yield Static("[dim]Geometric[/dim]", classes="subsection-header")

        # Rotation
        with Horizontal(classes="param-row"):
            yield Checkbox(
                "Rotation",
                value=aug.rotation_enabled if aug else True,
                id="rotation-checkbox",
            )
            yield Label("±", classes="param-label")
            yield Input(
                value=str(aug.rotation_max if aug else 15.0),
                id="rotation-input",
                classes="param-input",
                type="number",
            )
            yield Label("degrees", classes="param-hint")

        # Scale
        with Horizontal(classes="param-row"):
            yield Checkbox(
                "Scale",
                value=aug.scale_enabled if aug else True,
                id="scale-checkbox",
            )
            yield Input(
                value=str(aug.scale_min if aug else 0.9),
                id="scale-min-input",
                classes="param-input",
                type="number",
            )
            yield Label("to", classes="param-hint")
            yield Input(
                value=str(aug.scale_max if aug else 1.1),
                id="scale-max-input",
                classes="param-input",
                type="number",
            )

        # Translate
        with Horizontal(classes="param-row"):
            yield Checkbox(
                "Translate",
                value=aug.translate_enabled if aug else False,
                id="translate-checkbox",
            )
            yield Label("±", classes="param-label")
            yield Input(
                value=str(aug.translate if aug else 0),
                id="translate-input",
                classes="param-input",
                type="number",
            )
            yield Label("% (shift in x/y)", classes="param-hint")

        # Intensity augmentations
        yield Static("[dim]Intensity[/dim]", classes="subsection-header")

        # Brightness
        with Horizontal(classes="param-row"):
            yield Checkbox(
                "Brightness",
                value=aug.brightness_enabled if aug else False,
                id="brightness-checkbox",
            )
            yield Label("±", classes="param-label")
            yield Input(
                value=str(aug.brightness_limit if aug else 0.2),
                id="brightness-limit-input",
                classes="param-input",
                type="number",
            )
            yield Label("(0.2 = ±20%)", classes="param-hint")

        # Contrast
        with Horizontal(classes="param-row"):
            yield Checkbox(
                "Contrast",
                value=aug.contrast_enabled if aug else False,
                id="contrast-checkbox",
            )
            yield Label("±", classes="param-label")
            yield Input(
                value=str(aug.contrast_limit if aug else 0.2),
                id="contrast-limit-input",
                classes="param-input",
                type="number",
            )
            yield Label("(0.2 = ±20%)", classes="param-hint")

    def _compose_data_pipeline_section(self) -> ComposeResult:
        """Compose data pipeline section (visible, not collapsible - matches webapp)."""
        # Speed tip info box (matching webapp)
        yield Static(
            "[green bold]💡 Speed Tip:[/green bold] Set [bold]Num Workers[/bold] to 2+ and "
            "use [bold]Cache to Memory[/bold] or [bold]Cache to Disk[/bold] for faster training.",
            classes="info-box speed-tip",
        )

        # Num Workers + Data Pipeline side by side (matching webapp grid-2 layout)
        with Horizontal(classes="param-row"):
            yield Label("Num Workers:", classes="param-label")
            yield Select(
                [
                    ("0", "0"),
                    ("2 (Default)", "2"),
                    ("4", "4"),
                    ("8", "8"),
                ],
                value=str(self._state._num_workers if self._state else 2),
                id="num-workers-select",
                classes="param-input",
            )

        current_pipeline = (
            self._state._data_pipeline.value if self._state else "litdata"
        )
        with Horizontal(classes="param-row"):
            yield Label("Data Pipeline:", classes="param-label")
            yield Select(
                [
                    ("Video", "torch_dataset"),
                    ("Cache to Memory (default)", "litdata"),
                    ("Cache to Disk", "litdata_disk"),
                ],
                value=current_pipeline,
                id="data-pipeline-select",
                classes="param-input",
            )
            yield Label("Data loading method", classes="param-hint")

        # Cache Memory Estimate (shown when caching is enabled)
        yield Static(id="cache-memory-display", classes="memory-info")

        # Cache config options (shown when caching is enabled)
        cache = self._state._cache_config if self._state else None

        # Parallel Caching
        with Horizontal(classes="param-row", id="parallel-caching-row"):
            yield Label("Parallel Caching:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=cache.parallel_caching if cache else True,
                id="parallel-caching-checkbox",
            )
            yield Label("Cache images in parallel", classes="param-hint")

        # Cache Workers (for caching process)
        with Horizontal(classes="param-row", id="cache-workers-row"):
            yield Label("Cache Workers:", classes="param-label")
            yield Input(
                value=str(cache.cache_workers if cache else 0),
                id="cache-workers-input",
                classes="param-input",
                type="integer",
            )
            yield Label("Workers for caching (0 = main process)", classes="param-hint")

        # Disk cache specific options
        yield Static(
            "[dim]Disk Cache Options[/dim]",
            classes="subsection-header",
            id="disk-cache-header",
        )

        # Cache Image Path
        with Horizontal(classes="param-row", id="cache-path-row"):
            yield Label("Cache Path:", classes="param-label")
            yield Input(
                value=cache.cache_img_path if cache else "",
                id="cache-path-input",
                classes="param-input-wide",
                placeholder="./cache (auto if empty)",
            )

        # Use Existing Images
        with Horizontal(classes="param-row", id="use-existing-row"):
            yield Label("Use Existing:", classes="param-label")
            yield Checkbox(
                "Reuse cached images",
                value=cache.use_existing_imgs if cache else False,
                id="use-existing-checkbox",
            )
            yield Label("Skip caching if images exist", classes="param-hint")

        # Delete Cache After Training
        with Horizontal(classes="param-row", id="delete-cache-row"):
            yield Label("Delete After:", classes="param-label")
            yield Checkbox(
                "Delete cache after training",
                value=cache.delete_cache_after_training if cache else True,
                id="delete-cache-checkbox",
            )
            yield Label("Clean up disk space", classes="param-hint")

    def _compose_additional_data_params(self) -> ComposeResult:
        """Compose additional data parameters (collapsible section)."""
        # User Instances Only
        with Horizontal(classes="param-row"):
            yield Label("User Instances:", classes="param-label")
            yield Checkbox(
                "Only user-labeled instances",
                value=self._state._user_instances_only if self._state else True,
                id="user-instances-checkbox",
            )
            yield Label("Filter out predicted instances", classes="param-hint")

        # Validation Fraction
        with Horizontal(classes="param-row"):
            yield Label("Val Fraction:", classes="param-label")
            yield Input(
                value=str(self._state._validation_fraction if self._state else 0.1),
                id="val-fraction-input",
                classes="param-input",
                type="number",
            )
            yield Label(
                "Fraction held out for validation (0.05-0.3)", classes="param-hint"
            )

        # Input Channels
        current_channels = "grayscale"
        if self._state:
            if self._state._ensure_rgb:
                current_channels = "rgb"
            elif self._state._ensure_grayscale:
                current_channels = "grayscale"

        with Horizontal(classes="param-row"):
            yield Label("Input Channels:", classes="param-label")
            yield Select(
                [
                    ("Grayscale (1 channel)", "grayscale"),
                    ("RGB (3 channels)", "rgb"),
                ],
                value=current_channels,
                id="channels-select",
                classes="param-input",
            )
            yield Label("Image color mode", classes="param-hint")

        # Max Height / Max Width on same row conceptually
        with Horizontal(classes="param-row"):
            yield Label("Max Height:", classes="param-label")
            yield Input(
                value=(
                    str(self._state._max_height)
                    if self._state and self._state._max_height
                    else ""
                ),
                id="max-height-input",
                classes="param-input",
                type="integer",
                placeholder="auto",
            )
            yield Label("Max Width:", classes="param-label")
            yield Input(
                value=(
                    str(self._state._max_width)
                    if self._state and self._state._max_width
                    else ""
                ),
                id="max-width-input",
                classes="param-input",
                type="integer",
                placeholder="auto",
            )

    # ==================== MODEL PARAMETERS ====================

    def _compose_model_params(self) -> ComposeResult:
        """Compose model architecture parameters."""
        # Model info display (RF and params)
        if self._state:
            yield Static(id="model-info-display", classes="shape-info")

        # Backbone selection
        with Horizontal(classes="param-row"):
            yield Label("Backbone:", classes="param-label")
            yield Select(
                [
                    ("UNet (recommended)", "unet_medium_rf"),
                    ("UNet Large RF", "unet_large_rf"),
                    ("ConvNeXt Tiny", "convnext_tiny"),
                    ("ConvNeXt Small", "convnext_small"),
                    ("SwinT Tiny", "swint_tiny"),
                    ("SwinT Small", "swint_small"),
                ],
                value=self._state._backbone if self._state else "unet_medium_rf",
                id="backbone-select",
                classes="param-input",
            )
            yield Label("Network architecture", classes="param-hint")

        # Max stride (UNet only)
        with Horizontal(classes="param-row", id="max-stride-row"):
            yield Label("Max Stride:", classes="param-label")
            yield Select(
                [("8", "8"), ("16", "16"), ("32", "32"), ("64", "64")],
                value=str(self._state._max_stride if self._state else 16),
                id="max-stride-select",
                classes="param-input",
            )
            yield Label("Receptive field (larger = more context)", classes="param-hint")

        # Base Filters (UNet only)
        with Horizontal(classes="param-row", id="filters-row"):
            yield Label("Base Filters:", classes="param-label")
            yield Input(
                value=str(self._state._filters if self._state else 32),
                id="filters-input",
                classes="param-input",
                type="integer",
            )
            yield Label("Initial filter count (model capacity)", classes="param-hint")

        # Filters Rate (UNet only)
        with Horizontal(classes="param-row", id="filters-rate-row"):
            yield Label("Filters Rate:", classes="param-label")
            yield Input(
                value=str(self._state._filters_rate if self._state else 2.0),
                id="filters-rate-input",
                classes="param-input",
                type="number",
            )
            yield Label("Filter scaling per block", classes="param-hint")

        # Sigma (confidence map spread)
        with Horizontal(classes="param-row"):
            yield Label("Sigma:", classes="param-label")
            yield Input(
                value=str(self._state._sigma if self._state else 5.0),
                id="sigma-input",
                classes="param-input",
                type="number",
            )
            yield Label("Confidence map spread (pixels)", classes="param-hint")

        # Output Stride
        with Horizontal(classes="param-row"):
            yield Label("Output Stride:", classes="param-label")
            yield Select(
                [
                    ("1 (full res)", "1"),
                    ("2 (half res)", "2"),
                    ("4 (quarter)", "4"),
                    ("8 (1/8 res)", "8"),
                    ("16 (1/16 res)", "16"),
                ],
                value=str(self._state._output_stride if self._state else 2),
                id="output-stride-select",
                classes="param-input",
            )
            yield Label("Higher = faster but less precise", classes="param-hint")

        # ImageNet Pretrained (for ConvNeXt/SwinT)
        with Horizontal(classes="param-row", id="imagenet-pretrained-row"):
            yield Label("ImageNet Weights:", classes="param-label")
            yield Checkbox(
                "Use ImageNet pretrained",
                value=self._state._use_imagenet_pretrained if self._state else True,
                id="imagenet-pretrained-checkbox",
            )
            yield Label("For ConvNeXt/SwinT backbones", classes="param-hint")

        # Pretrained Backbone Path
        with Horizontal(classes="param-row"):
            yield Label("Pretrained Backbone:", classes="param-label")
            yield Input(
                value=self._state._pretrained_backbone if self._state else "",
                id="pretrained-backbone-input",
                classes="param-input-wide",
                placeholder="Path to .ckpt (optional)",
            )

        # Pretrained Head Path
        with Horizontal(classes="param-row"):
            yield Label("Pretrained Head:", classes="param-label")
            yield Input(
                value=self._state._pretrained_head if self._state else "",
                id="pretrained-head-input",
                classes="param-input-wide",
                placeholder="Path to .ckpt (optional)",
            )

    # ==================== PAF PARAMETERS (Bottom-Up) ====================

    def _compose_paf_params(self) -> ComposeResult:
        """Compose Part Affinity Field parameters for bottom-up models."""
        paf = self._state._paf_config if self._state else None

        # PAF Sigma
        with Horizontal(classes="param-row"):
            yield Label("PAF Sigma:", classes="param-label")
            yield Input(
                value=str(paf.sigma if paf else 15.0),
                id="paf-sigma-input",
                classes="param-input",
                type="number",
            )
            yield Label(
                "Vector field width (10-20 precise, 15 default)", classes="param-hint"
            )

        # PAF Output Stride
        with Horizontal(classes="param-row"):
            yield Label("PAF Output Stride:", classes="param-label")
            yield Select(
                [
                    ("1 (full res)", "1"),
                    ("2 (half res)", "2"),
                    ("4 (quarter)", "4"),
                    ("8 (1/8 res)", "8"),
                    ("16 (1/16 res)", "16"),
                ],
                value=str(paf.output_stride if paf else 4),
                id="paf-output-stride-select",
                classes="param-input",
            )
            yield Label("Usually 2× confmaps stride", classes="param-hint")

        # Confmaps Loss Weight
        with Horizontal(classes="param-row"):
            yield Label("Confmaps Loss:", classes="param-label")
            yield Input(
                value=str(paf.confmaps_loss_weight if paf else 1.0),
                id="confmaps-loss-weight-input",
                classes="param-input",
                type="number",
            )
            yield Label(
                "Loss weight for keypoint heatmaps (1.0 default)", classes="param-hint"
            )

        # PAF Loss Weight
        with Horizontal(classes="param-row"):
            yield Label("PAF Loss Weight:", classes="param-label")
            yield Input(
                value=str(paf.loss_weight if paf else 1.0),
                id="paf-loss-weight-input",
                classes="param-input",
                type="number",
            )
            yield Label(
                "Increase to emphasize limb grouping (1.0 default)",
                classes="param-hint",
            )

    # ==================== CLASS VECTOR PARAMETERS (Multi-Class) ====================

    def _compose_class_vector_params(self) -> ComposeResult:
        """Compose class vector parameters for multi-class models."""
        cv = self._state._class_vector_config if self._state else None

        # Number of FC Layers
        with Horizontal(classes="param-row"):
            yield Label("FC Layers:", classes="param-label")
            yield Select(
                [("1", "1"), ("2", "2"), ("3", "3")],
                value=str(cv.num_fc_layers if cv else 1),
                id="fc-layers-select",
                classes="param-input",
            )
            yield Label(
                "Fully-connected layers for classification", classes="param-hint"
            )

        # FC Units
        with Horizontal(classes="param-row"):
            yield Label("FC Units:", classes="param-label")
            yield Input(
                value=str(cv.num_fc_units if cv else 64),
                id="fc-units-input",
                classes="param-input",
                type="integer",
            )
            yield Label("Units per FC layer", classes="param-hint")

        # Class Loss Weight
        with Horizontal(classes="param-row"):
            yield Label("Class Loss Weight:", classes="param-label")
            yield Input(
                value=str(cv.loss_weight if cv else 1.0),
                id="class-loss-weight-input",
                classes="param-input",
                type="number",
            )
            yield Label("Relative weight for classification loss", classes="param-hint")

    # ==================== TRAINING PARAMETERS ====================

    def _compose_training_params(self) -> ComposeResult:
        """Compose training hyperparameters (matching centroid layout)."""
        # Basic params visible (like centroid)
        # Batch size
        with Horizontal(classes="param-row"):
            yield Label("Batch Size:", classes="param-label")
            yield Select(
                [
                    ("1", "1"),
                    ("2", "2"),
                    ("4", "4"),
                    ("8", "8"),
                    ("16", "16"),
                    ("32", "32"),
                ],
                value=str(self._state._batch_size if self._state else 4),
                id="batch-size-select",
                classes="param-input",
            )
            yield Label("Samples per batch", classes="param-hint")

        # Max epochs
        with Horizontal(classes="param-row"):
            yield Label("Max Epochs:", classes="param-label")
            yield Input(
                value=str(self._state._max_epochs if self._state else 200),
                id="max-epochs-input",
                classes="param-input",
                type="integer",
            )
            yield Label("Maximum training epochs", classes="param-hint")

        # Learning rate
        with Horizontal(classes="param-row"):
            yield Label("Learning Rate:", classes="param-label")
            yield Input(
                value=str(self._state._learning_rate if self._state else 1e-4),
                id="lr-input",
                classes="param-input",
                type="number",
            )
            yield Label(
                "Initial optimizer step size (1e-4 is good default)",
                classes="param-hint",
            )

        # Advanced training params in collapsible
        with Collapsible(title="Advanced Training", classes="collapsible-section"):
            # Optimizer
            with Horizontal(classes="param-row"):
                yield Label("Optimizer:", classes="param-label")
                yield Select(
                    [("Adam", "Adam"), ("AdamW", "AdamW")],
                    value=self._state._optimizer if self._state else "Adam",
                    id="optimizer-select",
                    classes="param-input",
                )
                yield Label("Optimization algorithm", classes="param-hint")

            # Accelerator
            with Horizontal(classes="param-row"):
                yield Label("Accelerator:", classes="param-label")
                yield Select(
                    [
                        ("Auto", "auto"),
                        ("GPU", "gpu"),
                        ("MPS (Apple Silicon)", "mps"),
                        ("CPU", "cpu"),
                    ],
                    value=self._state._accelerator if self._state else "auto",
                    id="accelerator-select",
                    classes="param-input",
                )
                yield Label("Hardware for training", classes="param-hint")

            yield Static("[dim]Early Stopping[/dim]", classes="subsection-header")

            # Early stopping
            with Horizontal(classes="param-row"):
                yield Label("Enable:", classes="param-label")
                yield Checkbox(
                    "Stop if validation plateaus",
                    value=self._state._early_stopping if self._state else True,
                    id="early-stopping-checkbox",
                )

            # Early stopping patience
            with Horizontal(classes="param-row", id="es-patience-row"):
                yield Label("Patience:", classes="param-label")
                yield Input(
                    value=str(
                        self._state._early_stopping_patience if self._state else 10
                    ),
                    id="es-patience-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs without improvement", classes="param-hint")

            # Early stopping min delta
            with Horizontal(classes="param-row", id="es-min-delta-row"):
                yield Label("Min Delta:", classes="param-label")
                yield Input(
                    value=str(
                        self._state._early_stopping_min_delta if self._state else 1e-8
                    ),
                    id="es-min-delta-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Minimum improvement threshold", classes="param-hint")

            # Min Steps per Epoch
            with Horizontal(classes="param-row"):
                yield Label("Min Steps/Epoch:", classes="param-label")
                yield Input(
                    value=str(self._state._min_steps_per_epoch if self._state else 200),
                    id="min-steps-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Minimum training steps per epoch", classes="param-hint")

            # Random Seed
            with Horizontal(classes="param-row"):
                yield Label("Random Seed:", classes="param-label")
                yield Input(
                    value=(
                        str(self._state._random_seed)
                        if self._state and self._state._random_seed
                        else ""
                    ),
                    id="random-seed-input",
                    classes="param-input",
                    type="integer",
                    placeholder="None (random)",
                )
                yield Label("For reproducibility", classes="param-hint")

            yield Static(
                "[dim]Learning Rate Scheduler[/dim]", classes="subsection-header"
            )

            # LR Scheduler
            scheduler_type = (
                self._state._scheduler.type.value if self._state else "none"
            )
            with Horizontal(classes="param-row"):
                yield Label("Scheduler:", classes="param-label")
                yield Select(
                    [
                        ("Reduce on Plateau", "ReduceLROnPlateau"),
                        ("Cosine Annealing + Warmup", "CosineAnnealingWarmup"),
                        ("Linear Warmup + Decay", "LinearWarmupLinearDecay"),
                        ("Step LR", "StepLR"),
                        ("None (Constant)", "none"),
                    ],
                    value=(
                        scheduler_type
                        if scheduler_type != "none"
                        else "ReduceLROnPlateau"
                    ),
                    id="scheduler-select",
                    classes="param-input",
                )
                yield Label("LR decay strategy", classes="param-hint")

            # Scheduler-specific parameters
            yield from self._compose_scheduler_params()

    def _compose_scheduler_params(self) -> ComposeResult:
        """Compose scheduler-specific parameters based on selected scheduler type."""
        scheduler = self._state._scheduler if self._state else None
        scheduler_type = scheduler.type if scheduler else SchedulerType.NONE

        # ReduceLROnPlateau params
        with Container(
            id="scheduler-reduce-params",
            classes=(
                "hidden" if scheduler_type != SchedulerType.REDUCE_ON_PLATEAU else ""
            ),
        ):
            with Horizontal(classes="param-row"):
                yield Label("Factor:", classes="param-label")
                yield Input(
                    value=str(scheduler.factor if scheduler else 0.5),
                    id="scheduler-factor-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("LR multiply factor on plateau", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Patience:", classes="param-label")
                yield Input(
                    value=str(scheduler.plateau_patience if scheduler else 5),
                    id="scheduler-patience-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs to wait before reducing", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Min LR:", classes="param-label")
                yield Input(
                    value=str(scheduler.min_lr if scheduler else 1e-8),
                    id="scheduler-min-lr-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Minimum learning rate", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Cooldown:", classes="param-label")
                yield Input(
                    value=str(scheduler.cooldown if scheduler else 3),
                    id="scheduler-cooldown-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs to wait after LR reduction", classes="param-hint")

        # StepLR params
        with Container(
            id="scheduler-step-params",
            classes="hidden" if scheduler_type != SchedulerType.STEP_LR else "",
        ):
            with Horizontal(classes="param-row"):
                yield Label("Step Size:", classes="param-label")
                yield Input(
                    value=str(scheduler.step_size if scheduler else 10),
                    id="scheduler-step-size-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs between LR decay", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Gamma:", classes="param-label")
                yield Input(
                    value=str(scheduler.gamma if scheduler else 0.1),
                    id="scheduler-gamma-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("LR decay multiplier", classes="param-hint")

        # CosineAnnealingWarmup params
        with Container(
            id="scheduler-cosine-params",
            classes=(
                "hidden"
                if scheduler_type != SchedulerType.COSINE_ANNEALING_WARMUP
                else ""
            ),
        ):
            with Horizontal(classes="param-row"):
                yield Label("Warmup Epochs:", classes="param-label")
                yield Input(
                    value=str(scheduler.warmup_epochs if scheduler else 5),
                    id="scheduler-warmup-epochs-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs for warmup phase", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Warmup Start LR:", classes="param-label")
                yield Input(
                    value=str(scheduler.warmup_start_lr if scheduler else 0),
                    id="scheduler-warmup-start-lr-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Initial LR during warmup", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Eta Min:", classes="param-label")
                yield Input(
                    value=str(scheduler.eta_min if scheduler else 0),
                    id="scheduler-eta-min-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Minimum LR after cosine decay", classes="param-hint")

        # LinearWarmupLinearDecay params
        with Container(
            id="scheduler-linear-params",
            classes=(
                "hidden"
                if scheduler_type != SchedulerType.LINEAR_WARMUP_LINEAR_DECAY
                else ""
            ),
        ):
            with Horizontal(classes="param-row"):
                yield Label("Warmup Epochs:", classes="param-label")
                yield Input(
                    value=str(scheduler.linear_warmup_epochs if scheduler else 5),
                    id="scheduler-linear-warmup-epochs-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs for warmup phase", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Warmup Start LR:", classes="param-label")
                yield Input(
                    value=str(scheduler.linear_warmup_start_lr if scheduler else 0),
                    id="scheduler-linear-warmup-start-lr-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Initial LR during warmup", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("End LR:", classes="param-label")
                yield Input(
                    value=str(scheduler.end_lr if scheduler else 0),
                    id="scheduler-end-lr-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Final LR after linear decay", classes="param-hint")

    # ==================== CHECKPOINT PARAMETERS ====================

    def _compose_checkpoint_params(self) -> ComposeResult:
        """Compose checkpoint and logging parameters."""
        ckpt = self._state._checkpoint if self._state else None

        # Save Checkpoints (master toggle)
        with Horizontal(classes="param-row"):
            yield Label("Save Checkpoints:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=ckpt.enabled if ckpt else True,
                id="save-ckpt-checkbox",
            )
            yield Label("Enable checkpoint saving", classes="param-hint")

        # Checkpoint Directory
        with Horizontal(classes="param-row"):
            yield Label("Checkpoint Dir:", classes="param-label")
            yield Input(
                value=ckpt.checkpoint_dir if ckpt else "",
                id="ckpt-dir-input",
                classes="param-input-wide",
                placeholder="./models",
            )

        # Run Name
        with Horizontal(classes="param-row"):
            yield Label("Run Name:", classes="param-label")
            yield Input(
                value=ckpt.run_name if ckpt else "",
                id="run-name-input",
                classes="param-input-wide",
                placeholder="auto-generated",
            )

        # Resume from checkpoint
        with Horizontal(classes="param-row"):
            yield Label("Resume From:", classes="param-label")
            yield Input(
                value=ckpt.resume_from if ckpt else "",
                id="resume-ckpt-input",
                classes="param-input-wide",
                placeholder="Path to checkpoint.ckpt",
            )

        # Save Top K
        with Horizontal(classes="param-row"):
            yield Label("Save Top K:", classes="param-label")
            yield Input(
                value=str(ckpt.save_top_k if ckpt else 1),
                id="save-top-k-input",
                classes="param-input",
                type="integer",
            )
            yield Label("Number of best checkpoints to keep", classes="param-hint")

        # Save Last
        with Horizontal(classes="param-row"):
            yield Label("Save Last:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=ckpt.save_last if ckpt else False,
                id="save-last-checkbox",
            )
            yield Label("Keep last.ckpt symlink", classes="param-hint")

        yield Static("[dim]Weights & Biases[/dim]", classes="subsection-header")

        # WandB Enable
        wandb = self._state._wandb if self._state else None
        with Horizontal(classes="param-row"):
            yield Label("Enable WandB:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=wandb.enabled if wandb else False,
                id="wandb-checkbox",
            )
            yield Label("Log to Weights & Biases", classes="param-hint")

        # WandB Project (hidden until WandB enabled)
        with Horizontal(classes="param-row hidden", id="wandb-project-row"):
            yield Label("WandB Project:", classes="param-label")
            yield Input(
                value=wandb.project if wandb else "sleap-training",
                id="wandb-project-input",
                classes="param-input-wide",
            )

        # WandB Entity (hidden until WandB enabled)
        with Horizontal(classes="param-row hidden", id="wandb-entity-row"):
            yield Label("WandB Entity:", classes="param-label")
            yield Input(
                value=wandb.entity if wandb else "",
                id="wandb-entity-input",
                classes="param-input-wide",
                placeholder="username or team",
            )

        # WandB Run Name (hidden until WandB enabled)
        with Horizontal(classes="param-row hidden", id="wandb-name-row"):
            yield Label("WandB Name:", classes="param-label")
            yield Input(
                value=wandb.name if wandb else "",
                id="wandb-name-input",
                classes="param-input-wide",
                placeholder="auto-generated",
            )

        # WandB API Key (hidden until WandB enabled)
        with Horizontal(classes="param-row hidden", id="wandb-api-key-row"):
            yield Label("WandB API Key:", classes="param-label")
            yield Input(
                value=wandb.api_key if wandb else "",
                id="wandb-api-key-input",
                classes="param-input-wide",
                placeholder="(uses env var if empty)",
                password=True,
            )

        # WandB Mode (hidden until WandB enabled)
        with Horizontal(classes="param-row hidden", id="wandb-mode-row"):
            yield Label("WandB Mode:", classes="param-label")
            yield Select(
                [
                    ("Online", "online"),
                    ("Offline", "offline"),
                    ("Disabled", "disabled"),
                ],
                value=wandb.mode if wandb else "online",
                id="wandb-mode-select",
                classes="param-input",
            )
            yield Label("Logging mode", classes="param-hint")

        # WandB Visualization options (hidden until WandB enabled)
        with Horizontal(classes="param-row hidden", id="wandb-viz-row"):
            yield Label("Log Visualizations:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=wandb.viz_enabled if wandb else True,
                id="wandb-viz-checkbox",
            )
            yield Label("Log prediction visualizations to WandB", classes="param-hint")

        with Horizontal(classes="param-row hidden", id="wandb-save-viz-row"):
            yield Label("Upload Local Viz:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=wandb.save_viz_imgs if wandb else False,
                id="wandb-save-viz-checkbox",
            )
            yield Label("Upload local visualization images", classes="param-hint")

        yield Static("[dim]Save Visualizations[/dim]", classes="subsection-header")

        # Save Visualizations toggle (matches webapp enable-viz)
        with Horizontal(classes="param-row"):
            yield Label("Save Visualizations:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=self._state._visualize_preds if self._state else False,
                id="save-viz-checkbox",
            )
            yield Label("Save prediction visualizations locally", classes="param-hint")

        # Keep Viz Folder (hidden until Save Viz enabled - matches webapp)
        with Horizontal(classes="param-row hidden", id="viz-keep-folder-row"):
            yield Label("Keep Viz Folder:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=self._state._keep_viz if self._state else False,
                id="viz-keep-folder-checkbox",
            )
            yield Label(
                "Keep visualization folder after training", classes="param-hint"
            )

        yield Static("[dim]Evaluation[/dim]", classes="subsection-header")

        # Enable Evaluation toggle (matches webapp enable-eval)
        evaluation = self._state._evaluation if self._state else None
        with Horizontal(classes="param-row"):
            yield Label("Enable Evaluation:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=evaluation.enabled if evaluation else False,
                id="eval-checkbox",
            )
            yield Label("Run OKS evaluation during training", classes="param-hint")

        # Eval options (hidden until Enable Eval is checked)
        with Horizontal(classes="param-row hidden", id="eval-frequency-row"):
            yield Label("Eval Frequency:", classes="param-label")
            yield Input(
                value=str(evaluation.frequency if evaluation else 1),
                id="eval-frequency-input",
                classes="param-input",
                type="integer",
            )
            yield Label("Run eval every N epochs", classes="param-hint")

        with Horizontal(classes="param-row hidden", id="eval-oks-row"):
            yield Label("OKS Stddev:", classes="param-label")
            yield Input(
                value=str(evaluation.oks_stddev if evaluation else 0.025),
                id="eval-oks-input",
                classes="param-input",
                type="number",
            )
            yield Label("Standard deviation for OKS scoring", classes="param-hint")

    # ==================== ADVANCED PARAMETERS ====================

    def _compose_advanced_params(self) -> ComposeResult:
        """Compose advanced training parameters (less commonly changed)."""
        # Devices (number of GPUs)
        with Horizontal(classes="param-row"):
            yield Label("Devices:", classes="param-label")
            yield Select(
                [
                    ("Auto", "auto"),
                    ("1", "1"),
                    ("2", "2"),
                    ("4", "4"),
                    ("8", "8"),
                ],
                value=self._state._devices if self._state else "auto",
                id="devices-select",
                classes="param-input",
            )
            yield Label("Number of GPUs to use", classes="param-hint")

        # Progress Bar (moved from Logging to Advanced)
        with Horizontal(classes="param-row"):
            yield Label("Progress Bar:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=self._state._enable_progress_bar if self._state else True,
                id="progress-bar-checkbox",
            )
            yield Label("Show progress during training", classes="param-hint")

        yield Static(
            "[dim]Online Hard Keypoint Mining (OHKM)[/dim]", classes="subsection-header"
        )

        ohkm = self._state._ohkm if self._state else None
        with Horizontal(classes="param-row"):
            yield Label("Enable OHKM:", classes="param-label")
            yield Checkbox(
                "Enabled",
                value=ohkm.enabled if ohkm else False,
                id="ohkm-checkbox",
            )
            yield Label("Focus training on difficult keypoints", classes="param-hint")

        with Horizontal(classes="param-row"):
            yield Label("Hard-to-Easy Ratio:", classes="param-label")
            yield Input(
                value=str(ohkm.hard_to_easy_ratio if ohkm else 2.0),
                id="ohkm-ratio-input",
                classes="param-input",
                type="number",
            )
            yield Label("Ratio to classify as hard", classes="param-hint")

        with Horizontal(classes="param-row"):
            yield Label("OHKM Loss Scale:", classes="param-label")
            yield Input(
                value=str(ohkm.loss_scale if ohkm else 5.0),
                id="ohkm-scale-input",
                classes="param-input",
                type="number",
            )
            yield Label("Scale factor for hard keypoint losses", classes="param-hint")

        with Horizontal(classes="param-row"):
            yield Label("Min Hard Keypoints:", classes="param-label")
            yield Input(
                value=str(ohkm.min_hard_keypoints if ohkm else 2),
                id="ohkm-min-hard-input",
                classes="param-input",
                type="integer",
            )
            yield Label("Minimum keypoints to classify as hard", classes="param-hint")

        with Horizontal(classes="param-row"):
            yield Label("Max Hard Keypoints:", classes="param-label")
            yield Input(
                value=(
                    str(ohkm.max_hard_keypoints)
                    if ohkm and ohkm.max_hard_keypoints
                    else ""
                ),
                id="ohkm-max-hard-input",
                classes="param-input",
                type="integer",
                placeholder="none",
            )
            yield Label("Maximum (empty = unlimited)", classes="param-hint")

    # ==================== TOP-DOWN SPECIFIC ====================

    def _compose_shared_topdown_params(self) -> ComposeResult:
        """Compose shared parameters for top-down models (anchor point only)."""
        # Anchor part selection with visibility percentages
        with Container(classes="section-box"):
            yield Static("[bold]Anchor Point[/bold]", classes="section-header")
            yield Static(
                "[dim]Select a keypoint to use as the reference for centering crops. "
                "The percentage shows how often each keypoint is labeled.[/dim]"
            )

            # Build options with visibility percentages
            nodes = self._state.skeleton_nodes if self._state else []
            visibility = self._state.stats.node_visibility if self._state else {}

            options = [("(auto - centroid)", "")]
            for node in nodes:
                pct = visibility.get(node, 0) if visibility else 0
                # Color code: green >80%, orange >50%, red <=50%
                if pct > 80:
                    color = "green"
                elif pct > 50:
                    color = "yellow"
                else:
                    color = "red"
                # Format: "node_name (95%)"
                label = f"{node} ([{color}]{pct:.0f}%[/{color}])"
                options.append((label, node))

            current_value = (
                self._state._anchor_part
                if self._state and self._state._anchor_part
                else ""
            )

            with Horizontal(classes="param-row"):
                yield Label("Anchor Part:", classes="param-label")
                yield Select(
                    options,
                    value=current_value,
                    id="anchor-part-select",
                    classes="param-input-wide",
                )

    def _compose_centroid_params(self) -> ComposeResult:
        """Compose centroid model specific parameters (full configuration like web app)."""
        # Data configuration - main params
        with Container(classes="section-box"):
            yield Static("[bold]Data Configuration[/bold]", classes="section-header")

            # Scale for centroid (typically lower)
            with Horizontal(classes="param-row"):
                yield Label("Input Scale:", classes="param-label")
                yield Input(
                    value=str(self._state._input_scale if self._state else 0.5),
                    id="centroid-scale-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Lower scale OK for centroids (0.5 typical)", classes="param-hint"
                )

            # Shape info display
            yield Static(id="centroid-shape-info-display", classes="shape-info")

        # Data Augmentation section
        with Container(classes="section-box"):
            yield Static("[bold]Data Augmentation[/bold]", classes="section-header")
            aug = self._state._augmentation if self._state else None

            yield Static("[dim]Geometric[/dim]", classes="subsection-header")

            # Rotation
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Rotation",
                    value=aug.rotation_enabled if aug else True,
                    id="centroid-rotation-checkbox",
                )
                yield Label("±", classes="param-label")
                yield Input(
                    value=str(aug.rotation_max if aug else 15.0),
                    id="centroid-rotation-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("degrees", classes="param-hint")

            # Scale
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Scale",
                    value=aug.scale_enabled if aug else True,
                    id="centroid-scale-checkbox",
                )
                yield Input(
                    value=str(aug.scale_min if aug else 0.9),
                    id="centroid-scale-min-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("to", classes="param-hint")
                yield Input(
                    value=str(aug.scale_max if aug else 1.1),
                    id="centroid-scale-max-input",
                    classes="param-input",
                    type="number",
                )

            # Translate
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Translate",
                    value=aug.translate_enabled if aug else False,
                    id="centroid-translate-checkbox",
                )
                yield Input(
                    value=str(aug.translate if aug else 0.0),
                    id="centroid-translate-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("fraction (0-0.3)", classes="param-hint")

            yield Static("[dim]Intensity[/dim]", classes="subsection-header")

            # Brightness
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Brightness",
                    value=aug.brightness_enabled if aug else False,
                    id="centroid-brightness-checkbox",
                )
                yield Label("±", classes="param-label")
                yield Input(
                    value=str(aug.brightness_limit if aug else 0.2),
                    id="centroid-brightness-input",
                    classes="param-input",
                    type="number",
                )

            # Contrast
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Contrast",
                    value=aug.contrast_enabled if aug else False,
                    id="centroid-contrast-checkbox",
                )
                yield Label("±", classes="param-label")
                yield Input(
                    value=str(aug.contrast_limit if aug else 0.2),
                    id="centroid-contrast-input",
                    classes="param-input",
                    type="number",
                )

        # Data Pipeline section (visible - matches webapp layout)
        with Container(classes="section-box"):
            yield Static("[bold]Data Pipeline[/bold]", classes="section-header")

            # Speed tip info box (matching webapp)
            yield Static(
                "[green bold]💡 Speed Tip:[/green bold] Set [bold]Num Workers[/bold] to 2+ and "
                "use [bold]Cache to Memory[/bold] or [bold]Cache to Disk[/bold] for faster training.",
                classes="info-box speed-tip",
            )

            # Num Workers
            with Horizontal(classes="param-row"):
                yield Label("Num Workers:", classes="param-label")
                yield Select(
                    [
                        ("0", "0"),
                        ("2 (Default)", "2"),
                        ("4", "4"),
                        ("8", "8"),
                    ],
                    value=str(self._state._num_workers if self._state else 2),
                    id="centroid-num-workers-select",
                    classes="param-input",
                )
                yield Label("Data loader workers (0 for video)", classes="param-hint")

            # Data Pipeline
            current_pipeline = (
                self._state._data_pipeline.value if self._state else "litdata"
            )
            with Horizontal(classes="param-row"):
                yield Label("Data Pipeline:", classes="param-label")
                yield Select(
                    [
                        ("Video", "torch_dataset"),
                        ("Cache to Memory (default)", "litdata"),
                        ("Cache to Disk", "litdata_disk"),
                    ],
                    value=current_pipeline,
                    id="centroid-data-pipeline-select",
                    classes="param-input",
                )
                yield Label("Data loading method", classes="param-hint")

            # Cache Memory Estimate
            yield Static(id="centroid-cache-memory-display", classes="memory-info")

            # Cache config options
            cache = self._state._cache_config if self._state else None

            # Parallel Caching
            with Horizontal(classes="param-row", id="centroid-parallel-caching-row"):
                yield Label("Parallel Caching:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=cache.parallel_caching if cache else True,
                    id="centroid-parallel-caching-checkbox",
                )
                yield Label("Cache images in parallel", classes="param-hint")

            # Cache Workers
            with Horizontal(classes="param-row", id="centroid-cache-workers-row"):
                yield Label("Cache Workers:", classes="param-label")
                yield Input(
                    value=str(cache.cache_workers if cache else 0),
                    id="centroid-cache-workers-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label(
                    "Workers for caching (0 = main process)", classes="param-hint"
                )

            # Disk cache specific options
            yield Static(
                "[dim]Disk Cache Options[/dim]",
                classes="subsection-header",
                id="centroid-disk-cache-header",
            )

            # Cache Image Path
            with Horizontal(classes="param-row", id="centroid-cache-path-row"):
                yield Label("Cache Path:", classes="param-label")
                yield Input(
                    value=cache.cache_img_path if cache else "",
                    id="centroid-cache-path-input",
                    classes="param-input-wide",
                    placeholder="./cache (auto if empty)",
                )

            # Use Existing Images
            with Horizontal(classes="param-row", id="centroid-use-existing-row"):
                yield Label("Use Existing:", classes="param-label")
                yield Checkbox(
                    "Reuse cached images",
                    value=cache.use_existing_imgs if cache else False,
                    id="centroid-use-existing-checkbox",
                )
                yield Label("Skip caching if images exist", classes="param-hint")

            # Delete Cache After Training
            with Horizontal(classes="param-row", id="centroid-delete-cache-row"):
                yield Label("Delete After:", classes="param-label")
                yield Checkbox(
                    "Delete cache after training",
                    value=cache.delete_cache_after_training if cache else True,
                    id="centroid-delete-cache-checkbox",
                )
                yield Label("Clean up disk space", classes="param-hint")

        # Additional Data Parameters (collapsible)
        with Collapsible(
            title="Additional Data Parameters", classes="collapsible-section"
        ):
            # Validation Fraction
            with Horizontal(classes="param-row"):
                yield Label("Val Fraction:", classes="param-label")
                yield Input(
                    value=str(self._state._validation_fraction if self._state else 0.1),
                    id="centroid-val-fraction-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Fraction held out for validation (0.05-0.3)", classes="param-hint"
                )

            # Input Channels
            current_channels = "grayscale"
            if self._state:
                if self._state._ensure_rgb:
                    current_channels = "rgb"
                elif self._state._ensure_grayscale:
                    current_channels = "grayscale"

            with Horizontal(classes="param-row"):
                yield Label("Input Channels:", classes="param-label")
                yield Select(
                    [
                        ("Grayscale (1 channel)", "grayscale"),
                        ("RGB (3 channels)", "rgb"),
                    ],
                    value=current_channels,
                    id="centroid-channels-select",
                    classes="param-input",
                )
                yield Label("Image color mode", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Max Height:", classes="param-label")
                yield Input(
                    value=(
                        str(self._state._max_height)
                        if self._state and self._state._max_height
                        else ""
                    ),
                    id="centroid-max-height-input",
                    classes="param-input",
                    type="integer",
                    placeholder="auto",
                )
                yield Label("Max Width:", classes="param-label")
                yield Input(
                    value=(
                        str(self._state._max_width)
                        if self._state and self._state._max_width
                        else ""
                    ),
                    id="centroid-max-width-input",
                    classes="param-input",
                    type="integer",
                    placeholder="auto",
                )

        # Model configuration
        with Container(classes="section-box"):
            yield Static("[bold]Model Architecture[/bold]", classes="section-header")
            yield Static("[dim]Detects animal centers in full frame[/dim]")

            # Model info display
            yield Static(id="centroid-model-info-display", classes="shape-info")

            # Backbone for centroid
            with Horizontal(classes="param-row"):
                yield Label("Backbone:", classes="param-label")
                yield Select(
                    [
                        ("UNet (recommended)", "unet_medium_rf"),
                        ("UNet Large RF", "unet_large_rf"),
                        ("ConvNeXt Tiny", "convnext_tiny"),
                        ("ConvNeXt Small", "convnext_small"),
                        ("SwinT Tiny", "swint_tiny"),
                    ],
                    value=self._state._backbone if self._state else "unet_medium_rf",
                    id="centroid-backbone-select",
                    classes="param-input",
                )
                yield Label("Network architecture", classes="param-hint")

            # Max stride
            with Horizontal(classes="param-row"):
                yield Label("Max Stride:", classes="param-label")
                yield Select(
                    [("8", "8"), ("16", "16"), ("32", "32"), ("64", "64")],
                    value=str(self._state._max_stride if self._state else 16),
                    id="centroid-max-stride-select",
                    classes="param-input",
                )
                yield Label(
                    "Receptive field (larger = more context)", classes="param-hint"
                )

            # Base Filters
            with Horizontal(classes="param-row"):
                yield Label("Base Filters:", classes="param-label")
                yield Input(
                    value=str(self._state._filters if self._state else 32),
                    id="centroid-filters-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("First encoder block filters", classes="param-hint")

            # Filters Rate
            with Horizontal(classes="param-row"):
                yield Label("Filters Rate:", classes="param-label")
                yield Input(
                    value=str(self._state._filters_rate if self._state else 1.5),
                    id="centroid-filters-rate-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Multiplier per block (1.5 typical)", classes="param-hint")

            # Sigma for centroid
            with Horizontal(classes="param-row"):
                yield Label("Sigma:", classes="param-label")
                yield Input(
                    value=str(self._state._sigma if self._state else 5.0),
                    id="centroid-sigma-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Centroid confidence map spread", classes="param-hint")

            # Output stride
            with Horizontal(classes="param-row"):
                yield Label("Output Stride:", classes="param-label")
                yield Select(
                    [
                        ("1 (full res)", "1"),
                        ("2 (half res)", "2"),
                        ("4 (quarter)", "4"),
                        ("8 (1/8 res)", "8"),
                        ("16 (1/16 res)", "16"),
                    ],
                    value=str(self._state._output_stride if self._state else 2),
                    id="centroid-output-stride-select",
                    classes="param-input",
                )
                yield Label("Higher = faster but less precise", classes="param-hint")

            # ImageNet Pretrained (for ConvNeXt/SwinT)
            with Horizontal(classes="param-row", id="centroid-imagenet-row"):
                yield Label("ImageNet Weights:", classes="param-label")
                yield Checkbox(
                    "Use ImageNet pretrained",
                    value=self._state._use_imagenet_pretrained if self._state else True,
                    id="centroid-imagenet-checkbox",
                )
                yield Label("For ConvNeXt/SwinT backbones", classes="param-hint")

            # Pretrained Backbone Path
            with Horizontal(classes="param-row"):
                yield Label("Pretrained Backbone:", classes="param-label")
                yield Input(
                    value=self._state._pretrained_backbone if self._state else "",
                    id="centroid-pretrained-backbone-input",
                    classes="param-input-wide",
                    placeholder="Path to .ckpt (optional)",
                )

            # Pretrained Head Path
            with Horizontal(classes="param-row"):
                yield Label("Pretrained Head:", classes="param-label")
                yield Input(
                    value=self._state._pretrained_head if self._state else "",
                    id="centroid-pretrained-head-input",
                    classes="param-input-wide",
                    placeholder="Path to .ckpt (optional)",
                )

        # Training configuration
        with Container(classes="section-box"):
            yield Static("[bold]Training[/bold]", classes="section-header")

            # Batch size
            with Horizontal(classes="param-row"):
                yield Label("Batch Size:", classes="param-label")
                yield Select(
                    [("1", "1"), ("2", "2"), ("4", "4"), ("8", "8"), ("16", "16")],
                    value=str(self._state._batch_size if self._state else 4),
                    id="centroid-batch-size-select",
                    classes="param-input",
                )
                yield Label("Samples per batch", classes="param-hint")

            # Max epochs
            with Horizontal(classes="param-row"):
                yield Label("Max Epochs:", classes="param-label")
                yield Input(
                    value=str(self._state._max_epochs if self._state else 200),
                    id="centroid-max-epochs-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Maximum training epochs", classes="param-hint")

            # Learning rate
            with Horizontal(classes="param-row"):
                yield Label("Learning Rate:", classes="param-label")
                yield Input(
                    value=str(self._state._learning_rate if self._state else 1e-4),
                    id="centroid-lr-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Initial optimizer step size (1e-4 is good default)",
                    classes="param-hint",
                )

        # Checkpoint & Logging
        with Collapsible(title="Checkpoints & Logging", classes="collapsible-section"):
            ckpt = self._state._checkpoint if self._state else None

            # Save Checkpoints toggle
            with Horizontal(classes="param-row"):
                yield Label("Save Checkpoints:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=ckpt.enabled if ckpt else True,
                    id="centroid-save-ckpt-checkbox",
                )

            with Horizontal(classes="param-row"):
                yield Label("Checkpoint Dir:", classes="param-label")
                yield Input(
                    value=ckpt.checkpoint_dir if ckpt else "",
                    id="centroid-ckpt-dir-input",
                    classes="param-input-wide",
                    placeholder="./models",
                )

            with Horizontal(classes="param-row"):
                yield Label("Run Name:", classes="param-label")
                yield Input(
                    value=ckpt.run_name if ckpt else "",
                    id="centroid-run-name-input",
                    classes="param-input-wide",
                    placeholder="centroid_model",
                )

            # Save Top K
            with Horizontal(classes="param-row"):
                yield Label("Save Top K:", classes="param-label")
                yield Input(
                    value=str(ckpt.save_top_k if ckpt else 1),
                    id="centroid-save-top-k-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Best checkpoints to keep", classes="param-hint")

            # Resume from checkpoint
            with Horizontal(classes="param-row"):
                yield Label("Resume From:", classes="param-label")
                yield Input(
                    value=ckpt.resume_from if ckpt else "",
                    id="centroid-resume-ckpt-input",
                    classes="param-input-wide",
                    placeholder="Path to checkpoint.ckpt",
                )

            yield Static("[dim]Weights & Biases[/dim]", classes="subsection-header")

            # WandB Enable
            wandb = self._state._wandb if self._state else None
            with Horizontal(classes="param-row"):
                yield Label("Enable WandB:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=wandb.enabled if wandb else False,
                    id="centroid-wandb-checkbox",
                )
                yield Label("Log to Weights & Biases", classes="param-hint")

            # WandB Project (hidden until WandB enabled)
            with Horizontal(
                classes="param-row hidden", id="centroid-wandb-project-row"
            ):
                yield Label("WandB Project:", classes="param-label")
                yield Input(
                    value=wandb.project if wandb else "sleap-training",
                    id="centroid-wandb-project-input",
                    classes="param-input-wide",
                )

            # WandB Entity (hidden until WandB enabled)
            with Horizontal(classes="param-row hidden", id="centroid-wandb-entity-row"):
                yield Label("WandB Entity:", classes="param-label")
                yield Input(
                    value=wandb.entity if wandb else "",
                    id="centroid-wandb-entity-input",
                    classes="param-input-wide",
                    placeholder="username or team",
                )

            # WandB Run Name (hidden until WandB enabled)
            with Horizontal(classes="param-row hidden", id="centroid-wandb-name-row"):
                yield Label("WandB Name:", classes="param-label")
                yield Input(
                    value=wandb.name if wandb else "",
                    id="centroid-wandb-name-input",
                    classes="param-input-wide",
                    placeholder="auto-generated",
                )

            # WandB API Key (hidden until WandB enabled)
            with Horizontal(
                classes="param-row hidden", id="centroid-wandb-api-key-row"
            ):
                yield Label("WandB API Key:", classes="param-label")
                yield Input(
                    value=wandb.api_key if wandb else "",
                    id="centroid-wandb-api-key-input",
                    classes="param-input-wide",
                    placeholder="(uses env var if empty)",
                    password=True,
                )

            # WandB Mode (hidden until WandB enabled)
            with Horizontal(classes="param-row hidden", id="centroid-wandb-mode-row"):
                yield Label("WandB Mode:", classes="param-label")
                yield Select(
                    [
                        ("Online", "online"),
                        ("Offline", "offline"),
                        ("Disabled", "disabled"),
                    ],
                    value=wandb.mode if wandb else "online",
                    id="centroid-wandb-mode-select",
                    classes="param-input",
                )
                yield Label("Logging mode", classes="param-hint")

            # WandB Visualization options (hidden until WandB enabled)
            with Horizontal(classes="param-row hidden", id="centroid-wandb-viz-row"):
                yield Label("Log Visualizations:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=wandb.viz_enabled if wandb else True,
                    id="centroid-wandb-viz-checkbox",
                )
                yield Label(
                    "Log prediction visualizations to WandB", classes="param-hint"
                )

            with Horizontal(
                classes="param-row hidden", id="centroid-wandb-save-viz-row"
            ):
                yield Label("Upload Local Viz:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=wandb.save_viz_imgs if wandb else False,
                    id="centroid-wandb-save-viz-checkbox",
                )
                yield Label("Upload local visualization images", classes="param-hint")

            yield Static("[dim]Save Visualizations[/dim]", classes="subsection-header")

            # Save Visualizations toggle (matches webapp enable-viz)
            with Horizontal(classes="param-row"):
                yield Label("Save Visualizations:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=self._state._visualize_preds if self._state else False,
                    id="centroid-save-viz-checkbox",
                )
                yield Label(
                    "Save prediction visualizations locally", classes="param-hint"
                )

            # Keep Viz Folder (hidden until Save Viz enabled)
            with Horizontal(
                classes="param-row hidden", id="centroid-viz-keep-folder-row"
            ):
                yield Label("Keep Viz Folder:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=self._state._keep_viz if self._state else False,
                    id="centroid-viz-keep-folder-checkbox",
                )
                yield Label(
                    "Keep visualization folder after training", classes="param-hint"
                )

            yield Static("[dim]Evaluation[/dim]", classes="subsection-header")

            # Enable Evaluation toggle
            evaluation = self._state._evaluation if self._state else None
            with Horizontal(classes="param-row"):
                yield Label("Enable Evaluation:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=evaluation.enabled if evaluation else False,
                    id="centroid-eval-checkbox",
                )
                yield Label("Run OKS evaluation during training", classes="param-hint")

            # Eval options (hidden until Enable Eval is checked)
            with Horizontal(
                classes="param-row hidden", id="centroid-eval-frequency-row"
            ):
                yield Label("Eval Frequency:", classes="param-label")
                yield Input(
                    value=str(evaluation.frequency if evaluation else 1),
                    id="centroid-eval-frequency-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Run eval every N epochs", classes="param-hint")

            with Horizontal(classes="param-row hidden", id="centroid-eval-oks-row"):
                yield Label("OKS Stddev:", classes="param-label")
                yield Input(
                    value=str(evaluation.oks_stddev if evaluation else 0.025),
                    id="centroid-eval-oks-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Standard deviation for OKS scoring", classes="param-hint")

        # Advanced Parameters (collapsible)
        with Collapsible(title="Advanced Parameters", classes="collapsible-section"):
            # Optimizer
            with Horizontal(classes="param-row"):
                yield Label("Optimizer:", classes="param-label")
                yield Select(
                    [("Adam", "Adam"), ("AdamW", "AdamW")],
                    value=self._state._optimizer if self._state else "Adam",
                    id="centroid-optimizer-select",
                    classes="param-input",
                )
                yield Label("Adam is recommended for most cases", classes="param-hint")

            # Early stopping
            with Horizontal(classes="param-row"):
                yield Label("Early Stopping:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=self._state._early_stopping if self._state else True,
                    id="centroid-early-stopping-checkbox",
                )
                yield Label(
                    "Stop when validation loss stops improving", classes="param-hint"
                )

            # ES Patience
            with Horizontal(classes="param-row"):
                yield Label("ES Patience:", classes="param-label")
                yield Input(
                    value=str(
                        self._state._early_stopping_patience if self._state else 10
                    ),
                    id="centroid-es-patience-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs to wait before stopping", classes="param-hint")

            # ES Min Delta
            with Horizontal(classes="param-row"):
                yield Label("ES Min Delta:", classes="param-label")
                yield Input(
                    value=str(
                        self._state._early_stopping_min_delta if self._state else 1e-6
                    ),
                    id="centroid-es-min-delta-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Minimum change to qualify as improvement", classes="param-hint"
                )

            yield Static(
                "[dim]Learning Rate Scheduler[/dim]", classes="subsection-header"
            )

            # LR Scheduler
            scheduler = self._state._scheduler if self._state else None
            with Horizontal(classes="param-row"):
                yield Label("Scheduler:", classes="param-label")
                yield Select(
                    [
                        ("ReduceLROnPlateau", "ReduceLROnPlateau"),
                        ("Cosine Annealing + Warmup", "CosineAnnealingWarmup"),
                        ("Step LR", "StepLR"),
                        ("None", "none"),
                    ],
                    value=scheduler.type.value if scheduler else "ReduceLROnPlateau",
                    id="centroid-scheduler-select",
                    classes="param-input",
                )
                yield Label("Reduces LR when loss plateaus", classes="param-hint")

            # Scheduler-specific params (ReduceLROnPlateau)
            with Horizontal(classes="param-row"):
                yield Label("LR Patience:", classes="param-label")
                yield Input(
                    value=str(scheduler.plateau_patience if scheduler else 5),
                    id="centroid-lr-patience-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs to wait before reducing LR", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("LR Factor:", classes="param-label")
                yield Input(
                    value=str(scheduler.factor if scheduler else 0.5),
                    id="centroid-lr-factor-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Factor to reduce LR by (0.5 = halve)", classes="param-hint"
                )

            yield Static("[dim]Hardware[/dim]", classes="subsection-header")

            # Accelerator
            with Horizontal(classes="param-row"):
                yield Label("Accelerator:", classes="param-label")
                yield Select(
                    [
                        ("Auto", "auto"),
                        ("CPU", "cpu"),
                        ("GPU (CUDA)", "gpu"),
                        ("MPS (Apple)", "mps"),
                    ],
                    value=self._state._accelerator if self._state else "auto",
                    id="centroid-accelerator-select",
                    classes="param-input",
                )
                yield Label("Hardware for training", classes="param-hint")

            # Devices
            with Horizontal(classes="param-row"):
                yield Label("Devices:", classes="param-label")
                yield Select(
                    [("Auto", "auto"), ("1", "1"), ("2", "2"), ("4", "4")],
                    value=self._state._devices if self._state else "auto",
                    id="centroid-devices-select",
                    classes="param-input",
                )
                yield Label("Number of GPUs", classes="param-hint")

            # Min Steps per Epoch
            with Horizontal(classes="param-row"):
                yield Label("Min Steps/Epoch:", classes="param-label")
                yield Input(
                    value=str(self._state._min_steps_per_epoch if self._state else 200),
                    id="centroid-min-steps-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Minimum training steps per epoch", classes="param-hint")

            # Random Seed
            with Horizontal(classes="param-row"):
                yield Label("Random Seed:", classes="param-label")
                yield Input(
                    value=(
                        str(self._state._random_seed)
                        if self._state and self._state._random_seed
                        else ""
                    ),
                    id="centroid-random-seed-input",
                    classes="param-input",
                    type="integer",
                    placeholder="none",
                )
                yield Label("For reproducibility", classes="param-hint")

        # Centroid memory estimate
        yield Static(id="centroid-memory-display", classes="memory-info")

    def _compose_instance_params(self) -> ComposeResult:
        """Compose centered instance model specific parameters."""
        # Data configuration - main params
        with Container(classes="section-box"):
            yield Static("[bold]Data Configuration[/bold]", classes="section-header")

            # Crop size (main param for instance model)
            crop_size = self._state._crop_size if self._state else None
            if crop_size is None and self._state:
                crop_size = self._state._compute_auto_crop_size()

            with Horizontal(classes="param-row"):
                yield Label("Crop Size:", classes="param-label")
                yield Input(
                    value=str(crop_size or 256),
                    id="crop-size-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Square crop around each instance", classes="param-hint")

            # Instance scale
            with Horizontal(classes="param-row"):
                yield Label("Input Scale:", classes="param-label")
                yield Input(
                    value=str(self._state._ci_input_scale if self._state else 1.0),
                    id="instance-scale-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Crop resize factor (1.0 = no resize)", classes="param-hint"
                )

        # Data Augmentation section
        with Container(classes="section-box"):
            yield Static("[bold]Data Augmentation[/bold]", classes="section-header")
            aug = self._state._ci_augmentation if self._state else None

            yield Static("[dim]Geometric[/dim]", classes="subsection-header")

            # Rotation
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Rotation",
                    value=aug.rotation_enabled if aug else True,
                    id="instance-rotation-checkbox",
                )
                yield Label("±", classes="param-label")
                yield Input(
                    value=str(aug.rotation_max if aug else 15.0),
                    id="instance-rotation-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("degrees", classes="param-hint")

            # Scale
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Scale",
                    value=aug.scale_enabled if aug else True,
                    id="instance-scale-checkbox",
                )
                yield Input(
                    value=str(aug.scale_min if aug else 0.9),
                    id="instance-scale-min-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("to", classes="param-hint")
                yield Input(
                    value=str(aug.scale_max if aug else 1.1),
                    id="instance-scale-max-input",
                    classes="param-input",
                    type="number",
                )

            yield Static("[dim]Intensity[/dim]", classes="subsection-header")

            # Brightness
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Brightness",
                    value=aug.brightness_enabled if aug else False,
                    id="instance-brightness-checkbox",
                )
                yield Label("±", classes="param-label")
                yield Input(
                    value=str(aug.brightness_limit if aug else 0.2),
                    id="instance-brightness-input",
                    classes="param-input",
                    type="number",
                )

            # Contrast
            with Horizontal(classes="param-row"):
                yield Checkbox(
                    "Contrast",
                    value=aug.contrast_enabled if aug else False,
                    id="instance-contrast-checkbox",
                )
                yield Label("±", classes="param-label")
                yield Input(
                    value=str(aug.contrast_limit if aug else 0.2),
                    id="instance-contrast-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("0=off, 0.2=±20%", classes="param-hint")

        # Data Pipeline section (visible - matches webapp layout)
        with Container(classes="section-box"):
            yield Static("[bold]Data Pipeline[/bold]", classes="section-header")

            # Speed tip info box
            yield Static(
                "[green bold]💡 Speed Tip:[/green bold] Set [bold]Num Workers[/bold] to 2+ and "
                "use [bold]Cache to Memory[/bold] or [bold]Cache to Disk[/bold] for faster training.",
                classes="info-box speed-tip",
            )

            # Num Workers
            with Horizontal(classes="param-row"):
                yield Label("Num Workers:", classes="param-label")
                yield Select(
                    [
                        ("0", "0"),
                        ("2 (Default)", "2"),
                        ("4", "4"),
                        ("8", "8"),
                    ],
                    value=str(self._state._num_workers if self._state else 2),
                    id="instance-num-workers-select",
                    classes="param-input",
                )
                yield Label("Data loader workers (0 for video)", classes="param-hint")

            # Data Pipeline
            current_pipeline = (
                self._state._data_pipeline.value if self._state else "litdata"
            )
            with Horizontal(classes="param-row"):
                yield Label("Data Pipeline:", classes="param-label")
                yield Select(
                    [
                        ("Video", "torch_dataset"),
                        ("Cache to Memory (default)", "litdata"),
                        ("Cache to Disk", "litdata_disk"),
                    ],
                    value=current_pipeline,
                    id="instance-data-pipeline-select",
                    classes="param-input",
                )
                yield Label("Data loading method", classes="param-hint")

            # Cache Memory Estimate
            yield Static(id="instance-cache-memory-display", classes="memory-info")

            # Cache config options
            cache = self._state._cache_config if self._state else None

            # Parallel Caching
            with Horizontal(classes="param-row", id="instance-parallel-caching-row"):
                yield Label("Parallel Caching:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=cache.parallel_caching if cache else True,
                    id="instance-parallel-caching-checkbox",
                )
                yield Label("Cache images in parallel", classes="param-hint")

            # Cache Workers
            with Horizontal(classes="param-row", id="instance-cache-workers-row"):
                yield Label("Cache Workers:", classes="param-label")
                yield Input(
                    value=str(cache.cache_workers if cache else 0),
                    id="instance-cache-workers-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label(
                    "Workers for caching (0 = main process)", classes="param-hint"
                )

            # Disk cache options
            yield Static(
                "[dim]Disk Cache Options[/dim]",
                classes="subsection-header",
                id="instance-disk-cache-header",
            )

            with Horizontal(classes="param-row", id="instance-cache-path-row"):
                yield Label("Cache Path:", classes="param-label")
                yield Input(
                    value=cache.cache_img_path if cache else "",
                    id="instance-cache-path-input",
                    classes="param-input-wide",
                    placeholder="./cache (auto if empty)",
                )

            with Horizontal(classes="param-row", id="instance-use-existing-row"):
                yield Label("Use Existing:", classes="param-label")
                yield Checkbox(
                    "Reuse cached images",
                    value=cache.use_existing_imgs if cache else False,
                    id="instance-use-existing-checkbox",
                )
                yield Label("Skip caching if images exist", classes="param-hint")

            with Horizontal(classes="param-row", id="instance-delete-cache-row"):
                yield Label("Delete After:", classes="param-label")
                yield Checkbox(
                    "Delete cache after training",
                    value=cache.delete_cache_after_training if cache else True,
                    id="instance-delete-cache-checkbox",
                )
                yield Label("Clean up disk space", classes="param-hint")

        # Additional Data Parameters (collapsible)
        with Collapsible(
            title="Additional Data Parameters", classes="collapsible-section"
        ):
            # Input Channels
            current_channels = "grayscale"
            if self._state:
                if self._state._ensure_rgb:
                    current_channels = "rgb"
                elif self._state._ensure_grayscale:
                    current_channels = "grayscale"

            with Horizontal(classes="param-row"):
                yield Label("Input Channels:", classes="param-label")
                yield Select(
                    [
                        ("Grayscale (1 channel)", "grayscale"),
                        ("RGB (3 channels)", "rgb"),
                    ],
                    value=current_channels,
                    id="instance-channels-select",
                    classes="param-input",
                )
                yield Label("Image color mode", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Min Crop Size:", classes="param-label")
                yield Input(
                    value=str(self._state._ci_min_crop_size if self._state else 100),
                    id="min-crop-size-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Minimum allowed crop size", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Crop Padding:", classes="param-label")
                yield Input(
                    value=(
                        str(self._state._ci_crop_padding)
                        if self._state and self._state._ci_crop_padding is not None
                        else ""
                    ),
                    id="crop-padding-input",
                    classes="param-input",
                    type="integer",
                    placeholder="auto",
                )
                yield Label(
                    "Extra padding around crops (empty = auto)", classes="param-hint"
                )

        # Model configuration
        with Container(classes="section-box"):
            yield Static("[bold]Model Architecture[/bold]", classes="section-header")
            yield Static("[dim]Detects keypoints within cropped regions[/dim]")

            # Instance backbone
            with Horizontal(classes="param-row"):
                yield Label("Backbone:", classes="param-label")
                yield Select(
                    [
                        ("UNet (recommended)", "unet_medium_rf"),
                        ("UNet Large RF", "unet_large_rf"),
                        ("ConvNeXt Tiny", "convnext_tiny"),
                        ("ConvNeXt Small", "convnext_small"),
                    ],
                    value=self._state._ci_backbone if self._state else "unet_medium_rf",
                    id="instance-backbone-select",
                    classes="param-input",
                )
                yield Label("Network architecture", classes="param-hint")

            # Max stride
            with Horizontal(classes="param-row"):
                yield Label("Max Stride:", classes="param-label")
                yield Select(
                    [("8", "8"), ("16", "16"), ("32", "32")],
                    value=str(self._state._ci_max_stride if self._state else 16),
                    id="instance-max-stride-select",
                    classes="param-input",
                )
                yield Label("Receptive field", classes="param-hint")

            # Instance sigma
            with Horizontal(classes="param-row"):
                yield Label("Sigma:", classes="param-label")
                yield Input(
                    value=str(self._state._ci_sigma if self._state else 2.5),
                    id="instance-sigma-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Tighter sigma for crops (2.5 typical)", classes="param-hint"
                )

            # Instance output stride
            with Horizontal(classes="param-row"):
                yield Label("Output Stride:", classes="param-label")
                yield Select(
                    [
                        ("1 (full res)", "1"),
                        ("2 (half res)", "2"),
                        ("4 (quarter)", "4"),
                        ("8 (1/8 res)", "8"),
                        ("16 (1/16 res)", "16"),
                    ],
                    value=str(self._state._ci_output_stride if self._state else 2),
                    id="instance-output-stride-select",
                    classes="param-input",
                )
                yield Label("Higher = faster but less precise", classes="param-hint")

            # Base Filters
            with Horizontal(classes="param-row"):
                yield Label("Base Filters:", classes="param-label")
                yield Input(
                    value=str(self._state._ci_filters if self._state else 32),
                    id="instance-filters-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label(
                    "First encoder block filters (32 typical)", classes="param-hint"
                )

            # Filters Rate
            with Horizontal(classes="param-row"):
                yield Label("Filters Rate:", classes="param-label")
                yield Input(
                    value=str(self._state._ci_filters_rate if self._state else 1.5),
                    id="instance-filters-rate-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Multiplier per block (1.5 typical)", classes="param-hint")

            # ImageNet Pretrained (for ConvNeXt/SwinT)
            with Horizontal(classes="param-row", id="instance-imagenet-row"):
                yield Label("ImageNet Weights:", classes="param-label")
                yield Checkbox(
                    "Use ImageNet pretrained",
                    value=self._state._use_imagenet_pretrained if self._state else True,
                    id="instance-imagenet-checkbox",
                )
                yield Label("For ConvNeXt/SwinT backbones", classes="param-hint")

            # Pretrained Backbone Path
            with Horizontal(classes="param-row"):
                yield Label("Pretrained Backbone:", classes="param-label")
                yield Input(
                    value=self._state._ci_pretrained_backbone if self._state else "",
                    id="instance-pretrained-backbone-input",
                    classes="param-input-wide",
                    placeholder="Path to .ckpt (optional)",
                )

            # Pretrained Head Path
            with Horizontal(classes="param-row"):
                yield Label("Pretrained Head:", classes="param-label")
                yield Input(
                    value=self._state._ci_pretrained_head if self._state else "",
                    id="instance-pretrained-head-input",
                    classes="param-input-wide",
                    placeholder="Path to .ckpt (optional)",
                )

            # Model Info Display
            yield Static(id="instance-model-info-display", classes="model-info")

        # Training configuration
        with Container(classes="section-box"):
            yield Static("[bold]Training[/bold]", classes="section-header")

            # Batch size
            with Horizontal(classes="param-row"):
                yield Label("Batch Size:", classes="param-label")
                yield Select(
                    [("1", "1"), ("2", "2"), ("4", "4"), ("8", "8"), ("16", "16")],
                    value=str(self._state._ci_batch_size if self._state else 4),
                    id="instance-batch-size-select",
                    classes="param-input",
                )
                yield Label(
                    "Crops per batch (more = faster, more memory)", classes="param-hint"
                )

            # Max epochs
            with Horizontal(classes="param-row"):
                yield Label("Max Epochs:", classes="param-label")
                yield Input(
                    value=str(self._state._ci_max_epochs if self._state else 200),
                    id="instance-max-epochs-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label(
                    "Training stops after this many epochs", classes="param-hint"
                )

            # Learning rate
            with Horizontal(classes="param-row"):
                yield Label("Learning Rate:", classes="param-label")
                yield Select(
                    [
                        ("1e-4 (Default)", "0.0001"),
                        ("5e-4", "0.0005"),
                        ("1e-3", "0.001"),
                        ("5e-5", "0.00005"),
                    ],
                    value=str(
                        self._state._ci_learning_rate if self._state else "0.0001"
                    ),
                    id="instance-lr-select",
                    classes="param-input",
                )
                yield Label("Initial optimizer step size", classes="param-hint")

        # Checkpoint & Logging section
        with Collapsible(title="Checkpoints & Logging", classes="collapsible-section"):
            ckpt = self._state._checkpoint if self._state else None

            yield Static("[dim]Checkpoints[/dim]", classes="subsection-header")

            # Save Checkpoint
            with Horizontal(classes="param-row"):
                yield Label("Save Checkpoints:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=ckpt.enabled if ckpt else True,
                    id="instance-save-ckpt-checkbox",
                )
                yield Label(
                    "Save model checkpoints during training", classes="param-hint"
                )

            with Horizontal(classes="param-row"):
                yield Label("Checkpoint Dir:", classes="param-label")
                yield Input(
                    value=ckpt.checkpoint_dir if ckpt else "",
                    id="instance-ckpt-dir-input",
                    classes="param-input-wide",
                    placeholder="./models",
                )

            with Horizontal(classes="param-row"):
                yield Label("Run Name:", classes="param-label")
                yield Input(
                    value=ckpt.run_name if ckpt else "",
                    id="instance-run-name-input",
                    classes="param-input-wide",
                    placeholder="centered_instance_model",
                )

            with Horizontal(classes="param-row"):
                yield Label("Save Top K:", classes="param-label")
                yield Input(
                    value=str(ckpt.save_top_k if ckpt else 1),
                    id="instance-save-top-k-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Number of best checkpoints to keep", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("Save Last:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=ckpt.save_last if ckpt else False,
                    id="instance-save-last-checkbox",
                )
                yield Label("Keep last.ckpt symlink", classes="param-hint")

            yield Static("[dim]Weights & Biases[/dim]", classes="subsection-header")

            # WandB Enable
            wandb = self._state._wandb if self._state else None
            with Horizontal(classes="param-row"):
                yield Label("Enable WandB:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=wandb.enabled if wandb else False,
                    id="instance-wandb-checkbox",
                )
                yield Label("Log to Weights & Biases", classes="param-hint")

            # WandB Project (hidden until WandB enabled)
            with Horizontal(
                classes="param-row hidden", id="instance-wandb-project-row"
            ):
                yield Label("WandB Project:", classes="param-label")
                yield Input(
                    value=wandb.project if wandb else "sleap-training",
                    id="instance-wandb-project-input",
                    classes="param-input-wide",
                )

            # WandB Entity (hidden until WandB enabled)
            with Horizontal(classes="param-row hidden", id="instance-wandb-entity-row"):
                yield Label("WandB Entity:", classes="param-label")
                yield Input(
                    value=wandb.entity if wandb else "",
                    id="instance-wandb-entity-input",
                    classes="param-input-wide",
                    placeholder="username or team",
                )

            yield Static("[dim]Save Visualizations[/dim]", classes="subsection-header")

            # Save Visualizations toggle
            with Horizontal(classes="param-row"):
                yield Label("Save Visualizations:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=self._state._visualize_preds if self._state else False,
                    id="instance-save-viz-checkbox",
                )
                yield Label(
                    "Save prediction visualizations locally", classes="param-hint"
                )

            # Keep Viz Folder (hidden until Save Viz enabled)
            with Horizontal(
                classes="param-row hidden", id="instance-viz-keep-folder-row"
            ):
                yield Label("Keep Viz Folder:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=self._state._keep_viz if self._state else False,
                    id="instance-viz-keep-folder-checkbox",
                )
                yield Label(
                    "Keep visualization folder after training", classes="param-hint"
                )

            yield Static("[dim]Evaluation[/dim]", classes="subsection-header")

            # Enable Evaluation toggle
            evaluation = self._state._evaluation if self._state else None
            with Horizontal(classes="param-row"):
                yield Label("Enable Evaluation:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=evaluation.enabled if evaluation else False,
                    id="instance-eval-checkbox",
                )
                yield Label("Run OKS evaluation during training", classes="param-hint")

            # Eval options (hidden until Enable Eval is checked)
            with Horizontal(
                classes="param-row hidden", id="instance-eval-frequency-row"
            ):
                yield Label("Eval Frequency:", classes="param-label")
                yield Input(
                    value=str(evaluation.frequency if evaluation else 1),
                    id="instance-eval-frequency-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Run eval every N epochs", classes="param-hint")

            with Horizontal(classes="param-row hidden", id="instance-eval-oks-row"):
                yield Label("OKS Stddev:", classes="param-label")
                yield Input(
                    value=str(evaluation.oks_stddev if evaluation else 0.025),
                    id="instance-eval-oks-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Standard deviation for OKS scoring", classes="param-hint")

        # Advanced Parameters (collapsible)
        with Collapsible(title="Advanced Parameters", classes="collapsible-section"):
            # Optimizer
            with Horizontal(classes="param-row"):
                yield Label("Optimizer:", classes="param-label")
                yield Select(
                    [("Adam", "Adam"), ("AdamW", "AdamW")],
                    value=self._state._ci_optimizer if self._state else "Adam",
                    id="instance-optimizer-select",
                    classes="param-input",
                )
                yield Label("Adam is recommended for most cases", classes="param-hint")

            # Early stopping
            with Horizontal(classes="param-row"):
                yield Label("Early Stopping:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=self._state._ci_early_stopping if self._state else True,
                    id="instance-early-stopping-checkbox",
                )
                yield Label(
                    "Stop when validation loss stops improving", classes="param-hint"
                )

            # ES Patience
            with Horizontal(classes="param-row"):
                yield Label("ES Patience:", classes="param-label")
                yield Input(
                    value=str(
                        self._state._ci_early_stopping_patience if self._state else 5
                    ),
                    id="instance-es-patience-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs to wait before stopping", classes="param-hint")

            # ES Min Delta
            with Horizontal(classes="param-row"):
                yield Label("ES Min Delta:", classes="param-label")
                yield Input(
                    value=str(
                        self._state._ci_early_stopping_min_delta
                        if self._state
                        else 1e-6
                    ),
                    id="instance-es-min-delta-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Minimum change to qualify as improvement", classes="param-hint"
                )

            yield Static(
                "[dim]Learning Rate Scheduler[/dim]", classes="subsection-header"
            )

            # LR Scheduler
            scheduler = self._state._ci_scheduler if self._state else None
            with Horizontal(classes="param-row"):
                yield Label("Scheduler:", classes="param-label")
                yield Select(
                    [
                        ("ReduceLROnPlateau", "ReduceLROnPlateau"),
                        ("Cosine Annealing + Warmup", "CosineAnnealingWarmup"),
                        ("Step LR", "StepLR"),
                        ("None", "none"),
                    ],
                    value=scheduler.type.value if scheduler else "ReduceLROnPlateau",
                    id="instance-scheduler-select",
                    classes="param-input",
                )
                yield Label("Reduces LR when loss plateaus", classes="param-hint")

            # Scheduler-specific params (ReduceLROnPlateau)
            with Horizontal(classes="param-row"):
                yield Label("LR Patience:", classes="param-label")
                yield Input(
                    value=str(scheduler.plateau_patience if scheduler else 5),
                    id="instance-lr-patience-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Epochs to wait before reducing LR", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("LR Factor:", classes="param-label")
                yield Input(
                    value=str(scheduler.factor if scheduler else 0.5),
                    id="instance-lr-factor-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Factor to reduce LR by (0.5 = halve)", classes="param-hint"
                )

            yield Static(
                "[dim]Online Hard Keypoint Mining (OHKM)[/dim]",
                classes="subsection-header",
            )

            ohkm = self._state._ohkm if self._state else None
            with Horizontal(classes="param-row"):
                yield Label("Enable OHKM:", classes="param-label")
                yield Checkbox(
                    "Enabled",
                    value=ohkm.enabled if ohkm else False,
                    id="instance-ohkm-checkbox",
                )
                yield Label(
                    "Focus training on difficult keypoints", classes="param-hint"
                )

            with Horizontal(classes="param-row"):
                yield Label("Hard-to-Easy Ratio:", classes="param-label")
                yield Input(
                    value=str(ohkm.hard_to_easy_ratio if ohkm else 2.0),
                    id="instance-ohkm-ratio-input",
                    classes="param-input",
                    type="number",
                )
                yield Label("Ratio to classify keypoints as hard", classes="param-hint")

            with Horizontal(classes="param-row"):
                yield Label("OHKM Loss Scale:", classes="param-label")
                yield Input(
                    value=str(ohkm.loss_scale if ohkm else 5.0),
                    id="instance-ohkm-scale-input",
                    classes="param-input",
                    type="number",
                )
                yield Label(
                    "Scale factor for hard keypoint losses", classes="param-hint"
                )

            with Horizontal(classes="param-row"):
                yield Label("Min Hard Keypoints:", classes="param-label")
                yield Input(
                    value=str(ohkm.min_hard_keypoints if ohkm else 2),
                    id="instance-ohkm-min-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label(
                    "Minimum keypoints to classify as hard", classes="param-hint"
                )

            with Horizontal(classes="param-row"):
                yield Label("Max Hard Keypoints:", classes="param-label")
                yield Input(
                    value=(
                        str(ohkm.max_hard_keypoints)
                        if ohkm and ohkm.max_hard_keypoints
                        else ""
                    ),
                    id="instance-ohkm-max-input",
                    classes="param-input",
                    type="integer",
                    placeholder="none",
                )
                yield Label("Maximum (empty = unlimited)", classes="param-hint")

            yield Static("[dim]Hardware[/dim]", classes="subsection-header")

            # Accelerator
            with Horizontal(classes="param-row"):
                yield Label("Accelerator:", classes="param-label")
                yield Select(
                    [
                        ("Auto", "auto"),
                        ("CPU", "cpu"),
                        ("GPU (CUDA)", "gpu"),
                        ("MPS (Apple)", "mps"),
                    ],
                    value=self._state._accelerator if self._state else "auto",
                    id="instance-accelerator-select",
                    classes="param-input",
                )
                yield Label("Hardware for training", classes="param-hint")

            # Devices
            with Horizontal(classes="param-row"):
                yield Label("Devices:", classes="param-label")
                yield Select(
                    [("Auto", "auto"), ("1", "1"), ("2", "2"), ("4", "4")],
                    value=self._state._devices if self._state else "auto",
                    id="instance-devices-select",
                    classes="param-input",
                )
                yield Label("Number of GPUs", classes="param-hint")

            # Min Steps per Epoch
            with Horizontal(classes="param-row"):
                yield Label("Min Steps/Epoch:", classes="param-label")
                yield Input(
                    value=str(self._state._min_steps_per_epoch if self._state else 200),
                    id="instance-min-steps-input",
                    classes="param-input",
                    type="integer",
                )
                yield Label("Minimum training steps per epoch", classes="param-hint")

            # Random Seed
            with Horizontal(classes="param-row"):
                yield Label("Random Seed:", classes="param-label")
                yield Input(
                    value=(
                        str(self._state._random_seed)
                        if self._state and self._state._random_seed
                        else ""
                    ),
                    id="instance-random-seed-input",
                    classes="param-input",
                    type="integer",
                    placeholder="none",
                )
                yield Label("For reproducibility", classes="param-hint")

        # Instance memory estimate
        yield Static(id="instance-memory-display", classes="memory-info")

    # ==================== MEMORY ESTIMATE ====================

    def _compose_memory_estimate(self) -> ComposeResult:
        """Compose memory estimate display."""
        if not self._state:
            return

        yield Static(id="memory-info-display", classes="memory-info")

    # ==================== EVENT HANDLERS ====================

    # Data handlers
    @on(Input.Changed, "#scale-input")
    def handle_scale_change(self, event: Input.Changed) -> None:
        """Handle scale changes."""
        if self._state and event.value:
            try:
                self._state._input_scale = float(event.value)
                self._update_shape_display()
                self._update_memory_display()
            except ValueError:
                pass

    @on(Input.Changed, "#max-height-input")
    def handle_max_height_change(self, event: Input.Changed) -> None:
        """Handle max height changes."""
        if self._state:
            self._state._max_height = int(event.value) if event.value else None
            self._update_shape_display()
            self._update_memory_display()

    @on(Input.Changed, "#max-width-input")
    def handle_max_width_change(self, event: Input.Changed) -> None:
        """Handle max width changes."""
        if self._state:
            self._state._max_width = int(event.value) if event.value else None
            self._update_shape_display()
            self._update_memory_display()

    @on(Select.Changed, "#channels-select")
    def handle_channels_change(self, event: Select.Changed) -> None:
        """Handle channels changes."""
        if self._state and event.value:
            self._state._ensure_rgb = event.value == "rgb"
            self._state._ensure_grayscale = event.value == "grayscale"
            self._update_shape_display()
            self._update_memory_display()
            self._update_model_info_display()

    @on(Input.Changed, "#val-fraction-input")
    def handle_val_fraction_change(self, event: Input.Changed) -> None:
        """Handle val fraction changes."""
        if self._state and event.value:
            try:
                self._state._validation_fraction = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#num-workers-select")
    def handle_num_workers_select_change(self, event: Select.Changed) -> None:
        """Handle num workers changes."""
        if self._state and event.value:
            self._state._num_workers = int(event.value)
            self._update_cache_memory_display()

    @on(Select.Changed, "#data-pipeline-select")
    def handle_data_pipeline_change(self, event: Select.Changed) -> None:
        """Handle data pipeline changes."""
        if self._state and event.value:
            self._state._data_pipeline = DataPipelineType(event.value)
            self._update_memory_display()
            self._update_cache_memory_display()
            self._update_cache_options_visibility()

    # Model handlers
    @on(Select.Changed, "#backbone-select")
    def handle_backbone_change(self, event: Select.Changed) -> None:
        """Handle backbone changes."""
        if self._state and event.value:
            self._state._backbone = event.value
            if "convnext" in event.value or "swint" in event.value:
                self._state._max_stride = 32
                try:
                    select = self.query_one("#max-stride-select", Select)
                    select.value = "32"
                except Exception:
                    pass
            self._update_model_info_display()
            self._update_memory_display()
            self._update_imagenet_visibility()

    @on(Select.Changed, "#max-stride-select")
    def handle_stride_change(self, event: Select.Changed) -> None:
        """Handle stride changes."""
        if self._state and event.value:
            self._state._max_stride = int(event.value)
            self._update_model_info_display()
            self._update_memory_display()

    @on(Input.Changed, "#filters-input")
    def handle_filters_change(self, event: Input.Changed) -> None:
        """Handle filters changes."""
        if self._state and event.value:
            try:
                self._state._filters = int(event.value)
                self._update_model_info_display()
                self._update_memory_display()
            except ValueError:
                pass

    @on(Input.Changed, "#filters-rate-input")
    def handle_filters_rate_change(self, event: Input.Changed) -> None:
        """Handle filters rate changes."""
        if self._state and event.value:
            try:
                self._state._filters_rate = float(event.value)
                self._update_model_info_display()
                self._update_memory_display()
            except ValueError:
                pass

    @on(Input.Changed, "#sigma-input")
    def handle_sigma_change(self, event: Input.Changed) -> None:
        """Handle sigma changes."""
        if self._state and event.value:
            try:
                self._state._sigma = float(event.value)
                self._update_model_info_display()  # Update Gaussian radius display
            except ValueError:
                pass

    @on(Select.Changed, "#output-stride-select")
    def handle_output_stride_change(self, event: Select.Changed) -> None:
        """Handle output stride changes."""
        if self._state and event.value:
            self._state._output_stride = int(event.value)
            self._update_shape_display()
            self._update_memory_display()
            self._update_model_info_display()  # Update decoder blocks and Gaussian radius

    @on(Input.Changed, "#pretrained-backbone-input")
    def handle_pretrained_backbone_change(self, event: Input.Changed) -> None:
        """Handle pretrained backbone changes."""
        if self._state:
            self._state._pretrained_backbone = event.value or ""

    @on(Input.Changed, "#pretrained-head-input")
    def handle_pretrained_head_change(self, event: Input.Changed) -> None:
        """Handle pretrained head changes."""
        if self._state:
            self._state._pretrained_head = event.value or ""

    # PAF handlers
    @on(Input.Changed, "#paf-sigma-input")
    def handle_paf_sigma_change(self, event: Input.Changed) -> None:
        """Handle paf sigma changes."""
        if self._state and event.value:
            try:
                self._state._paf_config.sigma = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#paf-output-stride-select")
    def handle_paf_output_stride_change(self, event: Select.Changed) -> None:
        """Handle paf output stride changes."""
        if self._state and event.value:
            self._state._paf_config.output_stride = int(event.value)

    @on(Input.Changed, "#paf-loss-weight-input")
    def handle_paf_loss_weight_change(self, event: Input.Changed) -> None:
        """Handle paf loss weight changes."""
        if self._state and event.value:
            try:
                self._state._paf_config.loss_weight = float(event.value)
            except ValueError:
                pass

    # Class vector handlers
    @on(Select.Changed, "#fc-layers-select")
    def handle_fc_layers_change(self, event: Select.Changed) -> None:
        """Handle fc layers changes."""
        if self._state and event.value:
            self._state._class_vector_config.num_fc_layers = int(event.value)

    @on(Input.Changed, "#fc-units-input")
    def handle_fc_units_change(self, event: Input.Changed) -> None:
        """Handle fc units changes."""
        if self._state and event.value:
            try:
                self._state._class_vector_config.num_fc_units = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#class-loss-weight-input")
    def handle_class_loss_weight_change(self, event: Input.Changed) -> None:
        """Handle class loss weight changes."""
        if self._state and event.value:
            try:
                self._state._class_vector_config.loss_weight = float(event.value)
            except ValueError:
                pass

    # Training handlers
    @on(Select.Changed, "#batch-size-select")
    def handle_batch_change(self, event: Select.Changed) -> None:
        """Handle batch changes."""
        if self._state and event.value:
            self._state._batch_size = int(event.value)
            self._update_memory_display()

    @on(Input.Changed, "#max-epochs-input")
    def handle_epochs_change(self, event: Input.Changed) -> None:
        """Handle epochs changes."""
        if self._state and event.value:
            try:
                self._state._max_epochs = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#lr-input")
    def handle_lr_change(self, event: Input.Changed) -> None:
        """Handle lr changes."""
        if self._state and event.value:
            try:
                self._state._learning_rate = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#optimizer-select")
    def handle_optimizer_change(self, event: Select.Changed) -> None:
        """Handle optimizer changes."""
        if self._state and event.value:
            self._state._optimizer = event.value

    @on(Checkbox.Changed, "#early-stopping-checkbox")
    def handle_early_stopping_change(self, event: Checkbox.Changed) -> None:
        """Handle early stopping changes."""
        if self._state:
            self._state._early_stopping = event.value

    @on(Input.Changed, "#es-patience-input")
    def handle_es_patience_change(self, event: Input.Changed) -> None:
        """Handle es patience changes."""
        if self._state and event.value:
            try:
                self._state._early_stopping_patience = int(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#scheduler-select")
    def handle_scheduler_change(self, event: Select.Changed) -> None:
        """Handle scheduler changes."""
        if self._state and event.value:
            self._state._scheduler.type = SchedulerType(event.value)
            # Show/hide scheduler param containers
            self._update_scheduler_params_visibility(event.value)

    # Augmentation checkbox handlers (standard config)
    @on(Checkbox.Changed, "#rotation-checkbox")
    def handle_rotation_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle rotation changes."""
        if self._state:
            self._state._augmentation.rotation_enabled = event.value

    @on(Checkbox.Changed, "#scale-checkbox")
    def handle_scale_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle scale changes."""
        if self._state:
            self._state._augmentation.scale_enabled = event.value

    @on(Checkbox.Changed, "#brightness-checkbox")
    def handle_brightness_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle brightness changes."""
        if self._state:
            self._state._augmentation.brightness_enabled = event.value

    @on(Checkbox.Changed, "#contrast-checkbox")
    def handle_contrast_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle contrast changes."""
        if self._state:
            self._state._augmentation.contrast_enabled = event.value

    @on(Input.Changed, "#rotation-input")
    def handle_rotation_change(self, event: Input.Changed) -> None:
        """Handle rotation changes."""
        if self._state and event.value:
            try:
                val = float(event.value)
                self._state._augmentation.rotation_min = -abs(val)
                self._state._augmentation.rotation_max = abs(val)
            except ValueError:
                pass

    @on(Input.Changed, "#scale-min-input")
    def handle_scale_min_change(self, event: Input.Changed) -> None:
        """Handle scale min changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.scale_min = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scale-max-input")
    def handle_scale_max_change(self, event: Input.Changed) -> None:
        """Handle scale max changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.scale_max = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#brightness-limit-input")
    def handle_brightness_change(self, event: Input.Changed) -> None:
        """Handle brightness changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.brightness_limit = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#contrast-limit-input")
    def handle_contrast_change(self, event: Input.Changed) -> None:
        """Handle contrast changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.contrast_limit = float(event.value)
            except ValueError:
                pass

    # Checkpoint handlers
    @on(Input.Changed, "#ckpt-dir-input")
    def handle_ckpt_dir_change(self, event: Input.Changed) -> None:
        """Handle ckpt dir changes."""
        if self._state:
            self._state._checkpoint.checkpoint_dir = event.value or ""

    @on(Input.Changed, "#run-name-input")
    def handle_run_name_change(self, event: Input.Changed) -> None:
        """Handle run name changes."""
        if self._state:
            self._state._checkpoint.run_name = event.value or ""

    @on(Input.Changed, "#resume-ckpt-input")
    def handle_resume_ckpt_change(self, event: Input.Changed) -> None:
        """Handle resume ckpt changes."""
        if self._state:
            self._state._checkpoint.resume_from = event.value or ""

    @on(Input.Changed, "#save-top-k-input")
    def handle_save_top_k_change(self, event: Input.Changed) -> None:
        """Handle save top k changes."""
        if self._state and event.value:
            try:
                self._state._checkpoint.save_top_k = int(event.value)
            except ValueError:
                pass

    @on(Checkbox.Changed, "#save-last-checkbox")
    def handle_save_last_change(self, event: Checkbox.Changed) -> None:
        """Handle save last changes."""
        if self._state:
            self._state._checkpoint.save_last = event.value

    @on(Checkbox.Changed, "#wandb-checkbox")
    def handle_wandb_change(self, event: Checkbox.Changed) -> None:
        """Handle wandb changes."""
        if self._state:
            self._state._wandb.enabled = event.value
            self._update_wandb_options_visibility()

    @on(Input.Changed, "#wandb-project-input")
    def handle_wandb_project_change(self, event: Input.Changed) -> None:
        """Handle wandb project changes."""
        if self._state:
            self._state._wandb.project = event.value or "sleap-nn"

    @on(Input.Changed, "#wandb-entity-input")
    def handle_wandb_entity_change(self, event: Input.Changed) -> None:
        """Handle wandb entity changes."""
        if self._state:
            self._state._wandb.entity = event.value or ""

    # Advanced handlers
    @on(Select.Changed, "#accelerator-select")
    def handle_accelerator_change(self, event: Select.Changed) -> None:
        """Handle accelerator changes."""
        if self._state and event.value:
            self._state._accelerator = event.value

    @on(Input.Changed, "#min-steps-input")
    def handle_min_steps_change(self, event: Input.Changed) -> None:
        """Handle min steps changes."""
        if self._state and event.value:
            try:
                self._state._min_steps_per_epoch = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#random-seed-input")
    def handle_random_seed_change(self, event: Input.Changed) -> None:
        """Handle random seed changes."""
        if self._state:
            self._state._random_seed = int(event.value) if event.value else None

    # Visualization handlers
    @on(Checkbox.Changed, "#progress-bar-checkbox")
    def handle_progress_bar_change(self, event: Checkbox.Changed) -> None:
        """Handle progress bar changes."""
        if self._state:
            self._state._enable_progress_bar = event.value

    @on(Checkbox.Changed, "#save-viz-checkbox")
    def handle_save_viz_change(self, event: Checkbox.Changed) -> None:
        """Handle save viz changes."""
        if self._state:
            self._state._visualize_preds = event.value
            self._update_viz_options_visibility()

    @on(Checkbox.Changed, "#viz-keep-folder-checkbox")
    def handle_viz_keep_folder_change(self, event: Checkbox.Changed) -> None:
        """Handle viz keep folder changes."""
        if self._state:
            self._state._keep_viz = event.value

    @on(Checkbox.Changed, "#eval-checkbox")
    def handle_eval_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle eval changes."""
        if self._state:
            self._state._evaluation.enabled = event.value
            self._update_eval_options_visibility()

    # Legacy handlers for backwards compatibility
    @on(Checkbox.Changed, "#visualize-preds-checkbox")
    def handle_visualize_preds_change(self, event: Checkbox.Changed) -> None:
        """Handle visualize preds changes."""
        if self._state:
            self._state._visualize_preds = event.value
            self._update_viz_options_visibility()

    @on(Checkbox.Changed, "#keep-viz-checkbox")
    def handle_keep_viz_change(self, event: Checkbox.Changed) -> None:
        """Handle keep viz changes."""
        if self._state:
            self._state._keep_viz = event.value

    # Cache config handlers
    @on(Checkbox.Changed, "#parallel-caching-checkbox")
    def handle_parallel_caching_change(self, event: Checkbox.Changed) -> None:
        """Handle parallel caching changes."""
        if self._state:
            self._state._cache_config.parallel_caching = event.value

    @on(Input.Changed, "#cache-workers-input")
    def handle_cache_workers_change(self, event: Input.Changed) -> None:
        """Handle cache workers changes."""
        if self._state and event.value:
            try:
                self._state._cache_config.cache_workers = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#cache-path-input")
    def handle_cache_path_change(self, event: Input.Changed) -> None:
        """Handle cache path changes."""
        if self._state:
            self._state._cache_config.cache_img_path = event.value or ""

    @on(Checkbox.Changed, "#use-existing-checkbox")
    def handle_use_existing_change(self, event: Checkbox.Changed) -> None:
        """Handle use existing changes."""
        if self._state:
            self._state._cache_config.use_existing_imgs = event.value

    @on(Checkbox.Changed, "#delete-cache-checkbox")
    def handle_delete_cache_change(self, event: Checkbox.Changed) -> None:
        """Handle delete cache changes."""
        if self._state:
            self._state._cache_config.delete_cache_after_training = event.value

    @on(Checkbox.Changed, "#ohkm-checkbox")
    def handle_ohkm_change(self, event: Checkbox.Changed) -> None:
        """Handle ohkm changes."""
        if self._state:
            self._state._ohkm.enabled = event.value

    @on(Input.Changed, "#ohkm-ratio-input")
    def handle_ohkm_ratio_change(self, event: Input.Changed) -> None:
        """Handle ohkm ratio changes."""
        if self._state and event.value:
            try:
                self._state._ohkm.hard_to_easy_ratio = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#ohkm-scale-input")
    def handle_ohkm_scale_change(self, event: Input.Changed) -> None:
        """Handle ohkm scale changes."""
        if self._state and event.value:
            try:
                self._state._ohkm.loss_scale = float(event.value)
            except ValueError:
                pass

    # Top-down specific handlers
    @on(Select.Changed, "#anchor-part-select")
    def handle_anchor_change(self, event: Select.Changed) -> None:
        """Handle anchor changes."""
        if self._state:
            self._state._anchor_part = event.value if event.value else None

    @on(Input.Changed, "#centroid-scale-input")
    def handle_centroid_scale_change(self, event: Input.Changed) -> None:
        """Handle centroid scale changes."""
        if self._state and event.value:
            try:
                self._state._input_scale = float(event.value)
                self._update_centroid_shape_display()
                self._update_centroid_model_info_display()
                self._update_centroid_memory_display()
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-sigma-input")
    def handle_centroid_sigma_change(self, event: Input.Changed) -> None:
        """Handle centroid sigma changes."""
        if self._state and event.value:
            try:
                self._state._sigma = float(event.value)
                self._update_centroid_model_info_display()
            except ValueError:
                pass

    @on(Select.Changed, "#centroid-backbone-select")
    def handle_centroid_backbone_change(self, event: Select.Changed) -> None:
        """Handle centroid backbone changes."""
        if self._state and event.value:
            self._state._backbone = event.value
            self._update_centroid_model_info_display()
            self._update_centroid_memory_display()
            self._update_imagenet_visibility()

    @on(Input.Changed, "#crop-size-input")
    def handle_crop_size_change(self, event: Input.Changed) -> None:
        """Handle crop size changes."""
        if self._state and event.value:
            try:
                self._state._crop_size = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#min-crop-size-input")
    def handle_min_crop_size_change(self, event: Input.Changed) -> None:
        """Handle min crop size changes."""
        if self._state and event.value:
            try:
                self._state._ci_min_crop_size = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-scale-input")
    def handle_instance_scale_change(self, event: Input.Changed) -> None:
        """Handle instance scale changes."""
        if self._state and event.value:
            try:
                self._state._ci_input_scale = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-sigma-input")
    def handle_instance_sigma_change(self, event: Input.Changed) -> None:
        """Handle instance sigma changes."""
        if self._state and event.value:
            try:
                self._state._ci_sigma = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#instance-backbone-select")
    def handle_instance_backbone_change(self, event: Select.Changed) -> None:
        """Handle instance backbone changes."""
        if self._state and event.value:
            self._state._ci_backbone = event.value

    @on(Select.Changed, "#instance-output-stride-select")
    def handle_instance_output_stride_change(self, event: Select.Changed) -> None:
        """Handle instance output stride changes."""
        if self._state and event.value:
            self._state._ci_output_stride = int(event.value)

    # Additional top-down handlers
    @on(Input.Changed, "#centroid-max-height-input")
    def handle_centroid_max_height_change(self, event: Input.Changed) -> None:
        """Handle centroid max height changes."""
        if self._state:
            self._state._max_height = int(event.value) if event.value else None

    @on(Input.Changed, "#centroid-max-width-input")
    def handle_centroid_max_width_change(self, event: Input.Changed) -> None:
        """Handle centroid max width changes."""
        if self._state:
            self._state._max_width = int(event.value) if event.value else None

    @on(Select.Changed, "#centroid-max-stride-select")
    def handle_centroid_max_stride_change(self, event: Select.Changed) -> None:
        """Handle centroid max stride changes."""
        if self._state and event.value:
            self._state._max_stride = int(event.value)
            self._update_centroid_model_info_display()

    @on(Select.Changed, "#centroid-output-stride-select")
    def handle_centroid_output_stride_change(self, event: Select.Changed) -> None:
        """Handle centroid output stride changes."""
        if self._state and event.value:
            self._state._output_stride = int(event.value)
            self._update_centroid_shape_display()
            self._update_centroid_model_info_display()

    @on(Select.Changed, "#centroid-batch-size-select")
    def handle_centroid_batch_change(self, event: Select.Changed) -> None:
        """Handle centroid batch changes."""
        if self._state and event.value:
            self._state._batch_size = int(event.value)
            self._update_centroid_memory_display()

    @on(Input.Changed, "#centroid-max-epochs-input")
    def handle_centroid_epochs_change(self, event: Input.Changed) -> None:
        """Handle centroid epochs changes."""
        if self._state and event.value:
            try:
                self._state._max_epochs = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-lr-input")
    def handle_centroid_lr_change(self, event: Input.Changed) -> None:
        """Handle centroid lr changes."""
        if self._state and event.value:
            try:
                self._state._learning_rate = float(event.value)
            except ValueError:
                pass

    # Centroid augmentation checkbox handlers
    @on(Checkbox.Changed, "#centroid-rotation-checkbox")
    def handle_centroid_rotation_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid rotation changes."""
        if self._state:
            self._state._augmentation.rotation_enabled = event.value

    @on(Checkbox.Changed, "#centroid-scale-checkbox")
    def handle_centroid_scale_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid scale changes."""
        if self._state:
            self._state._augmentation.scale_enabled = event.value

    @on(Checkbox.Changed, "#centroid-brightness-checkbox")
    def handle_centroid_brightness_checkbox_change(
        self, event: Checkbox.Changed
    ) -> None:
        """Handle centroid brightness changes."""
        if self._state:
            self._state._augmentation.brightness_enabled = event.value

    @on(Checkbox.Changed, "#centroid-contrast-checkbox")
    def handle_centroid_contrast_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid contrast changes."""
        if self._state:
            self._state._augmentation.contrast_enabled = event.value

    @on(Input.Changed, "#centroid-rotation-input")
    def handle_centroid_rotation_change(self, event: Input.Changed) -> None:
        """Handle centroid rotation changes."""
        if self._state and event.value:
            try:
                val = float(event.value)
                self._state._augmentation.rotation_max = val
                self._state._augmentation.rotation_min = -val
            except ValueError:
                pass

    @on(Select.Changed, "#instance-max-stride-select")
    def handle_instance_max_stride_change(self, event: Select.Changed) -> None:
        """Handle instance max stride changes."""
        if self._state and event.value:
            self._state._ci_max_stride = int(event.value)

    @on(Select.Changed, "#instance-batch-size-select")
    def handle_instance_batch_change(self, event: Select.Changed) -> None:
        """Handle instance batch changes."""
        if self._state and event.value:
            self._state._ci_batch_size = int(event.value)

    @on(Input.Changed, "#instance-max-epochs-input")
    def handle_instance_epochs_change(self, event: Input.Changed) -> None:
        """Handle instance epochs changes."""
        if self._state and event.value:
            try:
                self._state._ci_max_epochs = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-lr-input")
    def handle_instance_lr_change(self, event: Input.Changed) -> None:
        """Handle instance lr changes."""
        if self._state and event.value:
            try:
                self._state._ci_learning_rate = float(event.value)
            except ValueError:
                pass

    # Instance augmentation checkbox handlers
    @on(Checkbox.Changed, "#instance-rotation-checkbox")
    def handle_instance_rotation_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle instance rotation changes."""
        if self._state:
            self._state._ci_augmentation.rotation_enabled = event.value

    @on(Checkbox.Changed, "#instance-scale-checkbox")
    def handle_instance_scale_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle instance scale changes."""
        if self._state:
            self._state._ci_augmentation.scale_enabled = event.value

    @on(Checkbox.Changed, "#instance-brightness-checkbox")
    def handle_instance_brightness_checkbox_change(
        self, event: Checkbox.Changed
    ) -> None:
        """Handle instance brightness changes."""
        if self._state:
            self._state._ci_augmentation.brightness_enabled = event.value

    @on(Checkbox.Changed, "#instance-contrast-checkbox")
    def handle_instance_contrast_checkbox_change(self, event: Checkbox.Changed) -> None:
        """Handle instance contrast changes."""
        if self._state:
            self._state._ci_augmentation.contrast_enabled = event.value

    @on(Input.Changed, "#instance-rotation-input")
    def handle_instance_rotation_change(self, event: Input.Changed) -> None:
        """Handle instance rotation changes."""
        if self._state and event.value:
            try:
                val = float(event.value)
                self._state._ci_augmentation.rotation_max = val
                self._state._ci_augmentation.rotation_min = -val
            except ValueError:
                pass

    # Checkpoint handlers for top-down models
    @on(Input.Changed, "#centroid-ckpt-dir-input")
    def handle_centroid_ckpt_dir_change(self, event: Input.Changed) -> None:
        """Handle centroid ckpt dir changes."""
        if self._state:
            self._state._checkpoint.checkpoint_dir = event.value or ""

    @on(Input.Changed, "#centroid-run-name-input")
    def handle_centroid_run_name_change(self, event: Input.Changed) -> None:
        """Handle centroid run name changes."""
        if self._state:
            self._state._checkpoint.run_name = event.value or ""

    @on(Input.Changed, "#instance-ckpt-dir-input")
    def handle_instance_ckpt_dir_change(self, event: Input.Changed) -> None:
        """Handle instance ckpt dir changes."""
        if self._state:
            self._state._ci_checkpoint_dir = event.value or ""

    @on(Input.Changed, "#instance-run-name-input")
    def handle_instance_run_name_change(self, event: Input.Changed) -> None:
        """Handle instance run name changes."""
        if self._state:
            self._state._ci_run_name = event.value or ""

    # Centroid augmentation handlers
    @on(Input.Changed, "#centroid-scale-min-input")
    def handle_centroid_scale_min_change(self, event: Input.Changed) -> None:
        """Handle centroid scale min changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.scale_min = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-scale-max-input")
    def handle_centroid_scale_max_change(self, event: Input.Changed) -> None:
        """Handle centroid scale max changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.scale_max = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-brightness-input")
    def handle_centroid_brightness_change(self, event: Input.Changed) -> None:
        """Handle centroid brightness changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.brightness_limit = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-contrast-input")
    def handle_centroid_contrast_change(self, event: Input.Changed) -> None:
        """Handle centroid contrast changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.contrast_limit = float(event.value)
            except ValueError:
                pass

    # Instance augmentation handlers
    @on(Input.Changed, "#instance-scale-min-input")
    def handle_instance_scale_min_change(self, event: Input.Changed) -> None:
        """Handle instance scale min changes."""
        if self._state and event.value:
            try:
                self._state._ci_augmentation.scale_min = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-scale-max-input")
    def handle_instance_scale_max_change(self, event: Input.Changed) -> None:
        """Handle instance scale max changes."""
        if self._state and event.value:
            try:
                self._state._ci_augmentation.scale_max = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-brightness-input")
    def handle_instance_brightness_change(self, event: Input.Changed) -> None:
        """Handle instance brightness changes."""
        if self._state and event.value:
            try:
                self._state._ci_augmentation.brightness_limit = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-contrast-input")
    def handle_instance_contrast_change(self, event: Input.Changed) -> None:
        """Handle instance contrast changes."""
        if self._state and event.value:
            try:
                self._state._ci_augmentation.contrast_limit = float(event.value)
            except ValueError:
                pass

    # Instance Checkpoint & Logging handlers
    @on(Checkbox.Changed, "#instance-save-ckpt-checkbox")
    def handle_instance_save_ckpt_change(self, event: Checkbox.Changed) -> None:
        """Handle instance save ckpt changes."""
        if self._state:
            self._state._checkpoint.enabled = event.value

    @on(Input.Changed, "#instance-save-top-k-input")
    def handle_instance_save_top_k_change(self, event: Input.Changed) -> None:
        """Handle instance save top k changes."""
        if self._state and event.value:
            try:
                self._state._checkpoint.save_top_k = int(event.value)
            except ValueError:
                pass

    @on(Checkbox.Changed, "#instance-save-last-checkbox")
    def handle_instance_save_last_change(self, event: Checkbox.Changed) -> None:
        """Handle instance save last changes."""
        if self._state:
            self._state._checkpoint.save_last = event.value

    @on(Checkbox.Changed, "#instance-wandb-checkbox")
    def handle_instance_wandb_change(self, event: Checkbox.Changed) -> None:
        """Handle instance wandb changes."""
        if self._state:
            self._state._wandb.enabled = event.value
            self._update_wandb_options_visibility()

    @on(Input.Changed, "#instance-wandb-project-input")
    def handle_instance_wandb_project_change(self, event: Input.Changed) -> None:
        """Handle instance wandb project changes."""
        if self._state:
            self._state._wandb.project = event.value or "sleap-training"

    @on(Input.Changed, "#instance-wandb-entity-input")
    def handle_instance_wandb_entity_change(self, event: Input.Changed) -> None:
        """Handle instance wandb entity changes."""
        if self._state:
            self._state._wandb.entity = event.value or ""

    @on(Checkbox.Changed, "#instance-save-viz-checkbox")
    def handle_instance_save_viz_change(self, event: Checkbox.Changed) -> None:
        """Handle instance save viz changes."""
        if self._state:
            self._state._visualize_preds = event.value
            self._update_viz_options_visibility()

    @on(Checkbox.Changed, "#instance-viz-keep-folder-checkbox")
    def handle_instance_viz_keep_folder_change(self, event: Checkbox.Changed) -> None:
        """Handle instance viz keep folder changes."""
        if self._state:
            self._state._keep_viz = event.value

    @on(Checkbox.Changed, "#instance-eval-checkbox")
    def handle_instance_eval_change(self, event: Checkbox.Changed) -> None:
        """Handle instance eval changes."""
        if self._state:
            self._state._evaluation.enabled = event.value
            self._update_eval_options_visibility()

    @on(Input.Changed, "#instance-eval-frequency-input")
    def handle_instance_eval_frequency_change(self, event: Input.Changed) -> None:
        """Handle instance eval frequency changes."""
        if self._state and event.value:
            try:
                self._state._evaluation.frequency = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-eval-oks-input")
    def handle_instance_eval_oks_change(self, event: Input.Changed) -> None:
        """Handle instance eval oks changes."""
        if self._state and event.value:
            try:
                self._state._evaluation.oks_stddev = float(event.value)
            except ValueError:
                pass

    # Instance Advanced params handlers
    @on(Select.Changed, "#instance-optimizer-select")
    def handle_instance_optimizer_change(self, event: Select.Changed) -> None:
        """Handle instance optimizer changes."""
        if self._state and event.value:
            self._state._ci_optimizer = event.value

    @on(Checkbox.Changed, "#instance-early-stopping-checkbox")
    def handle_instance_early_stopping_change(self, event: Checkbox.Changed) -> None:
        """Handle instance early stopping changes."""
        if self._state:
            self._state._ci_early_stopping = event.value

    @on(Input.Changed, "#instance-es-patience-input")
    def handle_instance_es_patience_change(self, event: Input.Changed) -> None:
        """Handle instance es patience changes."""
        if self._state and event.value:
            try:
                self._state._ci_early_stopping_patience = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-es-min-delta-input")
    def handle_instance_es_min_delta_change(self, event: Input.Changed) -> None:
        """Handle instance es min delta changes."""
        if self._state and event.value:
            try:
                self._state._ci_early_stopping_min_delta = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#instance-scheduler-select")
    def handle_instance_scheduler_change(self, event: Select.Changed) -> None:
        """Handle instance scheduler changes."""
        if self._state and event.value:
            from sleap_nn.config_generator.tui.state import SchedulerType

            self._state._ci_scheduler.type = SchedulerType(event.value)

    @on(Input.Changed, "#instance-lr-patience-input")
    def handle_instance_lr_patience_change(self, event: Input.Changed) -> None:
        """Handle instance lr patience changes."""
        if self._state and event.value:
            try:
                self._state._ci_scheduler.plateau_patience = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-lr-factor-input")
    def handle_instance_lr_factor_change(self, event: Input.Changed) -> None:
        """Handle instance lr factor changes."""
        if self._state and event.value:
            try:
                self._state._ci_scheduler.factor = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#instance-accelerator-select")
    def handle_instance_accelerator_change(self, event: Select.Changed) -> None:
        """Handle instance accelerator changes."""
        if self._state and event.value:
            self._state._accelerator = event.value

    @on(Select.Changed, "#instance-devices-select")
    def handle_instance_devices_change(self, event: Select.Changed) -> None:
        """Handle instance devices changes."""
        if self._state and event.value:
            self._state._devices = event.value

    @on(Input.Changed, "#instance-min-steps-input")
    def handle_instance_min_steps_change(self, event: Input.Changed) -> None:
        """Handle instance min steps changes."""
        if self._state and event.value:
            try:
                self._state._min_steps_per_epoch = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-random-seed-input")
    def handle_instance_random_seed_change(self, event: Input.Changed) -> None:
        """Handle instance random seed changes."""
        if self._state:
            self._state._random_seed = int(event.value) if event.value else None

    @on(Select.Changed, "#instance-lr-select")
    def handle_instance_lr_select_change(self, event: Select.Changed) -> None:
        """Handle instance lr changes."""
        if self._state and event.value:
            self._state._ci_learning_rate = float(event.value)

    # Instance Data Pipeline handlers
    @on(Select.Changed, "#instance-num-workers-select")
    def handle_instance_num_workers_select_change(self, event: Select.Changed) -> None:
        """Handle instance num workers changes."""
        if self._state and event.value:
            self._state._num_workers = int(event.value)
            self._update_instance_cache_memory_display()

    @on(Select.Changed, "#instance-data-pipeline-select")
    def handle_instance_data_pipeline_change(self, event: Select.Changed) -> None:
        """Handle instance data pipeline changes."""
        if self._state and event.value:
            from sleap_nn.config_generator.tui.state import DataPipelineType

            self._state._data_pipeline = DataPipelineType(event.value)
            self._update_instance_cache_memory_display()
            self._update_instance_cache_options_visibility()

    @on(Checkbox.Changed, "#instance-parallel-caching-checkbox")
    def handle_instance_parallel_caching_change(self, event: Checkbox.Changed) -> None:
        """Handle instance parallel caching changes."""
        if self._state:
            self._state._cache_config.parallel_caching = event.value

    @on(Input.Changed, "#instance-cache-workers-input")
    def handle_instance_cache_workers_change(self, event: Input.Changed) -> None:
        """Handle instance cache workers changes."""
        if self._state and event.value:
            try:
                self._state._cache_config.cache_workers = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-cache-path-input")
    def handle_instance_cache_path_change(self, event: Input.Changed) -> None:
        """Handle instance cache path changes."""
        if self._state:
            self._state._cache_config.cache_img_path = event.value or ""

    @on(Checkbox.Changed, "#instance-use-existing-checkbox")
    def handle_instance_use_existing_change(self, event: Checkbox.Changed) -> None:
        """Handle instance use existing changes."""
        if self._state:
            self._state._cache_config.use_existing_imgs = event.value

    @on(Checkbox.Changed, "#instance-delete-cache-checkbox")
    def handle_instance_delete_cache_change(self, event: Checkbox.Changed) -> None:
        """Handle instance delete cache changes."""
        if self._state:
            self._state._cache_config.delete_cache_after_training = event.value

    @on(Select.Changed, "#instance-channels-select")
    def handle_instance_channels_change(self, event: Select.Changed) -> None:
        """Handle instance channels changes."""
        if self._state and event.value:
            self._state._ensure_rgb = event.value == "rgb"
            self._state._ensure_grayscale = event.value == "grayscale"

    # Instance Model handlers
    @on(Input.Changed, "#instance-filters-input")
    def handle_instance_filters_change(self, event: Input.Changed) -> None:
        """Handle instance filters changes."""
        if self._state and event.value:
            try:
                self._state._ci_filters = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-filters-rate-input")
    def handle_instance_filters_rate_change(self, event: Input.Changed) -> None:
        """Handle instance filters rate changes."""
        if self._state and event.value:
            try:
                self._state._ci_filters_rate = float(event.value)
            except ValueError:
                pass

    @on(Checkbox.Changed, "#instance-imagenet-checkbox")
    def handle_instance_imagenet_change(self, event: Checkbox.Changed) -> None:
        """Handle instance imagenet changes."""
        if self._state:
            self._state._use_imagenet_pretrained = event.value

    @on(Input.Changed, "#instance-pretrained-backbone-input")
    def handle_instance_pretrained_backbone_change(self, event: Input.Changed) -> None:
        """Handle instance pretrained backbone changes."""
        if self._state:
            self._state._ci_pretrained_backbone = event.value or ""

    @on(Input.Changed, "#instance-pretrained-head-input")
    def handle_instance_pretrained_head_change(self, event: Input.Changed) -> None:
        """Handle instance pretrained head changes."""
        if self._state:
            self._state._ci_pretrained_head = event.value or ""

    # Instance OHKM handlers
    @on(Checkbox.Changed, "#instance-ohkm-checkbox")
    def handle_instance_ohkm_change(self, event: Checkbox.Changed) -> None:
        """Handle instance ohkm changes."""
        if self._state:
            self._state._ohkm.enabled = event.value

    @on(Input.Changed, "#instance-ohkm-ratio-input")
    def handle_instance_ohkm_ratio_change(self, event: Input.Changed) -> None:
        """Handle instance ohkm ratio changes."""
        if self._state and event.value:
            try:
                self._state._ohkm.hard_to_easy_ratio = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-ohkm-scale-input")
    def handle_instance_ohkm_scale_change(self, event: Input.Changed) -> None:
        """Handle instance ohkm scale changes."""
        if self._state and event.value:
            try:
                self._state._ohkm.loss_scale = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-ohkm-min-input")
    def handle_instance_ohkm_min_change(self, event: Input.Changed) -> None:
        """Handle instance ohkm min changes."""
        if self._state and event.value:
            try:
                self._state._ohkm.min_hard_keypoints = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#instance-ohkm-max-input")
    def handle_instance_ohkm_max_change(self, event: Input.Changed) -> None:
        """Handle instance ohkm max changes."""
        if self._state:
            self._state._ohkm.max_hard_keypoints = (
                int(event.value) if event.value else None
            )

    # Evaluation handlers (legacy)
    @on(Checkbox.Changed, "#evaluation-checkbox")
    def handle_evaluation_change(self, event: Checkbox.Changed) -> None:
        """Handle evaluation changes."""
        if self._state:
            self._state._evaluation.enabled = event.value
            self._update_eval_options_visibility()

    @on(Input.Changed, "#eval-frequency-input")
    def handle_eval_frequency_change(self, event: Input.Changed) -> None:
        """Handle eval frequency changes."""
        if self._state and event.value:
            try:
                self._state._evaluation.frequency = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#eval-oks-input")
    def handle_eval_oks_change(self, event: Input.Changed) -> None:
        """Handle eval oks changes."""
        if self._state and event.value:
            try:
                self._state._evaluation.oks_stddev = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#oks-stddev-input")
    def handle_oks_stddev_change(self, event: Input.Changed) -> None:
        """Handle oks stddev changes."""
        if self._state and event.value:
            try:
                self._state._evaluation.oks_stddev = float(event.value)
            except ValueError:
                pass

    # Scheduler visibility helper
    def _update_scheduler_params_visibility(self, scheduler_type: str) -> None:
        """Show/hide scheduler parameter containers based on selected type."""
        containers = {
            "scheduler-reduce-params": SchedulerType.REDUCE_ON_PLATEAU,
            "scheduler-step-params": SchedulerType.STEP_LR,
            "scheduler-cosine-params": SchedulerType.COSINE_ANNEALING_WARMUP,
            "scheduler-linear-params": SchedulerType.LINEAR_WARMUP_LINEAR_DECAY,
        }
        for container_id, sched_type in containers.items():
            try:
                container = self.query_one(f"#{container_id}", Container)
                if scheduler_type == sched_type.value:
                    container.remove_class("hidden")
                else:
                    container.add_class("hidden")
            except Exception:
                pass

    # Scheduler parameter handlers - ReduceLROnPlateau
    @on(Input.Changed, "#scheduler-factor-input")
    def handle_scheduler_factor_change(self, event: Input.Changed) -> None:
        """Handle scheduler factor changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.factor = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-patience-input")
    def handle_scheduler_patience_change(self, event: Input.Changed) -> None:
        """Handle scheduler patience changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.plateau_patience = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-min-lr-input")
    def handle_scheduler_min_lr_change(self, event: Input.Changed) -> None:
        """Handle scheduler min lr changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.min_lr = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-cooldown-input")
    def handle_scheduler_cooldown_change(self, event: Input.Changed) -> None:
        """Handle scheduler cooldown changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.cooldown = int(event.value)
            except ValueError:
                pass

    # Scheduler parameter handlers - StepLR
    @on(Input.Changed, "#scheduler-step-size-input")
    def handle_scheduler_step_size_change(self, event: Input.Changed) -> None:
        """Handle scheduler step size changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.step_size = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-gamma-input")
    def handle_scheduler_gamma_change(self, event: Input.Changed) -> None:
        """Handle scheduler gamma changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.gamma = float(event.value)
            except ValueError:
                pass

    # Scheduler parameter handlers - CosineAnnealingWarmup
    @on(Input.Changed, "#scheduler-warmup-epochs-input")
    def handle_scheduler_warmup_epochs_change(self, event: Input.Changed) -> None:
        """Handle scheduler warmup epochs changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.warmup_epochs = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-warmup-start-lr-input")
    def handle_scheduler_warmup_start_lr_change(self, event: Input.Changed) -> None:
        """Handle scheduler warmup start lr changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.warmup_start_lr = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-eta-min-input")
    def handle_scheduler_eta_min_change(self, event: Input.Changed) -> None:
        """Handle scheduler eta min changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.eta_min = float(event.value)
            except ValueError:
                pass

    # Scheduler parameter handlers - LinearWarmupLinearDecay
    @on(Input.Changed, "#scheduler-linear-warmup-epochs-input")
    def handle_scheduler_linear_warmup_epochs_change(
        self, event: Input.Changed
    ) -> None:
        """Handle scheduler linear warmup epochs changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.linear_warmup_epochs = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-linear-warmup-start-lr-input")
    def handle_scheduler_linear_warmup_start_lr_change(
        self, event: Input.Changed
    ) -> None:
        """Handle scheduler linear warmup start lr changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.linear_warmup_start_lr = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#scheduler-end-lr-input")
    def handle_scheduler_end_lr_change(self, event: Input.Changed) -> None:
        """Handle scheduler end lr changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.end_lr = float(event.value)
            except ValueError:
                pass

    # WandB visualization handlers
    @on(Checkbox.Changed, "#wandb-viz-checkbox")
    def handle_wandb_viz_change(self, event: Checkbox.Changed) -> None:
        """Handle wandb viz changes."""
        if self._state:
            self._state._wandb.viz_enabled = event.value

    @on(Checkbox.Changed, "#wandb-save-viz-checkbox")
    def handle_wandb_save_viz_change(self, event: Checkbox.Changed) -> None:
        """Handle wandb save viz changes."""
        if self._state:
            self._state._wandb.save_viz_imgs = event.value

    # Devices handler
    @on(Select.Changed, "#devices-select")
    def handle_devices_change(self, event: Select.Changed) -> None:
        """Handle devices changes."""
        if self._state and event.value:
            self._state._devices = event.value

    # ==================== CENTROID-SPECIFIC HANDLERS ====================
    # These handle inputs specific to the centroid tab that aren't covered by standard handlers

    @on(Checkbox.Changed, "#centroid-translate-checkbox")
    def handle_centroid_translate_checkbox_change(
        self, event: Checkbox.Changed
    ) -> None:
        """Handle centroid translate changes."""
        if self._state:
            self._state._augmentation.translate_enabled = event.value

    @on(Input.Changed, "#centroid-translate-input")
    def handle_centroid_translate_change(self, event: Input.Changed) -> None:
        """Handle centroid translate changes."""
        if self._state and event.value:
            try:
                self._state._augmentation.translate = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-val-fraction-input")
    def handle_centroid_val_fraction_change(self, event: Input.Changed) -> None:
        """Handle centroid val fraction changes."""
        if self._state and event.value:
            try:
                self._state._validation_fraction = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#centroid-channels-select")
    def handle_centroid_channels_change(self, event: Select.Changed) -> None:
        """Handle centroid channels changes."""
        if self._state and event.value:
            self._state._ensure_rgb = event.value == "rgb"
            self._state._ensure_grayscale = event.value == "grayscale"
            self._update_centroid_shape_display()
            self._update_centroid_memory_display()
            self._update_centroid_model_info_display()

    @on(Select.Changed, "#centroid-data-pipeline-select")
    def handle_centroid_data_pipeline_change(self, event: Select.Changed) -> None:
        """Handle centroid data pipeline changes."""
        if self._state and event.value:
            self._state._data_pipeline = DataPipelineType(event.value)
            self._update_cache_memory_display()
            self._update_centroid_cache_memory_display()
            self._update_centroid_cache_options_visibility()

    @on(Input.Changed, "#centroid-filters-input")
    def handle_centroid_filters_change(self, event: Input.Changed) -> None:
        """Handle centroid filters changes."""
        if self._state and event.value:
            try:
                self._state._filters = int(event.value)
                self._update_centroid_model_info_display()
                self._update_centroid_memory_display()
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-filters-rate-input")
    def handle_centroid_filters_rate_change(self, event: Input.Changed) -> None:
        """Handle centroid filters rate changes."""
        if self._state and event.value:
            try:
                self._state._filters_rate = float(event.value)
                self._update_centroid_model_info_display()
                self._update_centroid_memory_display()
            except ValueError:
                pass

    @on(Checkbox.Changed, "#centroid-imagenet-checkbox")
    def handle_centroid_imagenet_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid imagenet changes."""
        if self._state:
            self._state._use_imagenet_pretrained = event.value

    @on(Input.Changed, "#centroid-pretrained-backbone-input")
    def handle_centroid_pretrained_backbone_change(self, event: Input.Changed) -> None:
        """Handle centroid pretrained backbone changes."""
        if self._state:
            self._state._pretrained_backbone = event.value or ""

    @on(Input.Changed, "#centroid-pretrained-head-input")
    def handle_centroid_pretrained_head_change(self, event: Input.Changed) -> None:
        """Handle centroid pretrained head changes."""
        if self._state:
            self._state._pretrained_head = event.value or ""

    @on(Select.Changed, "#centroid-optimizer-select")
    def handle_centroid_optimizer_change(self, event: Select.Changed) -> None:
        """Handle centroid optimizer changes."""
        if self._state and event.value:
            self._state._optimizer = event.value

    @on(Checkbox.Changed, "#centroid-early-stopping-checkbox")
    def handle_centroid_early_stopping_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid early stopping changes."""
        if self._state:
            self._state._early_stopping = event.value

    @on(Input.Changed, "#centroid-es-patience-input")
    def handle_centroid_es_patience_change(self, event: Input.Changed) -> None:
        """Handle centroid es patience changes."""
        if self._state and event.value:
            try:
                self._state._early_stopping_patience = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-es-min-delta-input")
    def handle_centroid_es_min_delta_change(self, event: Input.Changed) -> None:
        """Handle centroid es min delta changes."""
        if self._state and event.value:
            try:
                self._state._early_stopping_min_delta = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-lr-patience-input")
    def handle_centroid_lr_patience_change(self, event: Input.Changed) -> None:
        """Handle centroid lr patience changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.plateau_patience = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-lr-factor-input")
    def handle_centroid_lr_factor_change(self, event: Input.Changed) -> None:
        """Handle centroid lr factor changes."""
        if self._state and event.value:
            try:
                self._state._scheduler.factor = float(event.value)
            except ValueError:
                pass

    @on(Select.Changed, "#centroid-scheduler-select")
    def handle_centroid_scheduler_change(self, event: Select.Changed) -> None:
        """Handle centroid scheduler changes."""
        if self._state and event.value:
            self._state._scheduler.type = SchedulerType(event.value)

    @on(Checkbox.Changed, "#centroid-save-ckpt-checkbox")
    def handle_centroid_save_ckpt_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid save ckpt changes."""
        if self._state:
            self._state._checkpoint.enabled = event.value

    @on(Input.Changed, "#centroid-save-top-k-input")
    def handle_centroid_save_top_k_change(self, event: Input.Changed) -> None:
        """Handle centroid save top k changes."""
        if self._state and event.value:
            try:
                self._state._checkpoint.save_top_k = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-resume-ckpt-input")
    def handle_centroid_resume_ckpt_change(self, event: Input.Changed) -> None:
        """Handle centroid resume ckpt changes."""
        if self._state:
            self._state._checkpoint.resume_from = event.value or ""

    @on(Checkbox.Changed, "#centroid-wandb-checkbox")
    def handle_centroid_wandb_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid wandb changes."""
        if self._state:
            self._state._wandb.enabled = event.value
            self._update_wandb_options_visibility()

    @on(Checkbox.Changed, "#centroid-save-viz-checkbox")
    def handle_centroid_save_viz_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid save viz changes."""
        if self._state:
            self._state._visualize_preds = event.value
            self._update_viz_options_visibility()

    @on(Checkbox.Changed, "#centroid-viz-keep-folder-checkbox")
    def handle_centroid_viz_keep_folder_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid viz keep folder changes."""
        if self._state:
            self._state._keep_viz = event.value

    @on(Checkbox.Changed, "#centroid-eval-checkbox")
    def handle_centroid_eval_change(self, event: Checkbox.Changed) -> None:
        """Handle centroid eval changes."""
        if self._state:
            self._state._evaluation.enabled = event.value
            self._update_eval_options_visibility()

    @on(Input.Changed, "#centroid-eval-frequency-input")
    def handle_centroid_eval_frequency_change(self, event: Input.Changed) -> None:
        """Handle centroid eval frequency changes."""
        if self._state and event.value:
            try:
                self._state._evaluation.frequency = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-eval-oks-input")
    def handle_centroid_eval_oks_change(self, event: Input.Changed) -> None:
        """Handle centroid eval oks changes."""
        if self._state and event.value:
            try:
                self._state._evaluation.oks_stddev = float(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-wandb-project-input")
    def handle_centroid_wandb_project_change(self, event: Input.Changed) -> None:
        """Handle centroid wandb project changes."""
        if self._state:
            self._state._wandb.project = event.value or "sleap-training"

    @on(Select.Changed, "#centroid-accelerator-select")
    def handle_centroid_accelerator_change(self, event: Select.Changed) -> None:
        """Handle centroid accelerator changes."""
        if self._state and event.value:
            self._state._accelerator = event.value

    @on(Select.Changed, "#centroid-devices-select")
    def handle_centroid_devices_change(self, event: Select.Changed) -> None:
        """Handle centroid devices changes."""
        if self._state and event.value:
            self._state._devices = event.value

    @on(Select.Changed, "#centroid-num-workers-select")
    def handle_centroid_num_workers_change(self, event: Select.Changed) -> None:
        """Handle centroid num workers changes."""
        if self._state and event.value:
            self._state._num_workers = int(event.value)
            self._update_centroid_cache_memory_display()

    # Legacy handler kept for compatibility (can be removed later)
    @on(Input.Changed, "#centroid-num-workers-input")
    def handle_centroid_num_workers_input_change(self, event: Input.Changed) -> None:
        """Handle centroid num workers changes."""
        if self._state and event.value:
            try:
                self._state._num_workers = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-min-steps-input")
    def handle_centroid_min_steps_change(self, event: Input.Changed) -> None:
        """Handle centroid min steps changes."""
        if self._state and event.value:
            try:
                self._state._min_steps_per_epoch = int(event.value)
            except ValueError:
                pass

    @on(Input.Changed, "#centroid-random-seed-input")
    def handle_centroid_random_seed_change(self, event: Input.Changed) -> None:
        """Handle centroid random seed changes."""
        if self._state:
            self._state._random_seed = int(event.value) if event.value else None

__init__(state=None, **kwargs)

Initialize the configure screen.

Parameters:

Name Type Description Default
state Optional[ConfigState]

ConfigState with current configuration.

None
**kwargs

Additional keyword arguments passed to parent.

{}
Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def __init__(self, state: Optional[ConfigState] = None, **kwargs):
    """Initialize the configure screen.

    Args:
        state: ConfigState with current configuration.
        **kwargs: Additional keyword arguments passed to parent.
    """
    super().__init__(**kwargs)
    self._state = state

action_goto_tab_1()

Switch to the Shared Settings tab.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def action_goto_tab_1(self) -> None:
    """Switch to the Shared Settings tab."""
    if not self._state or not self._state.is_topdown:
        return
    try:
        tabs = self.query_one("#topdown-tabs", TabbedContent)
        tabs.active = "shared-tab"
    except Exception:
        pass

action_goto_tab_2()

Switch to the Centroid Model tab.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def action_goto_tab_2(self) -> None:
    """Switch to the Centroid Model tab."""
    if not self._state or not self._state.is_topdown:
        return
    try:
        tabs = self.query_one("#topdown-tabs", TabbedContent)
        tabs.active = "centroid-tab"
    except Exception:
        pass

action_goto_tab_3()

Switch to the Instance Model tab.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def action_goto_tab_3(self) -> None:
    """Switch to the Instance Model tab."""
    if not self._state or not self._state.is_topdown:
        return
    try:
        tabs = self.query_one("#topdown-tabs", TabbedContent)
        tabs.active = "instance-tab"
    except Exception:
        pass

action_next_tab()

Switch to the next tab (for top-down models).

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def action_next_tab(self) -> None:
    """Switch to the next tab (for top-down models)."""
    if not self._state or not self._state.is_topdown:
        return
    try:
        tabs = self.query_one("#topdown-tabs", TabbedContent)
        # Get current tab index and switch to next
        tab_ids = ["shared-tab", "centroid-tab", "instance-tab"]
        current = tabs.active
        if current in tab_ids:
            idx = tab_ids.index(current)
            new_idx = (idx + 1) % len(tab_ids)
            tabs.active = tab_ids[new_idx]
    except Exception:
        pass

action_prev_tab()

Switch to the previous tab (for top-down models).

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def action_prev_tab(self) -> None:
    """Switch to the previous tab (for top-down models)."""
    if not self._state or not self._state.is_topdown:
        return
    try:
        tabs = self.query_one("#topdown-tabs", TabbedContent)
        # Get current tab index and switch to previous
        tab_ids = ["shared-tab", "centroid-tab", "instance-tab"]
        current = tabs.active
        if current in tab_ids:
            idx = tab_ids.index(current)
            new_idx = (idx - 1) % len(tab_ids)
            tabs.active = tab_ids[new_idx]
    except Exception:
        pass

compose()

Compose the screen layout.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def compose(self) -> ComposeResult:
    """Compose the screen layout."""
    with Vertical(id="config-container"):
        yield Label(
            "[bold]Step 3: Configure Training[/bold]", classes="section-title"
        )

        if self._state and self._state.is_topdown:
            yield Label(
                "[yellow]Top-down model selected - configuring 2 models[/yellow]",
                classes="hint",
            )

        with VerticalScroll(id="config-scroll"):
            # For top-down, show tabbed interface
            if self._state and self._state.is_topdown:
                yield from self._compose_topdown_config()
            else:
                yield from self._compose_standard_config()
                # Memory estimate only for non-topdown (topdown has per-model estimates)
                yield from self._compose_memory_estimate()

handle_accelerator_change(event)

Handle accelerator changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#accelerator-select")
def handle_accelerator_change(self, event: Select.Changed) -> None:
    """Handle accelerator changes."""
    if self._state and event.value:
        self._state._accelerator = event.value

handle_anchor_change(event)

Handle anchor changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#anchor-part-select")
def handle_anchor_change(self, event: Select.Changed) -> None:
    """Handle anchor changes."""
    if self._state:
        self._state._anchor_part = event.value if event.value else None

handle_backbone_change(event)

Handle backbone changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#backbone-select")
def handle_backbone_change(self, event: Select.Changed) -> None:
    """Handle backbone changes."""
    if self._state and event.value:
        self._state._backbone = event.value
        if "convnext" in event.value or "swint" in event.value:
            self._state._max_stride = 32
            try:
                select = self.query_one("#max-stride-select", Select)
                select.value = "32"
            except Exception:
                pass
        self._update_model_info_display()
        self._update_memory_display()
        self._update_imagenet_visibility()

handle_batch_change(event)

Handle batch changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#batch-size-select")
def handle_batch_change(self, event: Select.Changed) -> None:
    """Handle batch changes."""
    if self._state and event.value:
        self._state._batch_size = int(event.value)
        self._update_memory_display()

handle_brightness_change(event)

Handle brightness changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#brightness-limit-input")
def handle_brightness_change(self, event: Input.Changed) -> None:
    """Handle brightness changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.brightness_limit = float(event.value)
        except ValueError:
            pass

handle_brightness_checkbox_change(event)

Handle brightness changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#brightness-checkbox")
def handle_brightness_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle brightness changes."""
    if self._state:
        self._state._augmentation.brightness_enabled = event.value

handle_cache_path_change(event)

Handle cache path changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#cache-path-input")
def handle_cache_path_change(self, event: Input.Changed) -> None:
    """Handle cache path changes."""
    if self._state:
        self._state._cache_config.cache_img_path = event.value or ""

handle_cache_workers_change(event)

Handle cache workers changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#cache-workers-input")
def handle_cache_workers_change(self, event: Input.Changed) -> None:
    """Handle cache workers changes."""
    if self._state and event.value:
        try:
            self._state._cache_config.cache_workers = int(event.value)
        except ValueError:
            pass

handle_centroid_accelerator_change(event)

Handle centroid accelerator changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-accelerator-select")
def handle_centroid_accelerator_change(self, event: Select.Changed) -> None:
    """Handle centroid accelerator changes."""
    if self._state and event.value:
        self._state._accelerator = event.value

handle_centroid_backbone_change(event)

Handle centroid backbone changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-backbone-select")
def handle_centroid_backbone_change(self, event: Select.Changed) -> None:
    """Handle centroid backbone changes."""
    if self._state and event.value:
        self._state._backbone = event.value
        self._update_centroid_model_info_display()
        self._update_centroid_memory_display()
        self._update_imagenet_visibility()

handle_centroid_batch_change(event)

Handle centroid batch changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-batch-size-select")
def handle_centroid_batch_change(self, event: Select.Changed) -> None:
    """Handle centroid batch changes."""
    if self._state and event.value:
        self._state._batch_size = int(event.value)
        self._update_centroid_memory_display()

handle_centroid_brightness_change(event)

Handle centroid brightness changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-brightness-input")
def handle_centroid_brightness_change(self, event: Input.Changed) -> None:
    """Handle centroid brightness changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.brightness_limit = float(event.value)
        except ValueError:
            pass

handle_centroid_brightness_checkbox_change(event)

Handle centroid brightness changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-brightness-checkbox")
def handle_centroid_brightness_checkbox_change(
    self, event: Checkbox.Changed
) -> None:
    """Handle centroid brightness changes."""
    if self._state:
        self._state._augmentation.brightness_enabled = event.value

handle_centroid_channels_change(event)

Handle centroid channels changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-channels-select")
def handle_centroid_channels_change(self, event: Select.Changed) -> None:
    """Handle centroid channels changes."""
    if self._state and event.value:
        self._state._ensure_rgb = event.value == "rgb"
        self._state._ensure_grayscale = event.value == "grayscale"
        self._update_centroid_shape_display()
        self._update_centroid_memory_display()
        self._update_centroid_model_info_display()

handle_centroid_ckpt_dir_change(event)

Handle centroid ckpt dir changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-ckpt-dir-input")
def handle_centroid_ckpt_dir_change(self, event: Input.Changed) -> None:
    """Handle centroid ckpt dir changes."""
    if self._state:
        self._state._checkpoint.checkpoint_dir = event.value or ""

handle_centroid_contrast_change(event)

Handle centroid contrast changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-contrast-input")
def handle_centroid_contrast_change(self, event: Input.Changed) -> None:
    """Handle centroid contrast changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.contrast_limit = float(event.value)
        except ValueError:
            pass

handle_centroid_contrast_checkbox_change(event)

Handle centroid contrast changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-contrast-checkbox")
def handle_centroid_contrast_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid contrast changes."""
    if self._state:
        self._state._augmentation.contrast_enabled = event.value

handle_centroid_data_pipeline_change(event)

Handle centroid data pipeline changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-data-pipeline-select")
def handle_centroid_data_pipeline_change(self, event: Select.Changed) -> None:
    """Handle centroid data pipeline changes."""
    if self._state and event.value:
        self._state._data_pipeline = DataPipelineType(event.value)
        self._update_cache_memory_display()
        self._update_centroid_cache_memory_display()
        self._update_centroid_cache_options_visibility()

handle_centroid_devices_change(event)

Handle centroid devices changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-devices-select")
def handle_centroid_devices_change(self, event: Select.Changed) -> None:
    """Handle centroid devices changes."""
    if self._state and event.value:
        self._state._devices = event.value

handle_centroid_early_stopping_change(event)

Handle centroid early stopping changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-early-stopping-checkbox")
def handle_centroid_early_stopping_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid early stopping changes."""
    if self._state:
        self._state._early_stopping = event.value

handle_centroid_epochs_change(event)

Handle centroid epochs changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-max-epochs-input")
def handle_centroid_epochs_change(self, event: Input.Changed) -> None:
    """Handle centroid epochs changes."""
    if self._state and event.value:
        try:
            self._state._max_epochs = int(event.value)
        except ValueError:
            pass

handle_centroid_es_min_delta_change(event)

Handle centroid es min delta changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-es-min-delta-input")
def handle_centroid_es_min_delta_change(self, event: Input.Changed) -> None:
    """Handle centroid es min delta changes."""
    if self._state and event.value:
        try:
            self._state._early_stopping_min_delta = float(event.value)
        except ValueError:
            pass

handle_centroid_es_patience_change(event)

Handle centroid es patience changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-es-patience-input")
def handle_centroid_es_patience_change(self, event: Input.Changed) -> None:
    """Handle centroid es patience changes."""
    if self._state and event.value:
        try:
            self._state._early_stopping_patience = int(event.value)
        except ValueError:
            pass

handle_centroid_eval_change(event)

Handle centroid eval changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-eval-checkbox")
def handle_centroid_eval_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid eval changes."""
    if self._state:
        self._state._evaluation.enabled = event.value
        self._update_eval_options_visibility()

handle_centroid_eval_frequency_change(event)

Handle centroid eval frequency changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-eval-frequency-input")
def handle_centroid_eval_frequency_change(self, event: Input.Changed) -> None:
    """Handle centroid eval frequency changes."""
    if self._state and event.value:
        try:
            self._state._evaluation.frequency = int(event.value)
        except ValueError:
            pass

handle_centroid_eval_oks_change(event)

Handle centroid eval oks changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-eval-oks-input")
def handle_centroid_eval_oks_change(self, event: Input.Changed) -> None:
    """Handle centroid eval oks changes."""
    if self._state and event.value:
        try:
            self._state._evaluation.oks_stddev = float(event.value)
        except ValueError:
            pass

handle_centroid_filters_change(event)

Handle centroid filters changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-filters-input")
def handle_centroid_filters_change(self, event: Input.Changed) -> None:
    """Handle centroid filters changes."""
    if self._state and event.value:
        try:
            self._state._filters = int(event.value)
            self._update_centroid_model_info_display()
            self._update_centroid_memory_display()
        except ValueError:
            pass

handle_centroid_filters_rate_change(event)

Handle centroid filters rate changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-filters-rate-input")
def handle_centroid_filters_rate_change(self, event: Input.Changed) -> None:
    """Handle centroid filters rate changes."""
    if self._state and event.value:
        try:
            self._state._filters_rate = float(event.value)
            self._update_centroid_model_info_display()
            self._update_centroid_memory_display()
        except ValueError:
            pass

handle_centroid_imagenet_change(event)

Handle centroid imagenet changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-imagenet-checkbox")
def handle_centroid_imagenet_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid imagenet changes."""
    if self._state:
        self._state._use_imagenet_pretrained = event.value

handle_centroid_lr_change(event)

Handle centroid lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-lr-input")
def handle_centroid_lr_change(self, event: Input.Changed) -> None:
    """Handle centroid lr changes."""
    if self._state and event.value:
        try:
            self._state._learning_rate = float(event.value)
        except ValueError:
            pass

handle_centroid_lr_factor_change(event)

Handle centroid lr factor changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-lr-factor-input")
def handle_centroid_lr_factor_change(self, event: Input.Changed) -> None:
    """Handle centroid lr factor changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.factor = float(event.value)
        except ValueError:
            pass

handle_centroid_lr_patience_change(event)

Handle centroid lr patience changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-lr-patience-input")
def handle_centroid_lr_patience_change(self, event: Input.Changed) -> None:
    """Handle centroid lr patience changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.plateau_patience = int(event.value)
        except ValueError:
            pass

handle_centroid_max_height_change(event)

Handle centroid max height changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-max-height-input")
def handle_centroid_max_height_change(self, event: Input.Changed) -> None:
    """Handle centroid max height changes."""
    if self._state:
        self._state._max_height = int(event.value) if event.value else None

handle_centroid_max_stride_change(event)

Handle centroid max stride changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-max-stride-select")
def handle_centroid_max_stride_change(self, event: Select.Changed) -> None:
    """Handle centroid max stride changes."""
    if self._state and event.value:
        self._state._max_stride = int(event.value)
        self._update_centroid_model_info_display()

handle_centroid_max_width_change(event)

Handle centroid max width changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-max-width-input")
def handle_centroid_max_width_change(self, event: Input.Changed) -> None:
    """Handle centroid max width changes."""
    if self._state:
        self._state._max_width = int(event.value) if event.value else None

handle_centroid_min_steps_change(event)

Handle centroid min steps changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-min-steps-input")
def handle_centroid_min_steps_change(self, event: Input.Changed) -> None:
    """Handle centroid min steps changes."""
    if self._state and event.value:
        try:
            self._state._min_steps_per_epoch = int(event.value)
        except ValueError:
            pass

handle_centroid_num_workers_change(event)

Handle centroid num workers changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-num-workers-select")
def handle_centroid_num_workers_change(self, event: Select.Changed) -> None:
    """Handle centroid num workers changes."""
    if self._state and event.value:
        self._state._num_workers = int(event.value)
        self._update_centroid_cache_memory_display()

handle_centroid_num_workers_input_change(event)

Handle centroid num workers changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-num-workers-input")
def handle_centroid_num_workers_input_change(self, event: Input.Changed) -> None:
    """Handle centroid num workers changes."""
    if self._state and event.value:
        try:
            self._state._num_workers = int(event.value)
        except ValueError:
            pass

handle_centroid_optimizer_change(event)

Handle centroid optimizer changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-optimizer-select")
def handle_centroid_optimizer_change(self, event: Select.Changed) -> None:
    """Handle centroid optimizer changes."""
    if self._state and event.value:
        self._state._optimizer = event.value

handle_centroid_output_stride_change(event)

Handle centroid output stride changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-output-stride-select")
def handle_centroid_output_stride_change(self, event: Select.Changed) -> None:
    """Handle centroid output stride changes."""
    if self._state and event.value:
        self._state._output_stride = int(event.value)
        self._update_centroid_shape_display()
        self._update_centroid_model_info_display()

handle_centroid_pretrained_backbone_change(event)

Handle centroid pretrained backbone changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-pretrained-backbone-input")
def handle_centroid_pretrained_backbone_change(self, event: Input.Changed) -> None:
    """Handle centroid pretrained backbone changes."""
    if self._state:
        self._state._pretrained_backbone = event.value or ""

handle_centroid_pretrained_head_change(event)

Handle centroid pretrained head changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-pretrained-head-input")
def handle_centroid_pretrained_head_change(self, event: Input.Changed) -> None:
    """Handle centroid pretrained head changes."""
    if self._state:
        self._state._pretrained_head = event.value or ""

handle_centroid_random_seed_change(event)

Handle centroid random seed changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-random-seed-input")
def handle_centroid_random_seed_change(self, event: Input.Changed) -> None:
    """Handle centroid random seed changes."""
    if self._state:
        self._state._random_seed = int(event.value) if event.value else None

handle_centroid_resume_ckpt_change(event)

Handle centroid resume ckpt changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-resume-ckpt-input")
def handle_centroid_resume_ckpt_change(self, event: Input.Changed) -> None:
    """Handle centroid resume ckpt changes."""
    if self._state:
        self._state._checkpoint.resume_from = event.value or ""

handle_centroid_rotation_change(event)

Handle centroid rotation changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-rotation-input")
def handle_centroid_rotation_change(self, event: Input.Changed) -> None:
    """Handle centroid rotation changes."""
    if self._state and event.value:
        try:
            val = float(event.value)
            self._state._augmentation.rotation_max = val
            self._state._augmentation.rotation_min = -val
        except ValueError:
            pass

handle_centroid_rotation_checkbox_change(event)

Handle centroid rotation changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-rotation-checkbox")
def handle_centroid_rotation_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid rotation changes."""
    if self._state:
        self._state._augmentation.rotation_enabled = event.value

handle_centroid_run_name_change(event)

Handle centroid run name changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-run-name-input")
def handle_centroid_run_name_change(self, event: Input.Changed) -> None:
    """Handle centroid run name changes."""
    if self._state:
        self._state._checkpoint.run_name = event.value or ""

handle_centroid_save_ckpt_change(event)

Handle centroid save ckpt changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-save-ckpt-checkbox")
def handle_centroid_save_ckpt_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid save ckpt changes."""
    if self._state:
        self._state._checkpoint.enabled = event.value

handle_centroid_save_top_k_change(event)

Handle centroid save top k changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-save-top-k-input")
def handle_centroid_save_top_k_change(self, event: Input.Changed) -> None:
    """Handle centroid save top k changes."""
    if self._state and event.value:
        try:
            self._state._checkpoint.save_top_k = int(event.value)
        except ValueError:
            pass

handle_centroid_save_viz_change(event)

Handle centroid save viz changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-save-viz-checkbox")
def handle_centroid_save_viz_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid save viz changes."""
    if self._state:
        self._state._visualize_preds = event.value
        self._update_viz_options_visibility()

handle_centroid_scale_change(event)

Handle centroid scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-scale-input")
def handle_centroid_scale_change(self, event: Input.Changed) -> None:
    """Handle centroid scale changes."""
    if self._state and event.value:
        try:
            self._state._input_scale = float(event.value)
            self._update_centroid_shape_display()
            self._update_centroid_model_info_display()
            self._update_centroid_memory_display()
        except ValueError:
            pass

handle_centroid_scale_checkbox_change(event)

Handle centroid scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-scale-checkbox")
def handle_centroid_scale_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid scale changes."""
    if self._state:
        self._state._augmentation.scale_enabled = event.value

handle_centroid_scale_max_change(event)

Handle centroid scale max changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-scale-max-input")
def handle_centroid_scale_max_change(self, event: Input.Changed) -> None:
    """Handle centroid scale max changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.scale_max = float(event.value)
        except ValueError:
            pass

handle_centroid_scale_min_change(event)

Handle centroid scale min changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-scale-min-input")
def handle_centroid_scale_min_change(self, event: Input.Changed) -> None:
    """Handle centroid scale min changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.scale_min = float(event.value)
        except ValueError:
            pass

handle_centroid_scheduler_change(event)

Handle centroid scheduler changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#centroid-scheduler-select")
def handle_centroid_scheduler_change(self, event: Select.Changed) -> None:
    """Handle centroid scheduler changes."""
    if self._state and event.value:
        self._state._scheduler.type = SchedulerType(event.value)

handle_centroid_sigma_change(event)

Handle centroid sigma changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-sigma-input")
def handle_centroid_sigma_change(self, event: Input.Changed) -> None:
    """Handle centroid sigma changes."""
    if self._state and event.value:
        try:
            self._state._sigma = float(event.value)
            self._update_centroid_model_info_display()
        except ValueError:
            pass

handle_centroid_translate_change(event)

Handle centroid translate changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-translate-input")
def handle_centroid_translate_change(self, event: Input.Changed) -> None:
    """Handle centroid translate changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.translate = float(event.value)
        except ValueError:
            pass

handle_centroid_translate_checkbox_change(event)

Handle centroid translate changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-translate-checkbox")
def handle_centroid_translate_checkbox_change(
    self, event: Checkbox.Changed
) -> None:
    """Handle centroid translate changes."""
    if self._state:
        self._state._augmentation.translate_enabled = event.value

handle_centroid_val_fraction_change(event)

Handle centroid val fraction changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-val-fraction-input")
def handle_centroid_val_fraction_change(self, event: Input.Changed) -> None:
    """Handle centroid val fraction changes."""
    if self._state and event.value:
        try:
            self._state._validation_fraction = float(event.value)
        except ValueError:
            pass

handle_centroid_viz_keep_folder_change(event)

Handle centroid viz keep folder changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-viz-keep-folder-checkbox")
def handle_centroid_viz_keep_folder_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid viz keep folder changes."""
    if self._state:
        self._state._keep_viz = event.value

handle_centroid_wandb_change(event)

Handle centroid wandb changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#centroid-wandb-checkbox")
def handle_centroid_wandb_change(self, event: Checkbox.Changed) -> None:
    """Handle centroid wandb changes."""
    if self._state:
        self._state._wandb.enabled = event.value
        self._update_wandb_options_visibility()

handle_centroid_wandb_project_change(event)

Handle centroid wandb project changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#centroid-wandb-project-input")
def handle_centroid_wandb_project_change(self, event: Input.Changed) -> None:
    """Handle centroid wandb project changes."""
    if self._state:
        self._state._wandb.project = event.value or "sleap-training"

handle_channels_change(event)

Handle channels changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#channels-select")
def handle_channels_change(self, event: Select.Changed) -> None:
    """Handle channels changes."""
    if self._state and event.value:
        self._state._ensure_rgb = event.value == "rgb"
        self._state._ensure_grayscale = event.value == "grayscale"
        self._update_shape_display()
        self._update_memory_display()
        self._update_model_info_display()

handle_ckpt_dir_change(event)

Handle ckpt dir changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#ckpt-dir-input")
def handle_ckpt_dir_change(self, event: Input.Changed) -> None:
    """Handle ckpt dir changes."""
    if self._state:
        self._state._checkpoint.checkpoint_dir = event.value or ""

handle_class_loss_weight_change(event)

Handle class loss weight changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#class-loss-weight-input")
def handle_class_loss_weight_change(self, event: Input.Changed) -> None:
    """Handle class loss weight changes."""
    if self._state and event.value:
        try:
            self._state._class_vector_config.loss_weight = float(event.value)
        except ValueError:
            pass

handle_contrast_change(event)

Handle contrast changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#contrast-limit-input")
def handle_contrast_change(self, event: Input.Changed) -> None:
    """Handle contrast changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.contrast_limit = float(event.value)
        except ValueError:
            pass

handle_contrast_checkbox_change(event)

Handle contrast changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#contrast-checkbox")
def handle_contrast_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle contrast changes."""
    if self._state:
        self._state._augmentation.contrast_enabled = event.value

handle_crop_size_change(event)

Handle crop size changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#crop-size-input")
def handle_crop_size_change(self, event: Input.Changed) -> None:
    """Handle crop size changes."""
    if self._state and event.value:
        try:
            self._state._crop_size = int(event.value)
        except ValueError:
            pass

handle_data_pipeline_change(event)

Handle data pipeline changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#data-pipeline-select")
def handle_data_pipeline_change(self, event: Select.Changed) -> None:
    """Handle data pipeline changes."""
    if self._state and event.value:
        self._state._data_pipeline = DataPipelineType(event.value)
        self._update_memory_display()
        self._update_cache_memory_display()
        self._update_cache_options_visibility()

handle_delete_cache_change(event)

Handle delete cache changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#delete-cache-checkbox")
def handle_delete_cache_change(self, event: Checkbox.Changed) -> None:
    """Handle delete cache changes."""
    if self._state:
        self._state._cache_config.delete_cache_after_training = event.value

handle_devices_change(event)

Handle devices changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#devices-select")
def handle_devices_change(self, event: Select.Changed) -> None:
    """Handle devices changes."""
    if self._state and event.value:
        self._state._devices = event.value

handle_early_stopping_change(event)

Handle early stopping changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#early-stopping-checkbox")
def handle_early_stopping_change(self, event: Checkbox.Changed) -> None:
    """Handle early stopping changes."""
    if self._state:
        self._state._early_stopping = event.value

handle_epochs_change(event)

Handle epochs changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#max-epochs-input")
def handle_epochs_change(self, event: Input.Changed) -> None:
    """Handle epochs changes."""
    if self._state and event.value:
        try:
            self._state._max_epochs = int(event.value)
        except ValueError:
            pass

handle_es_patience_change(event)

Handle es patience changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#es-patience-input")
def handle_es_patience_change(self, event: Input.Changed) -> None:
    """Handle es patience changes."""
    if self._state and event.value:
        try:
            self._state._early_stopping_patience = int(event.value)
        except ValueError:
            pass

handle_eval_checkbox_change(event)

Handle eval changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#eval-checkbox")
def handle_eval_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle eval changes."""
    if self._state:
        self._state._evaluation.enabled = event.value
        self._update_eval_options_visibility()

handle_eval_frequency_change(event)

Handle eval frequency changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#eval-frequency-input")
def handle_eval_frequency_change(self, event: Input.Changed) -> None:
    """Handle eval frequency changes."""
    if self._state and event.value:
        try:
            self._state._evaluation.frequency = int(event.value)
        except ValueError:
            pass

handle_eval_oks_change(event)

Handle eval oks changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#eval-oks-input")
def handle_eval_oks_change(self, event: Input.Changed) -> None:
    """Handle eval oks changes."""
    if self._state and event.value:
        try:
            self._state._evaluation.oks_stddev = float(event.value)
        except ValueError:
            pass

handle_evaluation_change(event)

Handle evaluation changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#evaluation-checkbox")
def handle_evaluation_change(self, event: Checkbox.Changed) -> None:
    """Handle evaluation changes."""
    if self._state:
        self._state._evaluation.enabled = event.value
        self._update_eval_options_visibility()

handle_fc_layers_change(event)

Handle fc layers changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#fc-layers-select")
def handle_fc_layers_change(self, event: Select.Changed) -> None:
    """Handle fc layers changes."""
    if self._state and event.value:
        self._state._class_vector_config.num_fc_layers = int(event.value)

handle_fc_units_change(event)

Handle fc units changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#fc-units-input")
def handle_fc_units_change(self, event: Input.Changed) -> None:
    """Handle fc units changes."""
    if self._state and event.value:
        try:
            self._state._class_vector_config.num_fc_units = int(event.value)
        except ValueError:
            pass

handle_filters_change(event)

Handle filters changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#filters-input")
def handle_filters_change(self, event: Input.Changed) -> None:
    """Handle filters changes."""
    if self._state and event.value:
        try:
            self._state._filters = int(event.value)
            self._update_model_info_display()
            self._update_memory_display()
        except ValueError:
            pass

handle_filters_rate_change(event)

Handle filters rate changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#filters-rate-input")
def handle_filters_rate_change(self, event: Input.Changed) -> None:
    """Handle filters rate changes."""
    if self._state and event.value:
        try:
            self._state._filters_rate = float(event.value)
            self._update_model_info_display()
            self._update_memory_display()
        except ValueError:
            pass

handle_instance_accelerator_change(event)

Handle instance accelerator changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-accelerator-select")
def handle_instance_accelerator_change(self, event: Select.Changed) -> None:
    """Handle instance accelerator changes."""
    if self._state and event.value:
        self._state._accelerator = event.value

handle_instance_backbone_change(event)

Handle instance backbone changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-backbone-select")
def handle_instance_backbone_change(self, event: Select.Changed) -> None:
    """Handle instance backbone changes."""
    if self._state and event.value:
        self._state._ci_backbone = event.value

handle_instance_batch_change(event)

Handle instance batch changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-batch-size-select")
def handle_instance_batch_change(self, event: Select.Changed) -> None:
    """Handle instance batch changes."""
    if self._state and event.value:
        self._state._ci_batch_size = int(event.value)

handle_instance_brightness_change(event)

Handle instance brightness changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-brightness-input")
def handle_instance_brightness_change(self, event: Input.Changed) -> None:
    """Handle instance brightness changes."""
    if self._state and event.value:
        try:
            self._state._ci_augmentation.brightness_limit = float(event.value)
        except ValueError:
            pass

handle_instance_brightness_checkbox_change(event)

Handle instance brightness changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-brightness-checkbox")
def handle_instance_brightness_checkbox_change(
    self, event: Checkbox.Changed
) -> None:
    """Handle instance brightness changes."""
    if self._state:
        self._state._ci_augmentation.brightness_enabled = event.value

handle_instance_cache_path_change(event)

Handle instance cache path changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-cache-path-input")
def handle_instance_cache_path_change(self, event: Input.Changed) -> None:
    """Handle instance cache path changes."""
    if self._state:
        self._state._cache_config.cache_img_path = event.value or ""

handle_instance_cache_workers_change(event)

Handle instance cache workers changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-cache-workers-input")
def handle_instance_cache_workers_change(self, event: Input.Changed) -> None:
    """Handle instance cache workers changes."""
    if self._state and event.value:
        try:
            self._state._cache_config.cache_workers = int(event.value)
        except ValueError:
            pass

handle_instance_channels_change(event)

Handle instance channels changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-channels-select")
def handle_instance_channels_change(self, event: Select.Changed) -> None:
    """Handle instance channels changes."""
    if self._state and event.value:
        self._state._ensure_rgb = event.value == "rgb"
        self._state._ensure_grayscale = event.value == "grayscale"

handle_instance_ckpt_dir_change(event)

Handle instance ckpt dir changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-ckpt-dir-input")
def handle_instance_ckpt_dir_change(self, event: Input.Changed) -> None:
    """Handle instance ckpt dir changes."""
    if self._state:
        self._state._ci_checkpoint_dir = event.value or ""

handle_instance_contrast_change(event)

Handle instance contrast changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-contrast-input")
def handle_instance_contrast_change(self, event: Input.Changed) -> None:
    """Handle instance contrast changes."""
    if self._state and event.value:
        try:
            self._state._ci_augmentation.contrast_limit = float(event.value)
        except ValueError:
            pass

handle_instance_contrast_checkbox_change(event)

Handle instance contrast changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-contrast-checkbox")
def handle_instance_contrast_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle instance contrast changes."""
    if self._state:
        self._state._ci_augmentation.contrast_enabled = event.value

handle_instance_data_pipeline_change(event)

Handle instance data pipeline changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-data-pipeline-select")
def handle_instance_data_pipeline_change(self, event: Select.Changed) -> None:
    """Handle instance data pipeline changes."""
    if self._state and event.value:
        from sleap_nn.config_generator.tui.state import DataPipelineType

        self._state._data_pipeline = DataPipelineType(event.value)
        self._update_instance_cache_memory_display()
        self._update_instance_cache_options_visibility()

handle_instance_delete_cache_change(event)

Handle instance delete cache changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-delete-cache-checkbox")
def handle_instance_delete_cache_change(self, event: Checkbox.Changed) -> None:
    """Handle instance delete cache changes."""
    if self._state:
        self._state._cache_config.delete_cache_after_training = event.value

handle_instance_devices_change(event)

Handle instance devices changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-devices-select")
def handle_instance_devices_change(self, event: Select.Changed) -> None:
    """Handle instance devices changes."""
    if self._state and event.value:
        self._state._devices = event.value

handle_instance_early_stopping_change(event)

Handle instance early stopping changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-early-stopping-checkbox")
def handle_instance_early_stopping_change(self, event: Checkbox.Changed) -> None:
    """Handle instance early stopping changes."""
    if self._state:
        self._state._ci_early_stopping = event.value

handle_instance_epochs_change(event)

Handle instance epochs changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-max-epochs-input")
def handle_instance_epochs_change(self, event: Input.Changed) -> None:
    """Handle instance epochs changes."""
    if self._state and event.value:
        try:
            self._state._ci_max_epochs = int(event.value)
        except ValueError:
            pass

handle_instance_es_min_delta_change(event)

Handle instance es min delta changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-es-min-delta-input")
def handle_instance_es_min_delta_change(self, event: Input.Changed) -> None:
    """Handle instance es min delta changes."""
    if self._state and event.value:
        try:
            self._state._ci_early_stopping_min_delta = float(event.value)
        except ValueError:
            pass

handle_instance_es_patience_change(event)

Handle instance es patience changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-es-patience-input")
def handle_instance_es_patience_change(self, event: Input.Changed) -> None:
    """Handle instance es patience changes."""
    if self._state and event.value:
        try:
            self._state._ci_early_stopping_patience = int(event.value)
        except ValueError:
            pass

handle_instance_eval_change(event)

Handle instance eval changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-eval-checkbox")
def handle_instance_eval_change(self, event: Checkbox.Changed) -> None:
    """Handle instance eval changes."""
    if self._state:
        self._state._evaluation.enabled = event.value
        self._update_eval_options_visibility()

handle_instance_eval_frequency_change(event)

Handle instance eval frequency changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-eval-frequency-input")
def handle_instance_eval_frequency_change(self, event: Input.Changed) -> None:
    """Handle instance eval frequency changes."""
    if self._state and event.value:
        try:
            self._state._evaluation.frequency = int(event.value)
        except ValueError:
            pass

handle_instance_eval_oks_change(event)

Handle instance eval oks changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-eval-oks-input")
def handle_instance_eval_oks_change(self, event: Input.Changed) -> None:
    """Handle instance eval oks changes."""
    if self._state and event.value:
        try:
            self._state._evaluation.oks_stddev = float(event.value)
        except ValueError:
            pass

handle_instance_filters_change(event)

Handle instance filters changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-filters-input")
def handle_instance_filters_change(self, event: Input.Changed) -> None:
    """Handle instance filters changes."""
    if self._state and event.value:
        try:
            self._state._ci_filters = int(event.value)
        except ValueError:
            pass

handle_instance_filters_rate_change(event)

Handle instance filters rate changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-filters-rate-input")
def handle_instance_filters_rate_change(self, event: Input.Changed) -> None:
    """Handle instance filters rate changes."""
    if self._state and event.value:
        try:
            self._state._ci_filters_rate = float(event.value)
        except ValueError:
            pass

handle_instance_imagenet_change(event)

Handle instance imagenet changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-imagenet-checkbox")
def handle_instance_imagenet_change(self, event: Checkbox.Changed) -> None:
    """Handle instance imagenet changes."""
    if self._state:
        self._state._use_imagenet_pretrained = event.value

handle_instance_lr_change(event)

Handle instance lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-lr-input")
def handle_instance_lr_change(self, event: Input.Changed) -> None:
    """Handle instance lr changes."""
    if self._state and event.value:
        try:
            self._state._ci_learning_rate = float(event.value)
        except ValueError:
            pass

handle_instance_lr_factor_change(event)

Handle instance lr factor changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-lr-factor-input")
def handle_instance_lr_factor_change(self, event: Input.Changed) -> None:
    """Handle instance lr factor changes."""
    if self._state and event.value:
        try:
            self._state._ci_scheduler.factor = float(event.value)
        except ValueError:
            pass

handle_instance_lr_patience_change(event)

Handle instance lr patience changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-lr-patience-input")
def handle_instance_lr_patience_change(self, event: Input.Changed) -> None:
    """Handle instance lr patience changes."""
    if self._state and event.value:
        try:
            self._state._ci_scheduler.plateau_patience = int(event.value)
        except ValueError:
            pass

handle_instance_lr_select_change(event)

Handle instance lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-lr-select")
def handle_instance_lr_select_change(self, event: Select.Changed) -> None:
    """Handle instance lr changes."""
    if self._state and event.value:
        self._state._ci_learning_rate = float(event.value)

handle_instance_max_stride_change(event)

Handle instance max stride changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-max-stride-select")
def handle_instance_max_stride_change(self, event: Select.Changed) -> None:
    """Handle instance max stride changes."""
    if self._state and event.value:
        self._state._ci_max_stride = int(event.value)

handle_instance_min_steps_change(event)

Handle instance min steps changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-min-steps-input")
def handle_instance_min_steps_change(self, event: Input.Changed) -> None:
    """Handle instance min steps changes."""
    if self._state and event.value:
        try:
            self._state._min_steps_per_epoch = int(event.value)
        except ValueError:
            pass

handle_instance_num_workers_select_change(event)

Handle instance num workers changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-num-workers-select")
def handle_instance_num_workers_select_change(self, event: Select.Changed) -> None:
    """Handle instance num workers changes."""
    if self._state and event.value:
        self._state._num_workers = int(event.value)
        self._update_instance_cache_memory_display()

handle_instance_ohkm_change(event)

Handle instance ohkm changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-ohkm-checkbox")
def handle_instance_ohkm_change(self, event: Checkbox.Changed) -> None:
    """Handle instance ohkm changes."""
    if self._state:
        self._state._ohkm.enabled = event.value

handle_instance_ohkm_max_change(event)

Handle instance ohkm max changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-ohkm-max-input")
def handle_instance_ohkm_max_change(self, event: Input.Changed) -> None:
    """Handle instance ohkm max changes."""
    if self._state:
        self._state._ohkm.max_hard_keypoints = (
            int(event.value) if event.value else None
        )

handle_instance_ohkm_min_change(event)

Handle instance ohkm min changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-ohkm-min-input")
def handle_instance_ohkm_min_change(self, event: Input.Changed) -> None:
    """Handle instance ohkm min changes."""
    if self._state and event.value:
        try:
            self._state._ohkm.min_hard_keypoints = int(event.value)
        except ValueError:
            pass

handle_instance_ohkm_ratio_change(event)

Handle instance ohkm ratio changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-ohkm-ratio-input")
def handle_instance_ohkm_ratio_change(self, event: Input.Changed) -> None:
    """Handle instance ohkm ratio changes."""
    if self._state and event.value:
        try:
            self._state._ohkm.hard_to_easy_ratio = float(event.value)
        except ValueError:
            pass

handle_instance_ohkm_scale_change(event)

Handle instance ohkm scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-ohkm-scale-input")
def handle_instance_ohkm_scale_change(self, event: Input.Changed) -> None:
    """Handle instance ohkm scale changes."""
    if self._state and event.value:
        try:
            self._state._ohkm.loss_scale = float(event.value)
        except ValueError:
            pass

handle_instance_optimizer_change(event)

Handle instance optimizer changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-optimizer-select")
def handle_instance_optimizer_change(self, event: Select.Changed) -> None:
    """Handle instance optimizer changes."""
    if self._state and event.value:
        self._state._ci_optimizer = event.value

handle_instance_output_stride_change(event)

Handle instance output stride changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-output-stride-select")
def handle_instance_output_stride_change(self, event: Select.Changed) -> None:
    """Handle instance output stride changes."""
    if self._state and event.value:
        self._state._ci_output_stride = int(event.value)

handle_instance_parallel_caching_change(event)

Handle instance parallel caching changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-parallel-caching-checkbox")
def handle_instance_parallel_caching_change(self, event: Checkbox.Changed) -> None:
    """Handle instance parallel caching changes."""
    if self._state:
        self._state._cache_config.parallel_caching = event.value

handle_instance_pretrained_backbone_change(event)

Handle instance pretrained backbone changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-pretrained-backbone-input")
def handle_instance_pretrained_backbone_change(self, event: Input.Changed) -> None:
    """Handle instance pretrained backbone changes."""
    if self._state:
        self._state._ci_pretrained_backbone = event.value or ""

handle_instance_pretrained_head_change(event)

Handle instance pretrained head changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-pretrained-head-input")
def handle_instance_pretrained_head_change(self, event: Input.Changed) -> None:
    """Handle instance pretrained head changes."""
    if self._state:
        self._state._ci_pretrained_head = event.value or ""

handle_instance_random_seed_change(event)

Handle instance random seed changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-random-seed-input")
def handle_instance_random_seed_change(self, event: Input.Changed) -> None:
    """Handle instance random seed changes."""
    if self._state:
        self._state._random_seed = int(event.value) if event.value else None

handle_instance_rotation_change(event)

Handle instance rotation changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-rotation-input")
def handle_instance_rotation_change(self, event: Input.Changed) -> None:
    """Handle instance rotation changes."""
    if self._state and event.value:
        try:
            val = float(event.value)
            self._state._ci_augmentation.rotation_max = val
            self._state._ci_augmentation.rotation_min = -val
        except ValueError:
            pass

handle_instance_rotation_checkbox_change(event)

Handle instance rotation changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-rotation-checkbox")
def handle_instance_rotation_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle instance rotation changes."""
    if self._state:
        self._state._ci_augmentation.rotation_enabled = event.value

handle_instance_run_name_change(event)

Handle instance run name changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-run-name-input")
def handle_instance_run_name_change(self, event: Input.Changed) -> None:
    """Handle instance run name changes."""
    if self._state:
        self._state._ci_run_name = event.value or ""

handle_instance_save_ckpt_change(event)

Handle instance save ckpt changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-save-ckpt-checkbox")
def handle_instance_save_ckpt_change(self, event: Checkbox.Changed) -> None:
    """Handle instance save ckpt changes."""
    if self._state:
        self._state._checkpoint.enabled = event.value

handle_instance_save_last_change(event)

Handle instance save last changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-save-last-checkbox")
def handle_instance_save_last_change(self, event: Checkbox.Changed) -> None:
    """Handle instance save last changes."""
    if self._state:
        self._state._checkpoint.save_last = event.value

handle_instance_save_top_k_change(event)

Handle instance save top k changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-save-top-k-input")
def handle_instance_save_top_k_change(self, event: Input.Changed) -> None:
    """Handle instance save top k changes."""
    if self._state and event.value:
        try:
            self._state._checkpoint.save_top_k = int(event.value)
        except ValueError:
            pass

handle_instance_save_viz_change(event)

Handle instance save viz changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-save-viz-checkbox")
def handle_instance_save_viz_change(self, event: Checkbox.Changed) -> None:
    """Handle instance save viz changes."""
    if self._state:
        self._state._visualize_preds = event.value
        self._update_viz_options_visibility()

handle_instance_scale_change(event)

Handle instance scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-scale-input")
def handle_instance_scale_change(self, event: Input.Changed) -> None:
    """Handle instance scale changes."""
    if self._state and event.value:
        try:
            self._state._ci_input_scale = float(event.value)
        except ValueError:
            pass

handle_instance_scale_checkbox_change(event)

Handle instance scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-scale-checkbox")
def handle_instance_scale_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle instance scale changes."""
    if self._state:
        self._state._ci_augmentation.scale_enabled = event.value

handle_instance_scale_max_change(event)

Handle instance scale max changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-scale-max-input")
def handle_instance_scale_max_change(self, event: Input.Changed) -> None:
    """Handle instance scale max changes."""
    if self._state and event.value:
        try:
            self._state._ci_augmentation.scale_max = float(event.value)
        except ValueError:
            pass

handle_instance_scale_min_change(event)

Handle instance scale min changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-scale-min-input")
def handle_instance_scale_min_change(self, event: Input.Changed) -> None:
    """Handle instance scale min changes."""
    if self._state and event.value:
        try:
            self._state._ci_augmentation.scale_min = float(event.value)
        except ValueError:
            pass

handle_instance_scheduler_change(event)

Handle instance scheduler changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#instance-scheduler-select")
def handle_instance_scheduler_change(self, event: Select.Changed) -> None:
    """Handle instance scheduler changes."""
    if self._state and event.value:
        from sleap_nn.config_generator.tui.state import SchedulerType

        self._state._ci_scheduler.type = SchedulerType(event.value)

handle_instance_sigma_change(event)

Handle instance sigma changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-sigma-input")
def handle_instance_sigma_change(self, event: Input.Changed) -> None:
    """Handle instance sigma changes."""
    if self._state and event.value:
        try:
            self._state._ci_sigma = float(event.value)
        except ValueError:
            pass

handle_instance_use_existing_change(event)

Handle instance use existing changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-use-existing-checkbox")
def handle_instance_use_existing_change(self, event: Checkbox.Changed) -> None:
    """Handle instance use existing changes."""
    if self._state:
        self._state._cache_config.use_existing_imgs = event.value

handle_instance_viz_keep_folder_change(event)

Handle instance viz keep folder changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-viz-keep-folder-checkbox")
def handle_instance_viz_keep_folder_change(self, event: Checkbox.Changed) -> None:
    """Handle instance viz keep folder changes."""
    if self._state:
        self._state._keep_viz = event.value

handle_instance_wandb_change(event)

Handle instance wandb changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#instance-wandb-checkbox")
def handle_instance_wandb_change(self, event: Checkbox.Changed) -> None:
    """Handle instance wandb changes."""
    if self._state:
        self._state._wandb.enabled = event.value
        self._update_wandb_options_visibility()

handle_instance_wandb_entity_change(event)

Handle instance wandb entity changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-wandb-entity-input")
def handle_instance_wandb_entity_change(self, event: Input.Changed) -> None:
    """Handle instance wandb entity changes."""
    if self._state:
        self._state._wandb.entity = event.value or ""

handle_instance_wandb_project_change(event)

Handle instance wandb project changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#instance-wandb-project-input")
def handle_instance_wandb_project_change(self, event: Input.Changed) -> None:
    """Handle instance wandb project changes."""
    if self._state:
        self._state._wandb.project = event.value or "sleap-training"

handle_keep_viz_change(event)

Handle keep viz changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#keep-viz-checkbox")
def handle_keep_viz_change(self, event: Checkbox.Changed) -> None:
    """Handle keep viz changes."""
    if self._state:
        self._state._keep_viz = event.value

handle_lr_change(event)

Handle lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#lr-input")
def handle_lr_change(self, event: Input.Changed) -> None:
    """Handle lr changes."""
    if self._state and event.value:
        try:
            self._state._learning_rate = float(event.value)
        except ValueError:
            pass

handle_max_height_change(event)

Handle max height changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#max-height-input")
def handle_max_height_change(self, event: Input.Changed) -> None:
    """Handle max height changes."""
    if self._state:
        self._state._max_height = int(event.value) if event.value else None
        self._update_shape_display()
        self._update_memory_display()

handle_max_width_change(event)

Handle max width changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#max-width-input")
def handle_max_width_change(self, event: Input.Changed) -> None:
    """Handle max width changes."""
    if self._state:
        self._state._max_width = int(event.value) if event.value else None
        self._update_shape_display()
        self._update_memory_display()

handle_min_crop_size_change(event)

Handle min crop size changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#min-crop-size-input")
def handle_min_crop_size_change(self, event: Input.Changed) -> None:
    """Handle min crop size changes."""
    if self._state and event.value:
        try:
            self._state._ci_min_crop_size = int(event.value)
        except ValueError:
            pass

handle_min_steps_change(event)

Handle min steps changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#min-steps-input")
def handle_min_steps_change(self, event: Input.Changed) -> None:
    """Handle min steps changes."""
    if self._state and event.value:
        try:
            self._state._min_steps_per_epoch = int(event.value)
        except ValueError:
            pass

handle_num_workers_select_change(event)

Handle num workers changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#num-workers-select")
def handle_num_workers_select_change(self, event: Select.Changed) -> None:
    """Handle num workers changes."""
    if self._state and event.value:
        self._state._num_workers = int(event.value)
        self._update_cache_memory_display()

handle_ohkm_change(event)

Handle ohkm changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#ohkm-checkbox")
def handle_ohkm_change(self, event: Checkbox.Changed) -> None:
    """Handle ohkm changes."""
    if self._state:
        self._state._ohkm.enabled = event.value

handle_ohkm_ratio_change(event)

Handle ohkm ratio changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#ohkm-ratio-input")
def handle_ohkm_ratio_change(self, event: Input.Changed) -> None:
    """Handle ohkm ratio changes."""
    if self._state and event.value:
        try:
            self._state._ohkm.hard_to_easy_ratio = float(event.value)
        except ValueError:
            pass

handle_ohkm_scale_change(event)

Handle ohkm scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#ohkm-scale-input")
def handle_ohkm_scale_change(self, event: Input.Changed) -> None:
    """Handle ohkm scale changes."""
    if self._state and event.value:
        try:
            self._state._ohkm.loss_scale = float(event.value)
        except ValueError:
            pass

handle_oks_stddev_change(event)

Handle oks stddev changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#oks-stddev-input")
def handle_oks_stddev_change(self, event: Input.Changed) -> None:
    """Handle oks stddev changes."""
    if self._state and event.value:
        try:
            self._state._evaluation.oks_stddev = float(event.value)
        except ValueError:
            pass

handle_optimizer_change(event)

Handle optimizer changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#optimizer-select")
def handle_optimizer_change(self, event: Select.Changed) -> None:
    """Handle optimizer changes."""
    if self._state and event.value:
        self._state._optimizer = event.value

handle_output_stride_change(event)

Handle output stride changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#output-stride-select")
def handle_output_stride_change(self, event: Select.Changed) -> None:
    """Handle output stride changes."""
    if self._state and event.value:
        self._state._output_stride = int(event.value)
        self._update_shape_display()
        self._update_memory_display()
        self._update_model_info_display()  # Update decoder blocks and Gaussian radius

handle_paf_loss_weight_change(event)

Handle paf loss weight changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#paf-loss-weight-input")
def handle_paf_loss_weight_change(self, event: Input.Changed) -> None:
    """Handle paf loss weight changes."""
    if self._state and event.value:
        try:
            self._state._paf_config.loss_weight = float(event.value)
        except ValueError:
            pass

handle_paf_output_stride_change(event)

Handle paf output stride changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#paf-output-stride-select")
def handle_paf_output_stride_change(self, event: Select.Changed) -> None:
    """Handle paf output stride changes."""
    if self._state and event.value:
        self._state._paf_config.output_stride = int(event.value)

handle_paf_sigma_change(event)

Handle paf sigma changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#paf-sigma-input")
def handle_paf_sigma_change(self, event: Input.Changed) -> None:
    """Handle paf sigma changes."""
    if self._state and event.value:
        try:
            self._state._paf_config.sigma = float(event.value)
        except ValueError:
            pass

handle_parallel_caching_change(event)

Handle parallel caching changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#parallel-caching-checkbox")
def handle_parallel_caching_change(self, event: Checkbox.Changed) -> None:
    """Handle parallel caching changes."""
    if self._state:
        self._state._cache_config.parallel_caching = event.value

handle_pretrained_backbone_change(event)

Handle pretrained backbone changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#pretrained-backbone-input")
def handle_pretrained_backbone_change(self, event: Input.Changed) -> None:
    """Handle pretrained backbone changes."""
    if self._state:
        self._state._pretrained_backbone = event.value or ""

handle_pretrained_head_change(event)

Handle pretrained head changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#pretrained-head-input")
def handle_pretrained_head_change(self, event: Input.Changed) -> None:
    """Handle pretrained head changes."""
    if self._state:
        self._state._pretrained_head = event.value or ""

handle_progress_bar_change(event)

Handle progress bar changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#progress-bar-checkbox")
def handle_progress_bar_change(self, event: Checkbox.Changed) -> None:
    """Handle progress bar changes."""
    if self._state:
        self._state._enable_progress_bar = event.value

handle_random_seed_change(event)

Handle random seed changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#random-seed-input")
def handle_random_seed_change(self, event: Input.Changed) -> None:
    """Handle random seed changes."""
    if self._state:
        self._state._random_seed = int(event.value) if event.value else None

handle_resume_ckpt_change(event)

Handle resume ckpt changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#resume-ckpt-input")
def handle_resume_ckpt_change(self, event: Input.Changed) -> None:
    """Handle resume ckpt changes."""
    if self._state:
        self._state._checkpoint.resume_from = event.value or ""

handle_rotation_change(event)

Handle rotation changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#rotation-input")
def handle_rotation_change(self, event: Input.Changed) -> None:
    """Handle rotation changes."""
    if self._state and event.value:
        try:
            val = float(event.value)
            self._state._augmentation.rotation_min = -abs(val)
            self._state._augmentation.rotation_max = abs(val)
        except ValueError:
            pass

handle_rotation_checkbox_change(event)

Handle rotation changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#rotation-checkbox")
def handle_rotation_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle rotation changes."""
    if self._state:
        self._state._augmentation.rotation_enabled = event.value

handle_run_name_change(event)

Handle run name changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#run-name-input")
def handle_run_name_change(self, event: Input.Changed) -> None:
    """Handle run name changes."""
    if self._state:
        self._state._checkpoint.run_name = event.value or ""

handle_save_last_change(event)

Handle save last changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#save-last-checkbox")
def handle_save_last_change(self, event: Checkbox.Changed) -> None:
    """Handle save last changes."""
    if self._state:
        self._state._checkpoint.save_last = event.value

handle_save_top_k_change(event)

Handle save top k changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#save-top-k-input")
def handle_save_top_k_change(self, event: Input.Changed) -> None:
    """Handle save top k changes."""
    if self._state and event.value:
        try:
            self._state._checkpoint.save_top_k = int(event.value)
        except ValueError:
            pass

handle_save_viz_change(event)

Handle save viz changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#save-viz-checkbox")
def handle_save_viz_change(self, event: Checkbox.Changed) -> None:
    """Handle save viz changes."""
    if self._state:
        self._state._visualize_preds = event.value
        self._update_viz_options_visibility()

handle_scale_change(event)

Handle scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scale-input")
def handle_scale_change(self, event: Input.Changed) -> None:
    """Handle scale changes."""
    if self._state and event.value:
        try:
            self._state._input_scale = float(event.value)
            self._update_shape_display()
            self._update_memory_display()
        except ValueError:
            pass

handle_scale_checkbox_change(event)

Handle scale changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#scale-checkbox")
def handle_scale_checkbox_change(self, event: Checkbox.Changed) -> None:
    """Handle scale changes."""
    if self._state:
        self._state._augmentation.scale_enabled = event.value

handle_scale_max_change(event)

Handle scale max changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scale-max-input")
def handle_scale_max_change(self, event: Input.Changed) -> None:
    """Handle scale max changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.scale_max = float(event.value)
        except ValueError:
            pass

handle_scale_min_change(event)

Handle scale min changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scale-min-input")
def handle_scale_min_change(self, event: Input.Changed) -> None:
    """Handle scale min changes."""
    if self._state and event.value:
        try:
            self._state._augmentation.scale_min = float(event.value)
        except ValueError:
            pass

handle_scheduler_change(event)

Handle scheduler changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#scheduler-select")
def handle_scheduler_change(self, event: Select.Changed) -> None:
    """Handle scheduler changes."""
    if self._state and event.value:
        self._state._scheduler.type = SchedulerType(event.value)
        # Show/hide scheduler param containers
        self._update_scheduler_params_visibility(event.value)

handle_scheduler_cooldown_change(event)

Handle scheduler cooldown changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-cooldown-input")
def handle_scheduler_cooldown_change(self, event: Input.Changed) -> None:
    """Handle scheduler cooldown changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.cooldown = int(event.value)
        except ValueError:
            pass

handle_scheduler_end_lr_change(event)

Handle scheduler end lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-end-lr-input")
def handle_scheduler_end_lr_change(self, event: Input.Changed) -> None:
    """Handle scheduler end lr changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.end_lr = float(event.value)
        except ValueError:
            pass

handle_scheduler_eta_min_change(event)

Handle scheduler eta min changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-eta-min-input")
def handle_scheduler_eta_min_change(self, event: Input.Changed) -> None:
    """Handle scheduler eta min changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.eta_min = float(event.value)
        except ValueError:
            pass

handle_scheduler_factor_change(event)

Handle scheduler factor changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-factor-input")
def handle_scheduler_factor_change(self, event: Input.Changed) -> None:
    """Handle scheduler factor changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.factor = float(event.value)
        except ValueError:
            pass

handle_scheduler_gamma_change(event)

Handle scheduler gamma changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-gamma-input")
def handle_scheduler_gamma_change(self, event: Input.Changed) -> None:
    """Handle scheduler gamma changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.gamma = float(event.value)
        except ValueError:
            pass

handle_scheduler_linear_warmup_epochs_change(event)

Handle scheduler linear warmup epochs changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-linear-warmup-epochs-input")
def handle_scheduler_linear_warmup_epochs_change(
    self, event: Input.Changed
) -> None:
    """Handle scheduler linear warmup epochs changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.linear_warmup_epochs = int(event.value)
        except ValueError:
            pass

handle_scheduler_linear_warmup_start_lr_change(event)

Handle scheduler linear warmup start lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-linear-warmup-start-lr-input")
def handle_scheduler_linear_warmup_start_lr_change(
    self, event: Input.Changed
) -> None:
    """Handle scheduler linear warmup start lr changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.linear_warmup_start_lr = float(event.value)
        except ValueError:
            pass

handle_scheduler_min_lr_change(event)

Handle scheduler min lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-min-lr-input")
def handle_scheduler_min_lr_change(self, event: Input.Changed) -> None:
    """Handle scheduler min lr changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.min_lr = float(event.value)
        except ValueError:
            pass

handle_scheduler_patience_change(event)

Handle scheduler patience changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-patience-input")
def handle_scheduler_patience_change(self, event: Input.Changed) -> None:
    """Handle scheduler patience changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.plateau_patience = int(event.value)
        except ValueError:
            pass

handle_scheduler_step_size_change(event)

Handle scheduler step size changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-step-size-input")
def handle_scheduler_step_size_change(self, event: Input.Changed) -> None:
    """Handle scheduler step size changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.step_size = int(event.value)
        except ValueError:
            pass

handle_scheduler_warmup_epochs_change(event)

Handle scheduler warmup epochs changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-warmup-epochs-input")
def handle_scheduler_warmup_epochs_change(self, event: Input.Changed) -> None:
    """Handle scheduler warmup epochs changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.warmup_epochs = int(event.value)
        except ValueError:
            pass

handle_scheduler_warmup_start_lr_change(event)

Handle scheduler warmup start lr changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#scheduler-warmup-start-lr-input")
def handle_scheduler_warmup_start_lr_change(self, event: Input.Changed) -> None:
    """Handle scheduler warmup start lr changes."""
    if self._state and event.value:
        try:
            self._state._scheduler.warmup_start_lr = float(event.value)
        except ValueError:
            pass

handle_sigma_change(event)

Handle sigma changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#sigma-input")
def handle_sigma_change(self, event: Input.Changed) -> None:
    """Handle sigma changes."""
    if self._state and event.value:
        try:
            self._state._sigma = float(event.value)
            self._update_model_info_display()  # Update Gaussian radius display
        except ValueError:
            pass

handle_stride_change(event)

Handle stride changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Select.Changed, "#max-stride-select")
def handle_stride_change(self, event: Select.Changed) -> None:
    """Handle stride changes."""
    if self._state and event.value:
        self._state._max_stride = int(event.value)
        self._update_model_info_display()
        self._update_memory_display()

handle_use_existing_change(event)

Handle use existing changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#use-existing-checkbox")
def handle_use_existing_change(self, event: Checkbox.Changed) -> None:
    """Handle use existing changes."""
    if self._state:
        self._state._cache_config.use_existing_imgs = event.value

handle_val_fraction_change(event)

Handle val fraction changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#val-fraction-input")
def handle_val_fraction_change(self, event: Input.Changed) -> None:
    """Handle val fraction changes."""
    if self._state and event.value:
        try:
            self._state._validation_fraction = float(event.value)
        except ValueError:
            pass

handle_visualize_preds_change(event)

Handle visualize preds changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#visualize-preds-checkbox")
def handle_visualize_preds_change(self, event: Checkbox.Changed) -> None:
    """Handle visualize preds changes."""
    if self._state:
        self._state._visualize_preds = event.value
        self._update_viz_options_visibility()

handle_viz_keep_folder_change(event)

Handle viz keep folder changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#viz-keep-folder-checkbox")
def handle_viz_keep_folder_change(self, event: Checkbox.Changed) -> None:
    """Handle viz keep folder changes."""
    if self._state:
        self._state._keep_viz = event.value

handle_wandb_change(event)

Handle wandb changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#wandb-checkbox")
def handle_wandb_change(self, event: Checkbox.Changed) -> None:
    """Handle wandb changes."""
    if self._state:
        self._state._wandb.enabled = event.value
        self._update_wandb_options_visibility()

handle_wandb_entity_change(event)

Handle wandb entity changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#wandb-entity-input")
def handle_wandb_entity_change(self, event: Input.Changed) -> None:
    """Handle wandb entity changes."""
    if self._state:
        self._state._wandb.entity = event.value or ""

handle_wandb_project_change(event)

Handle wandb project changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Input.Changed, "#wandb-project-input")
def handle_wandb_project_change(self, event: Input.Changed) -> None:
    """Handle wandb project changes."""
    if self._state:
        self._state._wandb.project = event.value or "sleap-nn"

handle_wandb_save_viz_change(event)

Handle wandb save viz changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#wandb-save-viz-checkbox")
def handle_wandb_save_viz_change(self, event: Checkbox.Changed) -> None:
    """Handle wandb save viz changes."""
    if self._state:
        self._state._wandb.save_viz_imgs = event.value

handle_wandb_viz_change(event)

Handle wandb viz changes.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
@on(Checkbox.Changed, "#wandb-viz-checkbox")
def handle_wandb_viz_change(self, event: Checkbox.Changed) -> None:
    """Handle wandb viz changes."""
    if self._state:
        self._state._wandb.viz_enabled = event.value

on_mount()

Initialize displays when widget is mounted.

Source code in sleap_nn/config_generator/tui/screens/configure_screen.py
def on_mount(self) -> None:
    """Initialize displays when widget is mounted."""
    self._update_shape_display()
    self._update_memory_display()
    self._update_model_info_display()
    self._update_cache_memory_display()
    self._update_cache_options_visibility()
    self._update_imagenet_visibility()
    self._update_wandb_options_visibility()
    self._update_viz_options_visibility()
    self._update_eval_options_visibility()
    # For top-down models, also update centroid and instance-specific displays
    if self._state and self._state.is_topdown:
        self._update_centroid_shape_display()
        self._update_centroid_model_info_display()
        self._update_centroid_cache_memory_display()
        self._update_centroid_cache_options_visibility()
        self._update_instance_cache_memory_display()
        self._update_instance_cache_options_visibility()

ExportScreen

Bases: VerticalScroll

Export configuration screen component.

Provides: - YAML configuration preview - Dual config preview for top-down pipelines - Save to file functionality - Copy to clipboard - CLI command suggestions

Methods:

Name Description
__init__

Initialize the export screen.

compose

Compose the export screen layout.

handle_copy

Handle copy to clipboard button press.

handle_refresh

Handle refresh button press.

handle_save

Handle save button press.

on_mount

Initialize preview when mounted.

update_preview

Update the YAML preview displays.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
class ExportScreen(VerticalScroll):
    """Export configuration screen component.

    Provides:
    - YAML configuration preview
    - Dual config preview for top-down pipelines
    - Save to file functionality
    - Copy to clipboard
    - CLI command suggestions
    """

    DEFAULT_CSS = """
    ExportScreen {
        width: 100%;
        height: 100%;
        padding: 1;
    }

    .section-title {
        text-style: bold;
        padding: 1 0;
    }

    .yaml-preview {
        height: 1fr;
        min-height: 20;
    }

    .button-row {
        height: auto;
        padding: 1;
        align: center middle;
    }

    .cli-box {
        height: auto;
        padding: 1;
        margin: 1 0;
        border: solid $surface-lighten-2;
        background: $surface;
    }

    .cli-command {
        color: $success;
    }

    .status-message {
        height: auto;
        padding: 1 0;
    }
    """

    def __init__(self, state: "ConfigState", **kwargs):
        """Initialize the export screen.

        Args:
            state: Shared configuration state.
            **kwargs: Additional arguments for Container.
        """
        super().__init__(**kwargs)
        self._state = state

    def compose(self) -> ComposeResult:
        """Compose the export screen layout."""
        yield Static("Configuration Preview", classes="section-title")

        # Show different preview based on pipeline type
        if self._state.is_topdown:
            yield from self._compose_dual_preview()
        else:
            yield from self._compose_single_preview()

        yield Rule()

        # Export Options
        yield from self._compose_export_options()

        yield Rule()

        # CLI Commands
        yield from self._compose_cli_section()

        # Status message
        yield Static("", id="export-status", classes="status-message")

    def _compose_single_preview(self) -> ComposeResult:
        """Compose single config preview."""
        yield TextArea(
            id="yaml-preview",
            read_only=True,
            language="yaml",
            classes="yaml-preview",
        )

    def _compose_dual_preview(self) -> ComposeResult:
        """Compose dual config preview for top-down pipelines."""
        yield InfoBox(
            "Top-down pipelines require two separate configs: one for the centroid model "
            "and one for the centered instance model.",
        )

        with TabbedContent(id="dual-preview-tabs"):
            with TabPane("Centroid Config", id="centroid-tab"):
                yield TextArea(
                    id="centroid-yaml-preview",
                    read_only=True,
                    language="yaml",
                    classes="yaml-preview",
                )

            with TabPane("Centered Instance Config", id="ci-tab"):
                yield TextArea(
                    id="ci-yaml-preview",
                    read_only=True,
                    language="yaml",
                    classes="yaml-preview",
                )

    def _compose_export_options(self) -> ComposeResult:
        """Compose export options section."""
        yield Static("Export Options", classes="section-title")

        # Output path
        with Horizontal(classes="form-row"):
            yield Static("Output Path:", classes="form-label")
            yield Input(
                value=str(self._get_default_output_path()),
                id="output-path-input",
            )

        # Buttons
        with Horizontal(classes="button-row"):
            yield Button("Refresh Preview", id="refresh-btn")
            yield Button("Save to File", id="save-btn", variant="primary")
            yield Button("Copy to Clipboard", id="copy-btn")

    def _compose_cli_section(self) -> ComposeResult:
        """Compose CLI command suggestions section."""
        yield Static("CLI Commands", classes="section-title")

        yield InfoBox(
            "After saving your config, use these commands to train and run inference:",
        )

        # Training command
        output_path = self._get_default_output_path()
        with Container(classes="cli-box"):
            yield Static("Train the model:", classes="subsection-title")
            if self._state.is_topdown:
                yield Static(
                    f"# Step 1: Train centroid model\n"
                    f"sleap-nn train --config {output_path.stem}_centroid.yaml\n\n"
                    f"# Step 2: Train centered instance model\n"
                    f"sleap-nn train --config {output_path.stem}_centered_instance.yaml",
                    id="train-command",
                    classes="cli-command",
                )
            else:
                yield Static(
                    f"sleap-nn train --config {output_path}",
                    id="train-command",
                    classes="cli-command",
                )

        # Inference command
        with Container(classes="cli-box"):
            yield Static("Run inference:", classes="subsection-title")
            if self._state.is_topdown:
                yield Static(
                    "sleap-nn predict \\\n"
                    "  --model-paths centroid_model.ckpt centered_instance_model.ckpt \\\n"
                    "  --video-path your_video.mp4 \\\n"
                    "  --output-path predictions.slp",
                    id="predict-command",
                    classes="cli-command",
                )
            else:
                yield Static(
                    "sleap-nn predict \\\n"
                    "  --model-paths your_model.ckpt \\\n"
                    "  --video-path your_video.mp4 \\\n"
                    "  --output-path predictions.slp",
                    id="predict-command",
                    classes="cli-command",
                )

    def _get_default_output_path(self) -> Path:
        """Get the default output path for the config file."""
        return self._state.slp_path.parent / f"{self._state.slp_path.stem}_config.yaml"

    def update_preview(self) -> None:
        """Update the YAML preview displays."""
        try:
            if self._state.is_topdown:
                # Update dual previews
                try:
                    centroid_preview = self.query_one(
                        "#centroid-yaml-preview", TextArea
                    )
                    centroid_preview.text = self._state.to_centroid_yaml()
                except Exception:
                    pass

                try:
                    ci_preview = self.query_one("#ci-yaml-preview", TextArea)
                    ci_preview.text = self._state.to_centered_instance_yaml()
                except Exception:
                    pass
            else:
                # Update single preview
                try:
                    preview = self.query_one("#yaml-preview", TextArea)
                    preview.text = self._state.to_yaml()
                except Exception:
                    pass
        except Exception as e:
            self._show_status(f"Error generating preview: {e}", error=True)

    def _show_status(
        self, message: str, error: bool = False, success: bool = False
    ) -> None:
        """Show a status message.

        Args:
            message: Message to display.
            error: Whether this is an error message.
            success: Whether this is a success message.
        """
        try:
            status = self.query_one("#export-status", Static)
            if error:
                status.update(f"[red]Error: {message}[/red]")
            elif success:
                status.update(f"[green]✓ {message}[/green]")
            else:
                status.update(message)
        except Exception:
            pass

    @on(Button.Pressed, "#refresh-btn")
    def handle_refresh(self) -> None:
        """Handle refresh button press."""
        self.update_preview()
        self._show_status("Preview refreshed", success=True)

    @on(Button.Pressed, "#save-btn")
    def handle_save(self) -> None:
        """Handle save button press."""
        try:
            output_path = self.query_one("#output-path-input", Input).value

            if self._state.is_topdown:
                # Save dual configs
                base_path = output_path.replace(".yaml", "").replace("_config", "")
                centroid_path, ci_path = self._state.save_dual(base_path)
                self._show_status(
                    f"Saved: {centroid_path} and {ci_path}",
                    success=True,
                )
            else:
                # Save single config
                self._state.save(output_path)
                self._show_status(f"Saved to: {output_path}", success=True)

        except Exception as e:
            self._show_status(str(e), error=True)

    @on(Button.Pressed, "#copy-btn")
    def handle_copy(self) -> None:
        """Handle copy to clipboard button press."""
        try:
            if self._state.is_topdown:
                # Copy both configs
                yaml_str = (
                    "# ============== CENTROID CONFIG ==============\n"
                    + self._state.to_centroid_yaml()
                    + "\n\n# ============== CENTERED INSTANCE CONFIG ==============\n"
                    + self._state.to_centered_instance_yaml()
                )
            else:
                yaml_str = self._state.to_yaml()

            # Try to copy to clipboard
            try:
                import pyperclip

                pyperclip.copy(yaml_str)
                self._show_status("Copied to clipboard!", success=True)
            except ImportError:
                self._show_status(
                    "Install pyperclip for clipboard support: pip install pyperclip",
                    error=True,
                )
        except Exception as e:
            self._show_status(str(e), error=True)

    def on_mount(self) -> None:
        """Initialize preview when mounted."""
        self.update_preview()

__init__(state, **kwargs)

Initialize the export screen.

Parameters:

Name Type Description Default
state ConfigState

Shared configuration state.

required
**kwargs

Additional arguments for Container.

{}
Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def __init__(self, state: "ConfigState", **kwargs):
    """Initialize the export screen.

    Args:
        state: Shared configuration state.
        **kwargs: Additional arguments for Container.
    """
    super().__init__(**kwargs)
    self._state = state

compose()

Compose the export screen layout.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def compose(self) -> ComposeResult:
    """Compose the export screen layout."""
    yield Static("Configuration Preview", classes="section-title")

    # Show different preview based on pipeline type
    if self._state.is_topdown:
        yield from self._compose_dual_preview()
    else:
        yield from self._compose_single_preview()

    yield Rule()

    # Export Options
    yield from self._compose_export_options()

    yield Rule()

    # CLI Commands
    yield from self._compose_cli_section()

    # Status message
    yield Static("", id="export-status", classes="status-message")

handle_copy()

Handle copy to clipboard button press.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
@on(Button.Pressed, "#copy-btn")
def handle_copy(self) -> None:
    """Handle copy to clipboard button press."""
    try:
        if self._state.is_topdown:
            # Copy both configs
            yaml_str = (
                "# ============== CENTROID CONFIG ==============\n"
                + self._state.to_centroid_yaml()
                + "\n\n# ============== CENTERED INSTANCE CONFIG ==============\n"
                + self._state.to_centered_instance_yaml()
            )
        else:
            yaml_str = self._state.to_yaml()

        # Try to copy to clipboard
        try:
            import pyperclip

            pyperclip.copy(yaml_str)
            self._show_status("Copied to clipboard!", success=True)
        except ImportError:
            self._show_status(
                "Install pyperclip for clipboard support: pip install pyperclip",
                error=True,
            )
    except Exception as e:
        self._show_status(str(e), error=True)

handle_refresh()

Handle refresh button press.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
@on(Button.Pressed, "#refresh-btn")
def handle_refresh(self) -> None:
    """Handle refresh button press."""
    self.update_preview()
    self._show_status("Preview refreshed", success=True)

handle_save()

Handle save button press.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
@on(Button.Pressed, "#save-btn")
def handle_save(self) -> None:
    """Handle save button press."""
    try:
        output_path = self.query_one("#output-path-input", Input).value

        if self._state.is_topdown:
            # Save dual configs
            base_path = output_path.replace(".yaml", "").replace("_config", "")
            centroid_path, ci_path = self._state.save_dual(base_path)
            self._show_status(
                f"Saved: {centroid_path} and {ci_path}",
                success=True,
            )
        else:
            # Save single config
            self._state.save(output_path)
            self._show_status(f"Saved to: {output_path}", success=True)

    except Exception as e:
        self._show_status(str(e), error=True)

on_mount()

Initialize preview when mounted.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def on_mount(self) -> None:
    """Initialize preview when mounted."""
    self.update_preview()

update_preview()

Update the YAML preview displays.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def update_preview(self) -> None:
    """Update the YAML preview displays."""
    try:
        if self._state.is_topdown:
            # Update dual previews
            try:
                centroid_preview = self.query_one(
                    "#centroid-yaml-preview", TextArea
                )
                centroid_preview.text = self._state.to_centroid_yaml()
            except Exception:
                pass

            try:
                ci_preview = self.query_one("#ci-yaml-preview", TextArea)
                ci_preview.text = self._state.to_centered_instance_yaml()
            except Exception:
                pass
        else:
            # Update single preview
            try:
                preview = self.query_one("#yaml-preview", TextArea)
                preview.text = self._state.to_yaml()
            except Exception:
                pass
    except Exception as e:
        self._show_status(f"Error generating preview: {e}", error=True)

LoadScreen

Bases: Widget

Screen for loading and analyzing SLP files.

Classes:

Name Description
FileLoaded

Message sent when a file is loaded.

Methods:

Name Description
__init__

Initialize the load screen.

compose

Compose the screen layout.

handle_input_submit

Handle Enter key in input field.

on_mount

Handle mount - update summary if state exists.

Source code in sleap_nn/config_generator/tui/screens/load_screen.py
class LoadScreen(Widget):
    """Screen for loading and analyzing SLP files."""

    DEFAULT_CSS = """
    LoadScreen {
        width: 100%;
        height: 100%;
        padding: 1;
    }

    #load-container {
        width: 100%;
        height: auto;
    }

    #file-input-group {
        width: 100%;
        height: auto;
        padding: 1;
    }

    #file-input {
        width: 1fr;
    }

    #browse-btn {
        min-width: 12;
        margin-left: 1;
    }

    #summary-container {
        width: 100%;
        height: auto;
        margin-top: 2;
    }

    #dataset-summary {
        background: $panel;
        border: solid $primary;
        padding: 1 2;
        min-height: 15;
    }

    """

    class FileLoaded(Message):
        """Message sent when a file is loaded."""

        def __init__(self, state: ConfigState):
            """Initialize with the loaded state."""
            super().__init__()
            self.state = state

    def __init__(self, state: Optional[ConfigState] = None, **kwargs):
        """Initialize the load screen.

        Args:
            state: Optional existing ConfigState.
            **kwargs: Additional keyword arguments passed to parent.
        """
        super().__init__(**kwargs)
        self._state = state

    def compose(self) -> ComposeResult:
        """Compose the screen layout."""
        with Vertical(id="load-container"):
            yield Label(
                "[bold]Step 1: Dataset Overview[/bold]", classes="section-title"
            )

            if self._state:
                # File already loaded via CLI
                yield Label(
                    "Review your dataset statistics below, then proceed to "
                    "select a model type.",
                    classes="hint",
                )
            else:
                # No file provided, show input
                yield Label(
                    "Enter the path to your .slp file (SLEAP labels file)",
                    classes="hint",
                )

            with Horizontal(id="file-input-group"):
                yield Input(
                    placeholder="Path to .slp file... (press Enter to load)",
                    id="file-input",
                    value=str(self._state.slp_path) if self._state else "",
                )

            with Container(id="summary-container"):
                yield DatasetSummary(self._state, id="dataset-summary")

    def on_mount(self) -> None:
        """Handle mount - update summary if state exists."""
        if self._state is not None:
            summary = self.query_one("#dataset-summary", DatasetSummary)
            summary.update_state(self._state)

    @on(Input.Submitted, "#file-input")
    async def handle_input_submit(self, event: Input.Submitted) -> None:
        """Handle Enter key in input field."""
        file_input = self.query_one("#file-input", Input)
        path = file_input.value.strip()

        if not path:
            self.app.notify("Please enter a file path", severity="error")
            return

        path_obj = Path(path).expanduser().resolve()

        if not path_obj.exists():
            self.app.notify(f"File not found: {path}", severity="error")
            return

        if not path_obj.suffix.lower() in [".slp", ".h5"]:
            self.app.notify("Please select a .slp file", severity="error")
            return

        try:
            self.app.notify("Loading and analyzing file...")
            self._state = ConfigState(str(path_obj))

            # Trigger lazy loading of stats
            _ = self._state.stats

            # Update summary display
            summary = self.query_one("#dataset-summary", DatasetSummary)
            summary.update_state(self._state)

            # Auto-configure with defaults
            self._state.auto_configure()

            # Post message to parent app
            self.post_message(self.FileLoaded(self._state))

        except Exception as e:
            self.app.notify(f"Error loading file: {e}", severity="error")

FileLoaded

Bases: Message

Message sent when a file is loaded.

Methods:

Name Description
__init__

Initialize with the loaded state.

Source code in sleap_nn/config_generator/tui/screens/load_screen.py
class FileLoaded(Message):
    """Message sent when a file is loaded."""

    def __init__(self, state: ConfigState):
        """Initialize with the loaded state."""
        super().__init__()
        self.state = state
__init__(state)

Initialize with the loaded state.

Source code in sleap_nn/config_generator/tui/screens/load_screen.py
def __init__(self, state: ConfigState):
    """Initialize with the loaded state."""
    super().__init__()
    self.state = state

__init__(state=None, **kwargs)

Initialize the load screen.

Parameters:

Name Type Description Default
state Optional[ConfigState]

Optional existing ConfigState.

None
**kwargs

Additional keyword arguments passed to parent.

{}
Source code in sleap_nn/config_generator/tui/screens/load_screen.py
def __init__(self, state: Optional[ConfigState] = None, **kwargs):
    """Initialize the load screen.

    Args:
        state: Optional existing ConfigState.
        **kwargs: Additional keyword arguments passed to parent.
    """
    super().__init__(**kwargs)
    self._state = state

compose()

Compose the screen layout.

Source code in sleap_nn/config_generator/tui/screens/load_screen.py
def compose(self) -> ComposeResult:
    """Compose the screen layout."""
    with Vertical(id="load-container"):
        yield Label(
            "[bold]Step 1: Dataset Overview[/bold]", classes="section-title"
        )

        if self._state:
            # File already loaded via CLI
            yield Label(
                "Review your dataset statistics below, then proceed to "
                "select a model type.",
                classes="hint",
            )
        else:
            # No file provided, show input
            yield Label(
                "Enter the path to your .slp file (SLEAP labels file)",
                classes="hint",
            )

        with Horizontal(id="file-input-group"):
            yield Input(
                placeholder="Path to .slp file... (press Enter to load)",
                id="file-input",
                value=str(self._state.slp_path) if self._state else "",
            )

        with Container(id="summary-container"):
            yield DatasetSummary(self._state, id="dataset-summary")

handle_input_submit(event) async

Handle Enter key in input field.

Source code in sleap_nn/config_generator/tui/screens/load_screen.py
@on(Input.Submitted, "#file-input")
async def handle_input_submit(self, event: Input.Submitted) -> None:
    """Handle Enter key in input field."""
    file_input = self.query_one("#file-input", Input)
    path = file_input.value.strip()

    if not path:
        self.app.notify("Please enter a file path", severity="error")
        return

    path_obj = Path(path).expanduser().resolve()

    if not path_obj.exists():
        self.app.notify(f"File not found: {path}", severity="error")
        return

    if not path_obj.suffix.lower() in [".slp", ".h5"]:
        self.app.notify("Please select a .slp file", severity="error")
        return

    try:
        self.app.notify("Loading and analyzing file...")
        self._state = ConfigState(str(path_obj))

        # Trigger lazy loading of stats
        _ = self._state.stats

        # Update summary display
        summary = self.query_one("#dataset-summary", DatasetSummary)
        summary.update_state(self._state)

        # Auto-configure with defaults
        self._state.auto_configure()

        # Post message to parent app
        self.post_message(self.FileLoaded(self._state))

    except Exception as e:
        self.app.notify(f"Error loading file: {e}", severity="error")

on_mount()

Handle mount - update summary if state exists.

Source code in sleap_nn/config_generator/tui/screens/load_screen.py
def on_mount(self) -> None:
    """Handle mount - update summary if state exists."""
    if self._state is not None:
        summary = self.query_one("#dataset-summary", DatasetSummary)
        summary.update_state(self._state)

ModelSelectScreen

Bases: Widget

Screen for selecting model type.

Methods:

Name Description
__init__

Initialize the model select screen.

compose

Compose the screen layout.

handle_identity_change

Handle identity checkbox change.

handle_model_selected

Handle model type selection.

on_mount

Handle mount - preselect recommended option.

Source code in sleap_nn/config_generator/tui/screens/model_select_screen.py
class ModelSelectScreen(Widget):
    """Screen for selecting model type."""

    DEFAULT_CSS = """
    ModelSelectScreen {
        width: 100%;
        height: 100%;
        padding: 1;
    }

    #model-container {
        width: 100%;
        height: auto;
    }

    #model-options {
        width: 100%;
        height: auto;
        margin: 1 0;
    }

    .model-option {
        width: 100%;
        height: auto;
        padding: 1;
        margin: 0 0 1 0;
        background: $panel;
        border: solid $primary;
    }

    .model-option:hover {
        background: $panel-lighten-1;
    }

    .model-option.selected {
        border: solid $success;
        background: $success-darken-3;
    }

    .model-option.disabled {
        background: $surface-darken-1;
    }

    #identity-option {
        margin-top: 2;
        padding: 1;
    }

    #pipeline-info-box {
        background: $primary-darken-3;
        border: solid $primary;
        padding: 1;
        margin-top: 1;
        min-height: 3;
    }
    """

    def __init__(self, state: Optional[ConfigState] = None, **kwargs):
        """Initialize the model select screen.

        Args:
            state: ConfigState with dataset statistics.
            **kwargs: Additional keyword arguments passed to parent.
        """
        super().__init__(**kwargs)
        self._state = state
        self._selected_type: Optional[PipelineType] = None
        # Restore identity state from pipeline type
        self._use_identity = False
        if state and state._pipeline:
            self._use_identity = "multi_class" in str(state._pipeline)

    def compose(self) -> ComposeResult:
        """Compose the screen layout."""
        with Vertical(id="model-container"):
            yield Label(
                "[bold]Step 2: Select Model Type[/bold]", classes="section-title"
            )

            yield Label("Choose the model architecture:", classes="hint")

            # Model type options
            with Vertical(id="model-options"):
                yield from self._create_model_options()

            # Pipeline info box (shows details about selected pipeline)
            with Container(id="pipeline-info-box"):
                yield Static(id="pipeline-info")

            # Identity tracking option - restore from state
            identity_enabled = False
            if self._state and self._state._pipeline:
                identity_enabled = "multi_class" in str(self._state._pipeline)

            with Horizontal(id="identity-option"):
                yield Checkbox(
                    "Enable identity tracking",
                    id="identity-checkbox",
                    value=identity_enabled,
                )
                yield Label("(requires track annotations in your data)", classes="hint")

    def _create_model_options(self):
        """Create model type option widgets."""
        if not self._state:
            return

        stats = self._state.stats
        rec = self._state.recommendation

        # Single Instance
        single_disabled = stats.max_instances_per_frame > 1
        yield ModelTypeOption(
            pipeline_type="single_instance",
            title="Single Instance",
            description="For videos with exactly one animal per frame.",
            details="Best for: Single-animal experiments, isolated subjects.",
            is_recommended=rec.pipeline.recommended == "single_instance",
            option_disabled=single_disabled,
            disabled_reason=(
                "Multiple instances detected in data" if single_disabled else ""
            ),
            classes="model-option",
            id="opt-single",
        )

        # Top-Down
        is_topdown_rec = rec.pipeline.recommended in [
            "centroid",
            "centered_instance",
            "multi_class_topdown",
        ]
        yield ModelTypeOption(
            pipeline_type="centroid",
            title="Top-Down",
            description="Detect centroids first, then find keypoints in cropped regions.",
            details="Best for: Multiple well-separated animals that are small relative to frame.",
            is_recommended=is_topdown_rec,
            is_two_stage=True,
            classes="model-option",
            id="opt-topdown",
        )

        # Centroid (standalone) - single point per animal, ONE config.
        yield ModelTypeOption(
            pipeline_type="centroid_only",
            title="Centroid (single point per animal)",
            description="Detect one point per animal directly (no keypoint refinement stage).",
            details="Best for: Single-node skeletons / animal counting / tracking a single landmark.",
            is_recommended=rec.pipeline.recommended == "centroid_only",
            is_two_stage=False,
            classes="model-option",
            id="opt-centroid-only",
        )

        # Bottom-Up
        bottomup_disabled = stats.num_edges == 0
        is_bottomup_rec = rec.pipeline.recommended in [
            "bottomup",
            "multi_class_bottomup",
        ]
        yield ModelTypeOption(
            pipeline_type="bottomup",
            title="Bottom-Up",
            description="Multi-animal detection using Part Affinity Fields (PAFs).",
            details="Best for: Crowded/overlapping animals. Detects all parts, then groups into instances.",
            is_recommended=is_bottomup_rec,
            option_disabled=bottomup_disabled,
            disabled_reason=(
                "Requires skeleton edges for Part Affinity Fields"
                if bottomup_disabled
                else ""
            ),
            classes="model-option",
            id="opt-bottomup",
        )

    def on_mount(self) -> None:
        """Handle mount - preselect recommended option."""
        selected_type = None

        if self._state and self._state._pipeline:
            selected_type = self._state._pipeline
        elif self._state:
            rec = self._state.recommendation
            # Map to base type (not multi-class variant)
            base_type = rec.pipeline.recommended
            if base_type in ["multi_class_bottomup", "multi_class_topdown"]:
                base_type = "bottomup" if "bottomup" in base_type else "centroid"
            selected_type = base_type

        if selected_type:
            self._select_type(selected_type)

        # Disable identity checkbox if no tracks
        if self._state and not self._state.stats.has_tracks:
            checkbox = self.query_one("#identity-checkbox", Checkbox)
            checkbox.disabled = True

    def _select_type(self, pipeline_type: PipelineType) -> None:
        """Select a model type."""
        self._selected_type = pipeline_type

        # Update visual selection
        for opt in self.query(".model-option"):
            if isinstance(opt, ModelTypeOption):
                opt.selected = opt.pipeline_type == pipeline_type
                if opt.selected:
                    opt.add_class("selected")
                else:
                    opt.remove_class("selected")

        # Update pipeline info box
        self._update_pipeline_info(pipeline_type)

        # Update state
        if self._state:
            # Check if identity is enabled
            checkbox = self.query_one("#identity-checkbox", Checkbox)
            # The standalone centroid model has no multi-class variant — the
            # identity checkbox must NOT upgrade it. Only the paired top-down
            # ``centroid`` and ``bottomup`` map to their multi_class variants.
            if checkbox.value and pipeline_type == "centroid":
                self._state._pipeline = "multi_class_topdown"
            elif checkbox.value and pipeline_type == "bottomup":
                self._state._pipeline = "multi_class_bottomup"
            else:
                self._state._pipeline = pipeline_type

            # Update input scale based on pipeline type (web app behavior).
            # Top-down stage-1 centroid uses lower scale (0.5); the standalone
            # centroid_only and other single-stage models use full scale (1.0).
            is_topdown = self._state._pipeline in [
                "centroid",
                "centered_instance",
                "multi_class_topdown",
            ]
            if is_topdown:
                self._state._input_scale = 0.5  # Lower scale for centroid
                self._state._sigma = 5.0  # Larger sigma for centroid
                self._state._output_stride = 2
            elif self._state._pipeline == "centroid_only":
                # Standalone centroid: full resolution, tighter sigma.
                self._state._input_scale = 1.0
                self._state._sigma = 2.5
                self._state._output_stride = 2
            else:
                self._state._input_scale = 1.0  # Full scale for other models

            # Floor max_stride by RF coverage at the new scale, but DON'T
            # downgrade below what the bucket recommendation gave on SLP load
            # (which uses scale=1.0 — matches web app's setDefaultParameters).
            base_stride = 32 if "large_rf" in self._state._backbone else 16
            scaled_max_animal_size = (
                self._state.stats.max_bbox_size * self._state._input_scale
            )
            coverage_stride = self._state._compute_max_stride_for_animal_size(
                scaled_max_animal_size
            )
            self._state._max_stride = max(
                base_stride, coverage_stride, self._state._max_stride
            )

    def _update_pipeline_info(self, pipeline_type: PipelineType) -> None:
        """Update the pipeline info box based on selected type."""
        info_widget = self.query_one("#pipeline-info", Static)

        if pipeline_type == "single_instance":
            info_widget.update(
                "[bold cyan]Single Instance Pipeline[/bold cyan]\n"
                "Trains one model that detects all keypoints in full-frame images.\n"
                "You'll get [bold]1 YAML config[/bold] file."
            )
        elif pipeline_type == "centroid":
            info_widget.update(
                "[bold cyan]Top-Down Pipeline[/bold cyan]\n"
                "This requires training [bold]two models[/bold] sequentially:\n"
                "  [yellow]1. Centroid Model[/yellow] - Detects animal centers in full images\n"
                "  [yellow]2. Centered Instance Model[/yellow] - Detects keypoints in cropped regions\n"
                "You'll configure both models and get [bold]2 YAML configs[/bold]."
            )
        elif pipeline_type == "centroid_only":
            info_widget.update(
                "[bold cyan]Centroid Pipeline (standalone)[/bold cyan]\n"
                "Trains [bold]one model[/bold] that detects a single point per animal\n"
                "(anchor node, or mean of visible nodes). No keypoint-refinement stage.\n"
                "You'll get [bold]1 YAML config[/bold] file."
            )
        elif pipeline_type == "bottomup":
            info_widget.update(
                "[bold cyan]Bottom-Up Pipeline[/bold cyan]\n"
                "Trains one model that detects all keypoints and uses Part Affinity Fields\n"
                "to group them into animal instances. You'll get [bold]1 YAML config[/bold] file."
            )

    @on(Checkbox.Changed, "#identity-checkbox")
    def handle_identity_change(self, event: Checkbox.Changed) -> None:
        """Handle identity checkbox change."""
        self._use_identity = event.value
        # Re-apply selection with identity consideration
        if self._selected_type:
            self._select_type(self._selected_type)

    @on(ModelTypeOption.Selected)
    def handle_model_selected(self, event: ModelTypeOption.Selected) -> None:
        """Handle model type selection."""
        self._select_type(event.pipeline_type)

__init__(state=None, **kwargs)

Initialize the model select screen.

Parameters:

Name Type Description Default
state Optional[ConfigState]

ConfigState with dataset statistics.

None
**kwargs

Additional keyword arguments passed to parent.

{}
Source code in sleap_nn/config_generator/tui/screens/model_select_screen.py
def __init__(self, state: Optional[ConfigState] = None, **kwargs):
    """Initialize the model select screen.

    Args:
        state: ConfigState with dataset statistics.
        **kwargs: Additional keyword arguments passed to parent.
    """
    super().__init__(**kwargs)
    self._state = state
    self._selected_type: Optional[PipelineType] = None
    # Restore identity state from pipeline type
    self._use_identity = False
    if state and state._pipeline:
        self._use_identity = "multi_class" in str(state._pipeline)

compose()

Compose the screen layout.

Source code in sleap_nn/config_generator/tui/screens/model_select_screen.py
def compose(self) -> ComposeResult:
    """Compose the screen layout."""
    with Vertical(id="model-container"):
        yield Label(
            "[bold]Step 2: Select Model Type[/bold]", classes="section-title"
        )

        yield Label("Choose the model architecture:", classes="hint")

        # Model type options
        with Vertical(id="model-options"):
            yield from self._create_model_options()

        # Pipeline info box (shows details about selected pipeline)
        with Container(id="pipeline-info-box"):
            yield Static(id="pipeline-info")

        # Identity tracking option - restore from state
        identity_enabled = False
        if self._state and self._state._pipeline:
            identity_enabled = "multi_class" in str(self._state._pipeline)

        with Horizontal(id="identity-option"):
            yield Checkbox(
                "Enable identity tracking",
                id="identity-checkbox",
                value=identity_enabled,
            )
            yield Label("(requires track annotations in your data)", classes="hint")

handle_identity_change(event)

Handle identity checkbox change.

Source code in sleap_nn/config_generator/tui/screens/model_select_screen.py
@on(Checkbox.Changed, "#identity-checkbox")
def handle_identity_change(self, event: Checkbox.Changed) -> None:
    """Handle identity checkbox change."""
    self._use_identity = event.value
    # Re-apply selection with identity consideration
    if self._selected_type:
        self._select_type(self._selected_type)

handle_model_selected(event)

Handle model type selection.

Source code in sleap_nn/config_generator/tui/screens/model_select_screen.py
@on(ModelTypeOption.Selected)
def handle_model_selected(self, event: ModelTypeOption.Selected) -> None:
    """Handle model type selection."""
    self._select_type(event.pipeline_type)

on_mount()

Handle mount - preselect recommended option.

Source code in sleap_nn/config_generator/tui/screens/model_select_screen.py
def on_mount(self) -> None:
    """Handle mount - preselect recommended option."""
    selected_type = None

    if self._state and self._state._pipeline:
        selected_type = self._state._pipeline
    elif self._state:
        rec = self._state.recommendation
        # Map to base type (not multi-class variant)
        base_type = rec.pipeline.recommended
        if base_type in ["multi_class_bottomup", "multi_class_topdown"]:
            base_type = "bottomup" if "bottomup" in base_type else "centroid"
        selected_type = base_type

    if selected_type:
        self._select_type(selected_type)

    # Disable identity checkbox if no tracks
    if self._state and not self._state.stats.has_tracks:
        checkbox = self.query_one("#identity-checkbox", Checkbox)
        checkbox.disabled = True

TopDownExportScreen

Bases: Container

Specialized export screen for top-down pipelines.

Shows side-by-side configuration for centroid and centered instance models.

Methods:

Name Description
__init__

Initialize the top-down export screen.

compose

Compose the top-down export screen layout.

handle_refresh

Handle refresh button press.

handle_save

Handle save button press.

on_mount

Initialize previews on mount.

update_preview

Update both preview panes.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
class TopDownExportScreen(Container):
    """Specialized export screen for top-down pipelines.

    Shows side-by-side configuration for centroid and centered instance models.
    """

    DEFAULT_CSS = """
    TopDownExportScreen {
        height: 100%;
        padding: 0;
    }

    TopDownExportScreen .dual-preview {
        height: 1fr;
        layout: horizontal;
    }

    TopDownExportScreen .preview-pane {
        width: 1fr;
        height: 100%;
        padding: 0 1;
    }

    TopDownExportScreen .preview-title {
        text-style: bold;
        padding: 1 0;
        text-align: center;
    }
    """

    def __init__(self, state: "ConfigState", **kwargs):
        """Initialize the top-down export screen.

        Args:
            state: Shared configuration state.
            **kwargs: Additional arguments for Container.
        """
        super().__init__(**kwargs)
        self._state = state

    def compose(self) -> ComposeResult:
        """Compose the top-down export screen layout."""
        with Container(classes="dual-preview"):
            # Centroid config
            with Container(classes="preview-pane"):
                yield Static("Centroid Model Config", classes="preview-title")
                yield TextArea(
                    id="td-centroid-preview",
                    read_only=True,
                    language="yaml",
                )

            # Centered instance config
            with Container(classes="preview-pane"):
                yield Static("Centered Instance Model Config", classes="preview-title")
                yield TextArea(
                    id="td-ci-preview",
                    read_only=True,
                    language="yaml",
                )

        with Horizontal(classes="button-row"):
            yield Button("Refresh", id="td-refresh-btn")
            yield Button("Save Both", id="td-save-btn", variant="primary")

        yield Static("", id="td-export-status")

    def update_preview(self) -> None:
        """Update both preview panes."""
        try:
            self.query_one("#td-centroid-preview", TextArea).text = (
                self._state.to_centroid_yaml()
            )
            self.query_one("#td-ci-preview", TextArea).text = (
                self._state.to_centered_instance_yaml()
            )
        except Exception:
            pass

    @on(Button.Pressed, "#td-refresh-btn")
    def handle_refresh(self) -> None:
        """Handle refresh button press."""
        self.update_preview()

    @on(Button.Pressed, "#td-save-btn")
    def handle_save(self) -> None:
        """Handle save button press."""
        try:
            base_path = str(self._state.slp_path.parent / self._state.slp_path.stem)
            centroid_path, ci_path = self._state.save_dual(base_path)

            status = self.query_one("#td-export-status", Static)
            status.update(f"[green]✓ Saved: {centroid_path}, {ci_path}[/green]")
        except Exception as e:
            status = self.query_one("#td-export-status", Static)
            status.update(f"[red]Error: {e}[/red]")

    def on_mount(self) -> None:
        """Initialize previews on mount."""
        self.update_preview()

__init__(state, **kwargs)

Initialize the top-down export screen.

Parameters:

Name Type Description Default
state ConfigState

Shared configuration state.

required
**kwargs

Additional arguments for Container.

{}
Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def __init__(self, state: "ConfigState", **kwargs):
    """Initialize the top-down export screen.

    Args:
        state: Shared configuration state.
        **kwargs: Additional arguments for Container.
    """
    super().__init__(**kwargs)
    self._state = state

compose()

Compose the top-down export screen layout.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def compose(self) -> ComposeResult:
    """Compose the top-down export screen layout."""
    with Container(classes="dual-preview"):
        # Centroid config
        with Container(classes="preview-pane"):
            yield Static("Centroid Model Config", classes="preview-title")
            yield TextArea(
                id="td-centroid-preview",
                read_only=True,
                language="yaml",
            )

        # Centered instance config
        with Container(classes="preview-pane"):
            yield Static("Centered Instance Model Config", classes="preview-title")
            yield TextArea(
                id="td-ci-preview",
                read_only=True,
                language="yaml",
            )

    with Horizontal(classes="button-row"):
        yield Button("Refresh", id="td-refresh-btn")
        yield Button("Save Both", id="td-save-btn", variant="primary")

    yield Static("", id="td-export-status")

handle_refresh()

Handle refresh button press.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
@on(Button.Pressed, "#td-refresh-btn")
def handle_refresh(self) -> None:
    """Handle refresh button press."""
    self.update_preview()

handle_save()

Handle save button press.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
@on(Button.Pressed, "#td-save-btn")
def handle_save(self) -> None:
    """Handle save button press."""
    try:
        base_path = str(self._state.slp_path.parent / self._state.slp_path.stem)
        centroid_path, ci_path = self._state.save_dual(base_path)

        status = self.query_one("#td-export-status", Static)
        status.update(f"[green]✓ Saved: {centroid_path}, {ci_path}[/green]")
    except Exception as e:
        status = self.query_one("#td-export-status", Static)
        status.update(f"[red]Error: {e}[/red]")

on_mount()

Initialize previews on mount.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def on_mount(self) -> None:
    """Initialize previews on mount."""
    self.update_preview()

update_preview()

Update both preview panes.

Source code in sleap_nn/config_generator/tui/screens/export_screen.py
def update_preview(self) -> None:
    """Update both preview panes."""
    try:
        self.query_one("#td-centroid-preview", TextArea).text = (
            self._state.to_centroid_yaml()
        )
        self.query_one("#td-ci-preview", TextArea).text = (
            self._state.to_centered_instance_yaml()
        )
    except Exception:
        pass