File size: 51,829 Bytes
222a479
 
 
555af9e
9f6398a
 
222a479
 
 
 
 
 
 
 
 
735e6be
222a479
735e6be
 
 
 
 
 
 
 
 
 
 
222a479
735e6be
222a479
735e6be
 
 
 
 
222a479
 
d22cdd3
 
222a479
735e6be
222a479
 
 
 
9079a44
 
222a479
 
d22cdd3
735e6be
222a479
3457b3c
 
735e6be
2064ae5
 
 
3457b3c
 
 
 
d22cdd3
222a479
 
3457b3c
222a479
d22cdd3
222a479
 
9f6398a
222a479
735e6be
 
2064ae5
222a479
 
735e6be
222a479
 
 
 
 
 
 
 
735e6be
222a479
 
 
 
24a570b
90ad1ff
24a570b
 
 
 
 
90ad1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24a570b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b5ce8a
24a570b
 
 
 
 
 
 
 
 
 
0b5ce8a
222a479
24a570b
 
 
 
 
 
d4decd1
0b5ce8a
24a570b
0b5ce8a
24a570b
0b5ce8a
24a570b
0b5ce8a
24a570b
0b5ce8a
 
222a479
f1d8a94
222a479
d4decd1
222a479
 
24a570b
222a479
 
24a570b
 
222a479
24a570b
222a479
 
d4decd1
24a570b
 
 
 
 
 
 
 
 
 
d4decd1
24a570b
 
 
 
 
 
d4decd1
24a570b
222a479
 
555af9e
 
 
 
d479dee
 
 
 
555af9e
 
 
 
d479dee
 
555af9e
 
d479dee
555af9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
555af9e
 
 
 
 
 
 
 
 
c09e7f4
555af9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3457b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
3457b3c
 
c09e7f4
3457b3c
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3457b3c
 
 
 
 
 
c09e7f4
 
3457b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
c414c6c
c09e7f4
c414c6c
c09e7f4
 
 
 
c414c6c
c09e7f4
 
c414c6c
 
 
c09e7f4
c414c6c
 
c09e7f4
 
 
 
 
 
 
 
 
c414c6c
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
c414c6c
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3457b3c
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
3457b3c
 
 
 
c414c6c
3457b3c
c414c6c
 
 
 
 
 
 
 
 
 
 
3457b3c
 
 
 
 
 
 
 
 
c09e7f4
 
c414c6c
c09e7f4
c414c6c
 
 
 
 
 
 
c09e7f4
 
c414c6c
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3457b3c
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3457b3c
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222a479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b95c67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
735e6be
c09e7f4
 
 
 
 
555af9e
222a479
 
555af9e
222a479
 
555af9e
222a479
555af9e
c09e7f4
222a479
 
 
555af9e
 
 
 
c09e7f4
555af9e
 
c09e7f4
 
 
555af9e
 
 
 
c09e7f4
555af9e
 
c09e7f4
 
 
555af9e
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
555af9e
 
 
 
 
 
222a479
555af9e
 
 
 
 
 
 
 
 
 
3457b3c
555af9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4decd1
222a479
555af9e
 
222a479
 
5651996
 
 
 
222a479
 
5651996
 
 
222a479
555af9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c09e7f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555af9e
 
c09e7f4
222a479
 
735e6be
 
222a479
d479dee
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
"""YAML-BERT missing-field suggester β€” Gradio demo.

Paste a Kubernetes YAML manifest; the model identifies fields it expects
to see but that are absent. Runs the YAML-BERT checkpoint
trained on full 276K K8s corpus β€” atomic-vocab prediction conditioned on
doc_vec, with tree-aware bottom-up aggregation.

Run locally:
    pip install gradio
    PYTHONPATH=. python app.py
"""
from __future__ import annotations

import os
import sys
import time

# Progress logging β€” every step on its own line with elapsed wall time, so
# the HF Space build log shows continuous progress instead of long silent gaps.
_T0 = time.time()


def _log(msg: str) -> None:
    print(f"[{time.time() - _T0:6.2f}s] {msg}", file=sys.stderr, flush=True)


_log("Starting app...")
_log("Importing torch (takes a few seconds)...")
import torch
_log(f"torch {torch.__version__} imported")

_log("Importing gradio...")
import gradio as gr
_log(f"gradio {gr.__version__} imported")

_log("Importing yaml_bert package...")
from yaml_bert.config import YamlBertConfig
from yaml_bert.embedding import YamlBertEmbedding
from yaml_bert.model import YamlBertModel
from yaml_bert.suggest import suggest_missing_fields
from yaml_bert.vocab import Vocabulary
_log("yaml_bert imported")


# ----- Model loading (once at startup) -----

DEFAULT_CHECKPOINT = "model/yaml_bert.pt"
DEFAULT_VOCAB = "model/vocab.json"


def load_model(checkpoint_path: str, vocab_path: str) -> tuple[YamlBertModel, Vocabulary]:
    _log(f"Loading vocab from {vocab_path}")
    vocab = Vocabulary.load(vocab_path)
    _log(f"Vocab loaded: subword={vocab.subword_vocab_size}, "
         f"atomic targets={vocab.atomic_target_vocab_size}")

    _log(f"Reading checkpoint file {checkpoint_path}")
    cp = torch.load(checkpoint_path, map_location="cpu", weights_only=False)

    _log("Building YamlBertModel architecture (v9: subword embedding)")
    # recon_enabled=True keeps the checkpoint's recon_head weights loadable.
    # The recon head exists but is never invoked at inference time
    # (no subtree_roots_flat passed in forward).
    config = YamlBertConfig(recon_enabled=True)
    emb = YamlBertEmbedding(
        config=config,
        subword_vocab_size=vocab.subword_vocab_size,
    )
    model = YamlBertModel(
        config=config,
        embedding=emb,
        atomic_vocab_size=vocab.atomic_target_vocab_size,
    )
    _log("Model architecture ready")

    _log("Loading state dict into model")
    model.load_state_dict(cp["model_state_dict"])
    model.eval()
    _log("State dict loaded; model in eval mode")
    return model, vocab


checkpoint_path = os.environ.get("YAML_BERT_CHECKPOINT", DEFAULT_CHECKPOINT)
vocab_path = os.environ.get("YAML_BERT_VOCAB", DEFAULT_VOCAB)

MODEL, VOCAB = load_model(checkpoint_path, vocab_path)
n_params = sum(p.numel() for p in MODEL.parameters())
_log(f"Model fully loaded β€” {n_params:,} parameters")


# ----- Inference -----

import re
import yaml

MAX_LINES_PER_DOC = 300
_DOC_SEP_RE = re.compile(r"^---\s*$", re.MULTILINE)


def _label_for_example(yaml_text: str) -> str:
    """Compact label for an example YAML.

    - Single-doc: 'Kind: name' (with '(namespace)' suffix if metadata.namespace is set)
    - Multi-doc:  'MultiDoc'
    """
    try:
        docs = [d for d in yaml.safe_load_all(yaml_text) if isinstance(d, dict)]
    except Exception:
        return "(unparseable)"
    if len(docs) > 1:
        return "MultiDoc"
    if not docs:
        return "(unidentified)"
    d = docs[0]
    kind = d.get("kind", "(no kind)")
    meta = d.get("metadata") if isinstance(d.get("metadata"), dict) else {}
    name = meta.get("name")
    namespace = meta.get("namespace")
    label = f"{kind}: {name}" if name else str(kind)
    if namespace:
        label += f" ({namespace})"
    return label


def _split_yaml_documents(text: str) -> list[str]:
    """Split a multi-document YAML on '---' separator lines.

    Preserves original formatting (no parse-and-reserialize). Filters out
    empty / whitespace-only chunks and comment-only chunks.
    """
    parts = _DOC_SEP_RE.split(text)
    out: list[str] = []
    for p in parts:
        p = p.strip()
        if not p:
            continue
        # Skip chunks that are nothing but comments
        if all(line.strip().startswith("#") or not line.strip()
               for line in p.splitlines()):
            continue
        out.append(p)
    return out


def _format_suggestions(suggestions: list[dict]) -> str:
    """Render the suggestions list as a grouped markdown table."""
    by_parent: dict[str, list[dict]] = {}
    for s in suggestions:
        by_parent.setdefault(s.get("parent_path") or "(root)", []).append(s)

    blocks: list[str] = []
    for parent in sorted(by_parent.keys(),
                         key=lambda p: -max(s["confidence"] for s in by_parent[p])):
        rows = ["| Missing key | Confidence | Strength |", "|---|---:|---|"]
        for s in sorted(by_parent[parent], key=lambda x: -x["confidence"]):
            conf = s["confidence"]
            strength = "**STRONG**" if conf >= 0.7 else ("MODERATE" if conf >= 0.5 else "weak")
            rows.append(f"| `{s['missing_key']}` | {conf:.1%} | {strength} |")
        blocks.append(f"#### `{parent}`\n" + "\n".join(rows))
    return "\n\n".join(blocks)


def _detect_kind(yaml_text: str) -> str:
    """Best-effort 'kind:' extraction from raw YAML text (for the header label)."""
    m = re.search(r"^kind:\s*(\S+)", yaml_text, re.MULTILINE)
    return m.group(1) if m else "?"


def _suggest_one(yaml_text: str, threshold: float) -> str:
    n_lines = len(yaml_text.splitlines())
    if n_lines > MAX_LINES_PER_DOC:
        return (
            f"⚠️ **Document too large** β€” {n_lines} lines (limit: {MAX_LINES_PER_DOC}).\n\n"
            f"The model was trained on manifests up to ~512 linearized nodes. Large "
            f"manifests (cluster-dumped Pods with rich annotations / init containers, deep CRDs) "
            f"exceed that and inference becomes slow and unreliable.\n\n"
            f"Trim verbose sections (annotations, env vars, deep probes) or split the manifest."
        )

    try:
        suggestions, _skipped = suggest_missing_fields(
            MODEL, VOCAB, yaml_text,
            threshold=threshold,
        )
    except Exception as e:
        return f"**Parse error:**\n```\n{e}\n```"

    if not suggestions:
        return ("_No suggestions above threshold β€” the model thinks this is "
                "either complete or has no strong opinions._")

    return _format_suggestions(suggestions)


def suggest(yaml_text: str, threshold: float) -> str:
    yaml_text = (yaml_text or "").strip()
    if not yaml_text:
        return "_Paste a YAML manifest above to see missing-field suggestions._"

    docs = _split_yaml_documents(yaml_text)
    if not docs:
        return "_No YAML documents found in the input._"

    # Single doc: skip the document header for cleaner output
    if len(docs) == 1:
        return _suggest_one(docs[0], threshold)

    # Multi-doc: prefix each doc's output with a kind/index header
    blocks: list[str] = []
    for i, doc_text in enumerate(docs, 1):
        kind = _detect_kind(doc_text)
        header = f"### Document {i}: `{kind}`"
        blocks.append(header + "\n\n" + _suggest_one(doc_text, threshold))
    return "\n\n---\n\n".join(blocks)


# ----- Manifest galaxy (precomputed UMAP of YAML-BERT doc_vecs) -----

GALAXY_DATA_PATH = "galaxy_data.json"

# Qualitative palette (Plotly D3-style category20 + 5 more) so we can color
# up to 25 distinct kinds before falling back to "Other". The corpus has
# 49 distinct kinds total; the long tail under ~25 is rare enough that
# graying them together is fine.
_GALAXY_PALETTE = [
    "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
    "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf",
    "#aec7e8", "#ffbb78", "#98df8a", "#ff9896", "#c5b0d5",
    "#c49c94", "#f7b6d2", "#c7c7c7", "#dbdb8d", "#9edae5",
    "#393b79", "#637939", "#8c6d31", "#843c39", "#7b4173",
]
_GALAXY_OTHER_COLOR = "#d0d0d0"
_GALAXY_TOP_N = 25


def _build_galaxy_figure(data_path: str):
    """Build a Plotly scatter from the precomputed galaxy_data.json."""
    import json
    from collections import Counter
    import plotly.graph_objects as go

    with open(data_path) as f:
        data = json.load(f)

    kinds = data["kind"]
    top_kinds = [k for k, _ in Counter(kinds).most_common(_GALAXY_TOP_N)]
    top_set = set(top_kinds)
    color_map = {k: _GALAXY_PALETTE[i % len(_GALAXY_PALETTE)]
                 for i, k in enumerate(top_kinds)}

    fig = go.Figure()
    # "Other" first so the named kinds render on top
    series: list[tuple[str, str, list[int]]] = []
    other_idxs = [i for i, k in enumerate(kinds) if k not in top_set]
    if other_idxs:
        series.append(("Other", _GALAXY_OTHER_COLOR, other_idxs))
    for k in top_kinds:
        series.append((k, color_map[k], [i for i, kk in enumerate(kinds) if kk == k]))

    def _hover(i: int) -> str:
        parts = [f"<b>{kinds[i]}</b>", data["name"][i]]
        ns = data["namespace"][i]
        # "(default)" is the build-time placeholder when the manifest didn't
        # specify a namespace β€” true for all cluster-scoped kinds (Namespace,
        # ClusterRole, CRD, …) and for namespaced resources that omit it.
        # Showing "ns: (default)" for these is misleading, so suppress.
        if ns and ns != "(default)":
            parts.append(f"ns: {ns}")
        return "<br>".join(parts)

    for label, color, idxs in series:
        if not idxs:
            continue
        fig.add_scattergl(
            x=[data["x"][i] for i in idxs],
            y=[data["y"][i] for i in idxs],
            mode="markers",
            name=f"{label} ({len(idxs):,})",
            marker=dict(size=4, color=color, opacity=0.65),
            text=[_hover(i) for i in idxs],
            hovertemplate="%{text}<extra></extra>",
        )

    fig.update_layout(
        title=(f"UMAP projection of {data['n']:,} K8s manifests "
               f"(cosine metric)"),
        xaxis=dict(visible=False),
        yaxis=dict(visible=False, scaleanchor="x"),
        height=720,
        margin=dict(l=10, r=10, t=60, b=10),
        legend=dict(orientation="v", x=1.0, y=1.0, font=dict(size=10)),
        plot_bgcolor="white",
    )
    return fig


_log("Building manifest galaxy figure...")
try:
    GALAXY_FIG = _build_galaxy_figure(GALAXY_DATA_PATH)
    _log("Galaxy figure built")
except FileNotFoundError:
    GALAXY_FIG = None
    _log(f"Galaxy data not found at {GALAXY_DATA_PATH} β€” galaxy tab will be empty")


# ----- Structural probes -----
#
# Presets of hand-crafted manifests that probe whether the model encodes
# specific structural distinctions. Each preset's manifests are encoded to
# doc_vecs, projected to 2D via MDS (preserves pairwise cosine distances),
# and shown as a scatter plot. Users can add their own YAMLs to see where
# they land relative to the preset.

# ---- Preset manifests ----

_POD_NGINX = """apiVersion: v1
kind: Pod
metadata:
  name: nginx-app
spec:
  containers:
  - name: app
    image: nginx
    ports:
    - containerPort: 80
"""

_POD_REDIS = """apiVersion: v1
kind: Pod
metadata:
  name: redis-app
spec:
  containers:
  - name: app
    image: redis
    ports:
    - containerPort: 6379
"""

_POD_NGINX_INIT = """apiVersion: v1
kind: Pod
metadata:
  name: nginx-with-init
spec:
  initContainers:
  - name: setup
    image: busybox
    command: ["sh", "-c", "echo init"]
  containers:
  - name: app
    image: nginx
    ports:
    - containerPort: 80
"""

_POD_REDIS_INIT = """apiVersion: v1
kind: Pod
metadata:
  name: redis-with-init
spec:
  initContainers:
  - name: setup
    image: busybox
    command: ["sh", "-c", "echo init"]
  containers:
  - name: app
    image: redis
    ports:
    - containerPort: 6379
"""

_SVC_CLUSTERIP_WEB = """apiVersion: v1
kind: Service
metadata:
  name: web-clusterip
spec:
  type: ClusterIP
  selector:
    app: web
  ports:
  - port: 80
    targetPort: 8080
"""

_SVC_CLUSTERIP_API = """apiVersion: v1
kind: Service
metadata:
  name: api-clusterip
spec:
  type: ClusterIP
  selector:
    app: api
  ports:
  - port: 443
    targetPort: 8443
"""

_SVC_NODEPORT = """apiVersion: v1
kind: Service
metadata:
  name: web-nodeport
spec:
  type: NodePort
  selector:
    app: web
  ports:
  - port: 80
    targetPort: 8080
    nodePort: 30080
"""

_SVC_LOADBALANCER = """apiVersion: v1
kind: Service
metadata:
  name: web-lb
spec:
  type: LoadBalancer
  selector:
    app: web
  externalTrafficPolicy: Local
  ports:
  - port: 80
    targetPort: 8080
"""

_DEPLOY_NGINX = """apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: app
        image: nginx
        ports:
        - containerPort: 80
"""

_CONFIGMAP_APP = """apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  config.yaml: |
    debug: true
  app.properties: |
    key1=value1
"""

_POD_NS_PROD_1 = """apiVersion: v1
kind: Pod
metadata:
  name: web-1
  namespace: production
spec:
  containers:
  - name: app
    image: nginx
    ports:
    - containerPort: 80
"""

_POD_NS_PROD_2 = """apiVersion: v1
kind: Pod
metadata:
  name: web-2
  namespace: production
spec:
  containers:
  - name: app
    image: nginx
    ports:
    - containerPort: 80
"""

_POD_NS_STAGING_1 = """apiVersion: v1
kind: Pod
metadata:
  name: web-1
  namespace: staging
spec:
  containers:
  - name: app
    image: nginx
    ports:
    - containerPort: 80
"""

_POD_NS_STAGING_2 = """apiVersion: v1
kind: Pod
metadata:
  name: web-2
  namespace: staging
spec:
  containers:
  - name: app
    image: nginx
    ports:
    - containerPort: 80
"""

_DEPLOY_APPS_V1 = """apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: app
        image: nginx
        ports:
        - containerPort: 80
"""

_DEPLOY_EXT_V1BETA1 = """apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: app
        image: nginx
        ports:
        - containerPort: 80
"""

_REPLICASET_APPS_V1 = """apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: app
        image: nginx
        ports:
        - containerPort: 80
"""

_CONFIGMAP_PLAIN = """apiVersion: v1
kind: ConfigMap
metadata:
  name: web
data:
  config.yaml: |
    debug: true
  app.properties: |
    key=value
"""


def _verdict_init(cos):
    cd = float(cos[2][3])
    mx = float(max(cos[0][2], cos[1][3]))
    passed = cd > mx
    msg = (
        f"`cos(C, D)` = **{cd:.3f}** (both have init) Β· "
        f"`max(cos(A,C), cos(B,D))` = **{mx:.3f}** (mixed). "
        + ("Init-pairs cluster tighter than mixed pairs β€” the model treats "
           "`initContainers` as a real structural feature, stronger than the "
           "value-content similarity (shared `image: nginx` etc.)."
           if passed else
           "Mixed pairs are at least as close as init-pairs. This is not a "
           "regression β€” it reveals a re-balance: BPE makes `image` values "
           "compositionally visible to attention, so pods sharing `nginx` "
           "cluster together regardless of init presence. v8 with atomic "
           "`[UNK]` values had no choice but to lean on structure; v9 has "
           "both signals and now weights content more heavily here. "
           "Whether that's good depends on use case (good for content "
           "retrieval, less ideal for structure-only similarity).")
    )
    return passed, msg


def _verdict_service_type(cos):
    same = float(cos[0][1])
    cross = float(max(cos[0][2], cos[0][3], cos[1][2], cos[1][3], cos[2][3]))
    passed = same > cross
    msg = (
        f"`cos(A, B)` = **{same:.3f}** (both ClusterIP) Β· "
        f"`max(cross-type)` = **{cross:.3f}**. "
        + ("Same-type pairs cluster tighter than cross-type pairs β€” the "
           "model has internalized the `type` distinction (likely through "
           "the structural keys each type adds: `nodePort`, "
           "`externalTrafficPolicy`)."
           if passed else
           "Same-type pairs do not cluster more tightly than cross-type "
           "pairs β€” `type` is not a primary axis in the embedding here.")
    )
    return passed, msg


def _verdict_namespace(cos):
    # A, B in production Β· C, D in staging β€” all otherwise identical Pods.
    same_ns = float(min(cos[0][1], cos[2][3]))
    cross_ns = float(max(cos[0][2], cos[0][3], cos[1][2], cos[1][3]))
    passed = same_ns > cross_ns
    msg = (
        f"`min(same-ns cos)` = **{same_ns:.3f}** Β· "
        f"`max(cross-ns cos)` = **{cross_ns:.3f}**. "
        + ("Same-namespace pairs cluster tighter β€” value content reaches "
           "`doc_vec` even though the aggregator only sums KEY subtrees. "
           "BPE makes namespace values compositional (e.g., `prod | uction`), "
           "and self-attention spreads that signal into neighboring KEY "
           "hidden states, which then flow into `doc_vec`. This was the "
           "first failure of `[UNK]`-vocab v8 that v9 fixed."
           if passed else
           "Same-namespace and cross-namespace pairs have indistinguishable "
           "cosines. v8 saw this because both `production` and `staging` "
           "often hit `[UNK]`. v9 was expected to pass β€” if it does not, "
           "investigate.")
    )
    return passed, msg


def _verdict_apiversion(cos):
    # A = apps/v1 Deployment
    # B = extensions/v1beta1 Deployment  (same kind, deprecated apiVersion)
    # C = apps/v1 ReplicaSet              (different kind, same group, similar structure)
    # D = v1 ConfigMap                    (unrelated)
    same_kind = float(cos[0][1])
    same_group_diff_kind = float(cos[0][2])
    unrelated = float(cos[0][3])
    primary = same_kind > same_group_diff_kind
    secondary = same_group_diff_kind > unrelated
    passed = primary and secondary
    msg = (
        f"`cos(apps/v1 Dep, ext/v1beta1 Dep)` = **{same_kind:.3f}** Β· "
        f"`cos(Dep, ReplicaSet)` = **{same_group_diff_kind:.3f}** Β· "
        f"`cos(Dep, ConfigMap)` = **{unrelated:.3f}**. "
        + ("Same-kind-different-apiVersion pairs cluster tightest, then "
           "same-group-different-kind, then unrelated. The model treats "
           "apiVersion as a soft label, not a hard discriminator β€” it "
           "recognizes `apps/v1` and `extensions/v1beta1` Deployments as "
           "the same thing despite the apiVersion text differing."
           if passed else
           f"Expected ordering broken: same-kind={same_kind:.3f}, "
           f"same-group={same_group_diff_kind:.3f}, unrelated={unrelated:.3f}. "
           "If same-kind is NOT the tightest, the model is treating "
           "apiVersion as a hard discriminator and separating same-kind "
           "manifests by their api label β€” possibly an over-correction "
           "from the eval-probe accuracy.")
    )
    return passed, msg


def _verdict_cross_kind(cos):
    # A=Pod nginx, B=Pod redis, C=Deployment with nginx Pod template, D=ConfigMap
    pod_pod = float(cos[0][1])             # both Pods
    pod_deploy = float(cos[0][2])          # Pod ↔ Deployment with same-shape Pod template
    pod_cm = float(cos[0][3])              # Pod ↔ unrelated kind
    deploy_cm = float(cos[2][3])           # Deployment ↔ unrelated kind
    passed = pod_deploy > max(pod_cm, deploy_cm)
    msg = (
        f"`cos(Pod, Deployment-with-Pod-template)` = **{pod_deploy:.3f}** Β· "
        f"`cos(Pod, ConfigMap)` = **{pod_cm:.3f}** Β· "
        f"`cos(Pod, Pod)` = **{pod_pod:.3f}** (kind silo). "
        + ("Pod and the Deployment containing the same Pod template are "
           "closer than either is to an unrelated ConfigMap β€” the model "
           "encodes the shared Pod-shape across the two kinds."
           if passed else
           "The shared Pod-shape across the two kinds is not detected β€” "
           "kinds form sharp silos in the embedding.")
    )
    return passed, msg


PRESETS = [
    {
        "id": "init",
        "title": "Pod Β± initContainers",
        "hypothesis": (
            "If the model treats `initContainers` as a structural feature, "
            "Pods that both have one should land closer in embedding space "
            "than mixed pairs. _Caveat: the init container in C and D is "
            "the same busybox setup, so `cos(C, D)` reflects both "
            "structural-key presence AND shared busybox content β€” this "
            "test is necessary but not sufficient for the structural "
            "claim. A follow-up varying the init-container content would "
            "isolate the two signals._"
        ),
        "manifests": [
            {"name": "nginx (no init)",   "yaml": _POD_NGINX},
            {"name": "redis (no init)",   "yaml": _POD_REDIS},
            {"name": "nginx + init",      "yaml": _POD_NGINX_INIT},
            {"name": "redis + init",      "yaml": _POD_REDIS_INIT},
        ],
        "verdict_fn": _verdict_init,
    },
    {
        "id": "service-type",
        "title": "Service type (ClusterIP / NodePort / LoadBalancer)",
        "hypothesis": (
            "Each Service `type` brings its own structural keys "
            "(`nodePort`, `externalTrafficPolicy`, …). If the model "
            "encodes `type` as a structural axis, same-type Services "
            "should sit closer in embedding space than cross-type ones, "
            "even when their selectors and ports differ."
        ),
        "manifests": [
            {"name": "ClusterIP β€” app=web",       "yaml": _SVC_CLUSTERIP_WEB},
            {"name": "ClusterIP β€” app=api",       "yaml": _SVC_CLUSTERIP_API},
            {"name": "NodePort β€” app=web",        "yaml": _SVC_NODEPORT},
            {"name": "LoadBalancer β€” app=web",    "yaml": _SVC_LOADBALANCER},
        ],
        "verdict_fn": _verdict_service_type,
    },
    {
        "id": "namespace",
        "title": "Pods in same namespace vs different namespace",
        "hypothesis": (
            "If the model encodes `metadata.namespace` as a feature, two "
            "Pods in the same namespace should be closer than two Pods in "
            "different namespaces (controlling for structure). "
            "_v8 with atomic vocab failed this probe β€” `production` and "
            "`staging` often mapped to `[UNK]`, leaving attention with no "
            "compositional content to work with. v9's byte-level BPE "
            "decomposes namespace values into subwords, and self-attention "
            "now spreads value content into surrounding KEY hidden states. "
            "Those KEYs are what the aggregator pools into `doc_vec` β€” so "
            "namespace effectively reaches `doc_vec` through the attention "
            "channel, even though the aggregator stays KEY-only by design._"
        ),
        "manifests": [
            {"name": "production / web-1", "yaml": _POD_NS_PROD_1},
            {"name": "production / web-2", "yaml": _POD_NS_PROD_2},
            {"name": "staging / web-1",    "yaml": _POD_NS_STAGING_1},
            {"name": "staging / web-2",    "yaml": _POD_NS_STAGING_2},
        ],
        "verdict_fn": _verdict_namespace,
    },
    {
        "id": "apiversion",
        "title": "apiVersion sensitivity (same kind, different apiVersion)",
        "hypothesis": (
            "K8s supports multiple `apiVersion`s for the same kind "
            "(e.g., `apps/v1` Deployment and the deprecated "
            "`extensions/v1beta1` Deployment have nearly identical "
            "structure). If the model encodes kind as the dominant "
            "structural signal and `apiVersion` as a soft label, two "
            "same-kind manifests with different `apiVersion`s should "
            "still sit closer in embedding space than a same-group "
            "different-kind manifest (`apps/v1` ReplicaSet), which in "
            "turn should be closer than an unrelated kind "
            "(`v1` ConfigMap). _Eval probes already show 99.8% "
            "`apiVersion` classification accuracy β€” but classification "
            "is compatible with either treating `apiVersion` as a soft "
            "label or as a hard discriminator. This probe tests which._"
        ),
        "manifests": [
            {"name": "apps/v1 Deployment",         "yaml": _DEPLOY_APPS_V1},
            {"name": "extensions/v1beta1 Deploy",  "yaml": _DEPLOY_EXT_V1BETA1},
            {"name": "apps/v1 ReplicaSet",         "yaml": _REPLICASET_APPS_V1},
            {"name": "v1 ConfigMap (unrelated)",   "yaml": _CONFIGMAP_PLAIN},
        ],
        "verdict_fn": _verdict_apiversion,
    },
    {
        "id": "cross-kind",
        "title": "Pod vs Deployment containing the same Pod template",
        "hypothesis": (
            "A Deployment's `spec.template` carries a Pod's shape β€” the "
            "same `spec.containers` substructure as a standalone Pod, "
            "just nested one level deeper. If the model encodes that "
            "shape similarity, a standalone Pod and a Deployment "
            "containing the same Pod template should sit closer in "
            "embedding space than either does to an unrelated kind like "
            "ConfigMap."
        ),
        "manifests": [
            {"name": "Pod (nginx)",                       "yaml": _POD_NGINX},
            {"name": "Pod (redis)",                       "yaml": _POD_REDIS},
            {"name": "Deployment with nginx template",    "yaml": _DEPLOY_NGINX},
            {"name": "ConfigMap (unrelated)",             "yaml": _CONFIGMAP_APP},
        ],
        "verdict_fn": _verdict_cross_kind,
    },
]

# Letters & colors used for both plot points and accordion headers.
_PRESET_PALETTE = [
    "#1f77b4",  # A blue
    "#ff7f0e",  # B orange
    "#2ca02c",  # C green
    "#d62728",  # D red
    "#9467bd",  # E purple
    "#8c564b",  # F brown
    "#e377c2",  # G pink
    "#17becf",  # H cyan
]
_PRESET_LETTERS = ["A", "B", "C", "D", "E", "F", "G", "H"]


# Reuse one linearizer/annotator/config across calls (cheap, but skip the
# per-call construction inside _encode_doc_vec).
def _make_encoder_state():
    from yaml_bert.annotator import DomainAnnotator
    from yaml_bert.config import YamlBertConfig
    from yaml_bert.linearizer import YamlLinearizer
    return YamlLinearizer(), DomainAnnotator(), YamlBertConfig(
        mask_prob=0.0, recon_enabled=False,
    )


_LINEARIZER, _ANNOTATOR, _INFER_CONFIG = _make_encoder_state()


def _encode_doc_vec(yaml_text: str) -> torch.Tensor:
    """Encode one YAML doc and return its doc_vec (shape (d_model,))."""
    from yaml_bert.dataset import YamlBertDataset, collate_fn as _collate
    nodes = _LINEARIZER.linearize(yaml_text)
    if not nodes:
        raise ValueError("YAML produced no nodes")
    _ANNOTATOR.annotate(nodes)
    ds = YamlBertDataset([nodes], VOCAB, _INFER_CONFIG)
    item = ds[0]
    batch = _collate([item])
    with torch.no_grad():
        out = MODEL(
            token_ids=batch["token_ids"],
            node_types=batch["node_types"],
            depths=batch["depths"],
            sibling_indices=batch["sibling_indices"],
            batch_info=batch["batch_info"],
            padding_mask=batch["padding_mask"],
            logical_ids=batch["logical_ids"],
            n_logical_per_doc=batch["n_logical_per_doc"],
            parent_of_tensor=batch["parent_of_tensor"],
            top_level_key_mask=batch["top_level_key_mask"],
            edges_by_depth=batch["edges_by_depth"],
            parents_by_depth=batch["parents_by_depth"],
        )
    return out[1][0]  # (d_model,)


def _layout_2d(vecs):
    """Project doc_vecs to 2D coords via MDS on cosine distances."""
    import numpy as np
    n = len(vecs)
    if n == 1:
        return np.array([[0.0, 0.0]])
    if n == 2:
        return np.array([[-1.0, 0.0], [1.0, 0.0]])

    if isinstance(vecs, list):
        vecs = torch.stack(vecs)
    vecs_norm = vecs / vecs.norm(dim=1, keepdim=True)
    cos = (vecs_norm @ vecs_norm.t()).numpy()
    dist = 1.0 - cos
    np.fill_diagonal(dist, 0.0)
    dist = np.clip(dist, 0.0, None)
    # sklearn MDS(metric="precomputed") requires strict symmetry; floating-point
    # matmul can leave ~1e-7 asymmetries. Symmetrize explicitly.
    dist = (dist + dist.T) / 2

    from sklearn.manifold import MDS
    mds = MDS(
        n_components=2,
        metric="precomputed",
        random_state=42,
        normalized_stress="auto",
        init="classical_mds",
    )
    return mds.fit_transform(dist)


def _find_identical_groups(items, threshold: float = 0.9999):
    """Find groups of items whose pairwise cosine similarity is ~1.0.
    These represent inputs the model encodes to the same `doc_vec`
    (e.g. when their differing values all map to the same vocab token,
    typically [UNK]). The plot must show this honestly: they overlap.
    """
    if len(items) < 2:
        return []
    vecs = torch.stack([it["vec"] for it in items])
    vecs_norm = vecs / vecs.norm(dim=1, keepdim=True)
    cos = (vecs_norm @ vecs_norm.t()).numpy()

    groups: list[list[int]] = []
    assigned = [False] * len(items)
    for i in range(len(items)):
        if assigned[i]:
            continue
        group = [i]
        assigned[i] = True
        for j in range(i + 1, len(items)):
            if not assigned[j] and cos[i][j] >= threshold:
                group.append(j)
                assigned[j] = True
        if len(group) > 1:
            groups.append(group)
    return groups


def _collision_note(items):
    """Markdown note when two or more items produce identical doc_vecs."""
    groups = _find_identical_groups(items)
    if not groups:
        return ""
    lines = []
    for g in groups:
        labels = ", ".join(f"`{items[i]['letter']}`" for i in g)
        lines.append(
            f"- {labels} encode to **identical** `doc_vec`s "
            f"(`cos β‰ˆ 1.0`). The plot will show them overlapping β€” that "
            f"is honest: the model cannot tell these inputs apart. "
            f"Likely cause: differing values all collapse to the same "
            f"vocab token (often `[UNK]` when names aren't frequent "
            f"enough in the training corpus to earn a vocab slot)."
        )
    return "\n\n**Identical embeddings detected:**\n" + "\n".join(lines)


def _build_preset_figure(items, hypothesis=""):
    """Build a Plotly scatter from a list of {letter, name, vec, ...} items."""
    import plotly.graph_objects as go
    if not items:
        return go.Figure()
    vecs = [it["vec"] for it in items]
    coords = _layout_2d(vecs)
    colors = [_PRESET_PALETTE[i % len(_PRESET_PALETTE)] for i in range(len(items))]
    letters = [it["letter"] for it in items]
    names = [it["name"] for it in items]

    fig = go.Figure()
    fig.add_scatter(
        x=coords[:, 0],
        y=coords[:, 1],
        mode="markers+text",
        text=letters,
        textposition="top center",
        textfont=dict(size=14, color="#222"),
        marker=dict(size=18, color=colors, opacity=0.85,
                    line=dict(width=2, color="#222")),
        hovertext=[f"<b>{l}</b> β€” {n}" for l, n in zip(letters, names)],
        hovertemplate="%{hovertext}<extra></extra>",
        showlegend=False,
    )
    fig.update_layout(
        title="2D layout (MDS of cosine distances) β€” closer = more similar",
        height=460,
        margin=dict(l=10, r=10, t=50, b=10),
        xaxis=dict(visible=False),
        yaxis=dict(visible=False, scaleanchor="x"),
        plot_bgcolor="white",
    )
    return fig


def _encode_preset(preset):
    """Encode all manifests in a preset; return list of items with vecs."""
    items = []
    for i, m in enumerate(preset["manifests"]):
        vec = _encode_doc_vec(m["yaml"])
        items.append({
            "letter": _PRESET_LETTERS[i],
            "name": m["name"],
            "yaml": m["yaml"],
            "vec": vec,
            "preset_id": preset["id"],
        })
    return items


def _compute_cos_matrix(items):
    """Compute cosine matrix from items (for the verdict function)."""
    vecs = torch.stack([it["vec"] for it in items])
    vecs_norm = vecs / vecs.norm(dim=1, keepdim=True)
    return (vecs_norm @ vecs_norm.t()).numpy()


def _verdict_markdown(preset, items):
    """Run the preset's verdict function on the first N items (its presets)."""
    n_preset = len(preset["manifests"])
    if len(items) < n_preset:
        return "_(not enough manifests for verdict)_"
    cos = _compute_cos_matrix(items[:n_preset])
    passed, msg = preset["verdict_fn"](cos)
    emoji = "βœ…" if passed else "❌"
    main = f"**Verdict on preset:** {emoji} &nbsp; {msg}"
    return main + _collision_note(items)


_log("Encoding preset manifests...")
PRESET_BY_ID = {p["id"]: p for p in PRESETS}
PRESET_ITEMS_BY_ID = {p["id"]: _encode_preset(p) for p in PRESETS}
for p in PRESETS:
    items = PRESET_ITEMS_BY_ID[p["id"]]
    cos = _compute_cos_matrix(items)
    passed, _ = p["verdict_fn"](cos)
    _log(f"  '{p['title']}': {'PASS' if passed else 'FAIL'}")


# ----- UI -----

EXAMPLE_NGINX = """apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.8
        resources:
          limits:
            memory: "128Mi"
            cpu: "250m"
        ports:
        - containerPort: 80
"""

EXAMPLE_INCOMPLETE_SERVICE = """apiVersion: v1
kind: Service
metadata:
  name: my-svc
spec:
  selector:
    app: web
"""

EXAMPLE_CONFIGMAP = """apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  key1: value1
"""

EXAMPLE_STATEFULSET = """apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: nginx
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.21
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 1Gi
"""

EXAMPLE_CRONJOB = """apiVersion: batch/v1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/5 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox:1.28
            command: ["/bin/sh", "-c", "date; echo hello"]
          restartPolicy: OnFailure
"""

EXAMPLE_HPA = """apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: php-apache
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: php-apache
  minReplicas: 1
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
"""

EXAMPLE_NETWORKPOLICY = """apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-policy
spec:
  podSelector:
    matchLabels:
      app: db
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: api
    ports:
    - protocol: TCP
      port: 5432
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: kube-system
"""

EXAMPLE_INGRESS = """apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: site
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: site-svc
            port:
              number: 80
"""

EXAMPLE_POD_INIT_PROBES = """apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  initContainers:
  - name: init-db
    image: busybox
    command: ["sh", "-c", "until nc -z db 5432; do sleep 1; done"]
  containers:
  - name: app
    image: myapp:1.0
    ports:
    - containerPort: 8080
    livenessProbe:
      httpGet:
        path: /healthz
        port: 8080
      initialDelaySeconds: 10
      periodSeconds: 5
    readinessProbe:
      httpGet:
        path: /ready
        port: 8080
"""

EXAMPLE_SECRET = """apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
stringData:
  username: admin
  password: changeme
"""

EXAMPLE_DEPLOYMENT_INCOMPLETE = """# A Deployment missing selector and replicas β€” model should suggest both
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
      - name: api
        image: api:1.0
"""

EXAMPLE_RBAC_MULTIDOC = """# ClusterRole / PSP / ClusterRoleBinding bundle
# Source: kubernetes/examples staging/podsecuritypolicy/rbac/bindings.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: restricted-psp-user
rules:
- apiGroups:
  - policy
  resources:
  - podsecuritypolicies
  resourceNames:
  - restricted
  verbs:
  - use
---
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: restricted
spec:
  privileged: false
  fsGroup:
    rule: RunAsAny
  runAsUser:
    rule: MustRunAsNonRoot
  seLinux:
    rule: RunAsAny
  supplementalGroups:
    rule: RunAsAny
  volumes:
  - 'emptyDir'
  - 'secret'
  - 'downwardAPI'
  - 'configMap'
  - 'persistentVolumeClaim'
  - 'projected'
  hostPID: false
  hostIPC: false
  hostNetwork: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: restricted-psp-users
subjects:
- kind: Group
  apiGroup: rbac.authorization.k8s.io
  name: restricted-psp-users
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: restricted-psp-user
"""

_log("Building Gradio UI...")
_TILE_CSS = """
.demo-tile { display: flex !important; flex-direction: column !important; height: 100%; }
.demo-tile > .prose, .demo-tile > .markdown { flex: 1 1 auto; }
.demo-tile > button { margin-top: auto !important; }
"""
with gr.Blocks(title="YAML-BERT") as demo:
    gr.Markdown(
        f"""
# YAML-BERT β€” structural understanding of Kubernetes YAML

Code: [github.com/vimalk78/yaml-bert](https://github.com/vimalk78/yaml-bert) Β·
Trained with MLM + reconstruction on 276K K8s manifests Β·
{n_params:,} params

**This Space includes 3 demos β€” pick a tab below, or use the tiles on the Overview tab.**
"""
    )

    with gr.Tabs() as tabs:
        with gr.Tab("Overview", id="overview"):
            gr.Markdown("### Demos in this Space")
            with gr.Row():
                with gr.Column(elem_classes="demo-tile"):
                    gr.Markdown(
                        "#### 🧩 Missing-field suggester\n"
                        "Paste a YAML manifest; the model predicts which "
                        "structural fields it expects but you didn't include, "
                        "ranked by confidence."
                    )
                    open_suggester = gr.Button(
                        "Open missing-field suggester β†’", variant="primary"
                    )
                with gr.Column(elem_classes="demo-tile"):
                    gr.Markdown(
                        "#### 🌌 Manifest galaxy\n"
                        "10,000 K8s manifests projected to 2D from their "
                        "`doc_vec` embeddings. Kinds cluster spontaneously β€” "
                        "the model was never told what `kind` is."
                    )
                    open_galaxy = gr.Button(
                        "Open manifest galaxy β†’", variant="primary"
                    )
                with gr.Column(elem_classes="demo-tile"):
                    gr.Markdown(
                        "#### πŸ”¬ Structural probes\n"
                        "Preset manifest sets that test whether the model "
                        "has learned specific structural distinctions, "
                        "shown as a 2D layout. Add your own YAML to see "
                        "where it lands."
                    )
                    open_probes = gr.Button(
                        "Open structural probes β†’", variant="primary"
                    )

        with gr.Tab("Missing-field suggester", id="suggester"):
            gr.Markdown(
                "Paste a Kubernetes YAML manifest. The model walks each "
                "parent level, identifies fields it expects to see there "
                "but that are absent, and ranks the suggestions by confidence."
            )
            with gr.Row():
                with gr.Column(scale=1):
                    yaml_input = gr.Code(
                        language="yaml",
                        lines=22,
                        max_lines=100,
                        label="YAML input",
                        value=EXAMPLE_NGINX,
                    )
                    threshold = gr.Slider(
                        minimum=0.05, maximum=0.95, value=0.7, step=0.05,
                        label="Confidence threshold",
                    )
                    submit = gr.Button("Suggest missing fields", variant="primary")

                with gr.Column(scale=1):
                    output = gr.Markdown(label="Suggestions", value="")

            submit.click(fn=suggest, inputs=[yaml_input, threshold], outputs=output)
            # No auto-trigger on yaml_input.change β€” typing/pasting a long YAML
            # would fire many inference requests and back up the queue.

            _ALL_EXAMPLES = [
                EXAMPLE_NGINX,
                EXAMPLE_DEPLOYMENT_INCOMPLETE,
                EXAMPLE_INCOMPLETE_SERVICE,
                EXAMPLE_CONFIGMAP,
                EXAMPLE_SECRET,
                EXAMPLE_STATEFULSET,
                EXAMPLE_CRONJOB,
                EXAMPLE_HPA,
                EXAMPLE_NETWORKPOLICY,
                EXAMPLE_INGRESS,
                EXAMPLE_POD_INIT_PROBES,
                EXAMPLE_RBAC_MULTIDOC,
            ]
            gr.Examples(
                examples=[[y] for y in _ALL_EXAMPLES],
                example_labels=[_label_for_example(y) for y in _ALL_EXAMPLES],
                inputs=[yaml_input],
                examples_per_page=20,
                label="Example YAMLs",
            )

            gr.Markdown(
                """
---

### What it does well
- Predicts standard Kubernetes structural fields
- Distinguishes kind-specific fields (`Deployment.replicas` vs `Service.ports`)
- Calibrated confidence: strong on common patterns, weaker in ambiguous positions

### Known limitations
- Status-side fields are not well predicted
- Novel CRD instances and rare annotation keys may not work
- Trained on `substratusai/the-stack-yaml-k8s`
"""
            )

        with gr.Tab("Manifest galaxy", id="galaxy"):
            gr.Markdown(
                "Each point is one K8s manifest from the training corpus, "
                "embedded as a `doc_vec` by the bottom-up tree aggregator, "
                "then projected to 2D with UMAP (cosine metric). "
                "Manifests with similar structure end up near each other β€” "
                "the model has never been told what `kind` is, "
                "yet clusters of `Deployment`, `Service`, `ConfigMap` etc. "
                "form spontaneously."
            )
            if GALAXY_FIG is not None:
                gr.Plot(value=GALAXY_FIG, show_label=False)
            else:
                gr.Markdown("_Galaxy data unavailable._")
            gr.Markdown(
                "Hover for `kind / name / namespace`. "
                "Top 15 kinds are colored; everything else is gray. "
                "Click a legend entry to toggle that kind on/off."
            )

        with gr.Tab("Structural probes", id="probes"):
            gr.Markdown(
                "Pick a preset that explores a specific structural claim. "
                "The 2D plane is an MDS projection of the manifests' "
                "`doc_vecs` β€” **closer = more similar**. "
                "You can also paste your own YAML to see where it lands "
                "relative to the preset."
            )

            _initial_preset = PRESETS[0]
            _initial_items = PRESET_ITEMS_BY_ID[_initial_preset["id"]]

            preset_dd = gr.Dropdown(
                choices=[(p["title"], p["id"]) for p in PRESETS],
                value=_initial_preset["id"],
                label="Preset",
                interactive=True,
            )
            hypothesis_md = gr.Markdown(
                value=f"**Hypothesis:** {_initial_preset['hypothesis']}"
            )

            items_state = gr.State(value=_initial_items)

            with gr.Row():
                with gr.Column(scale=2):
                    plot = gr.Plot(
                        value=_build_preset_figure(_initial_items),
                        show_label=False,
                    )
                    verdict_md = gr.Markdown(
                        value=_verdict_markdown(_initial_preset, _initial_items)
                    )

                with gr.Column(scale=1):
                    gr.Markdown("**Manifests in this comparison**")

                    @gr.render(inputs=[items_state])
                    def _render_accordions(items):
                        if not items:
                            gr.Markdown("_No manifests._")
                            return
                        preset_id = items[0].get("preset_id", "")
                        n_preset = (len(PRESET_BY_ID[preset_id]["manifests"])
                                    if preset_id in PRESET_BY_ID else 0)
                        for i, it in enumerate(items):
                            is_user = i >= n_preset
                            label = f"[{it['letter']}] {it['name']}"
                            if is_user:
                                label += "  Β· added"
                            with gr.Accordion(label, open=False):
                                gr.Code(
                                    value=it["yaml"], language="yaml",
                                    lines=12, interactive=False,
                                )
                                if is_user:
                                    rm = gr.Button(
                                        f"Remove {it['letter']}",
                                        variant="secondary",
                                    )

                                    def _remove(state, idx=i):
                                        new = state[:idx] + state[idx + 1:]
                                        preset = PRESET_BY_ID.get(
                                            new[0]["preset_id"]) if new else None
                                        verdict = (_verdict_markdown(preset, new)
                                                   if preset else "")
                                        return (new,
                                                _build_preset_figure(new),
                                                verdict)
                                    rm.click(
                                        _remove,
                                        inputs=[items_state],
                                        outputs=[items_state, plot, verdict_md],
                                    )

                    gr.Markdown("---")
                    with gr.Accordion("βž• Add your own YAML", open=False):
                        new_yaml = gr.Code(
                            language="yaml", lines=10,
                            label="Paste a K8s manifest",
                        )
                        add_btn = gr.Button(
                            "Encode and add to comparison", variant="primary",
                        )
                        add_err = gr.Markdown("")

            def _on_add(state, yaml_text):
                if not yaml_text or not yaml_text.strip():
                    return state, _build_preset_figure(state), \
                        _verdict_markdown_for(state), \
                        "_Empty YAML β€” nothing to add._"
                if len(state) >= len(_PRESET_LETTERS):
                    return state, _build_preset_figure(state), \
                        _verdict_markdown_for(state), \
                        f"_Max {len(_PRESET_LETTERS)} manifests at once._"
                try:
                    vec = _encode_doc_vec(yaml_text)
                except Exception as e:
                    return state, _build_preset_figure(state), \
                        _verdict_markdown_for(state), \
                        f"_Encoding failed: `{type(e).__name__}: {e}`_"
                from yaml_bert.types import _extract_kind
                nodes = _LINEARIZER.linearize(yaml_text)
                kind = _extract_kind(nodes) or "?"
                preset_id = state[0]["preset_id"] if state else ""
                new_item = {
                    "letter": _PRESET_LETTERS[len(state)],
                    "name": f"{kind} (added)",
                    "yaml": yaml_text,
                    "vec": vec,
                    "preset_id": preset_id,
                }
                new_state = state + [new_item]
                return (new_state,
                        _build_preset_figure(new_state),
                        _verdict_markdown_for(new_state),
                        "")

            def _verdict_markdown_for(state):
                if not state:
                    return ""
                preset = PRESET_BY_ID.get(state[0].get("preset_id", ""))
                return _verdict_markdown(preset, state) if preset else ""

            def _on_preset_change(preset_id):
                if preset_id not in PRESET_BY_ID:
                    return gr.update(), gr.update(), gr.update(), gr.update()
                preset = PRESET_BY_ID[preset_id]
                items = PRESET_ITEMS_BY_ID[preset_id]
                return (items,
                        _build_preset_figure(items),
                        f"**Hypothesis:** {preset['hypothesis']}",
                        _verdict_markdown(preset, items))

            preset_dd.change(
                _on_preset_change,
                inputs=[preset_dd],
                outputs=[items_state, plot, hypothesis_md, verdict_md],
            )
            add_btn.click(
                _on_add,
                inputs=[items_state, new_yaml],
                outputs=[items_state, plot, verdict_md, add_err],
            )

    open_suggester.click(lambda: gr.Tabs(selected="suggester"), outputs=tabs)
    open_galaxy.click(lambda: gr.Tabs(selected="galaxy"), outputs=tabs)
    open_probes.click(lambda: gr.Tabs(selected="probes"), outputs=tabs)


_log("Gradio UI built β€” launching")

if __name__ == "__main__":
    # GRADIO_SHARE=true creates a temporary *.gradio.live tunnel.
    # Defaults off β€” Spaces deployment must stay local-bound.
    import os
    demo.launch(
        css=_TILE_CSS,
        share=os.environ.get("GRADIO_SHARE", "").lower() in ("1", "true", "yes"),
    )