File size: 71,356 Bytes
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fb75d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
e6404d0
0e778b6
 
 
 
 
 
e6404d0
 
 
 
0e778b6
e6404d0
0e778b6
 
 
e6404d0
 
 
 
0e778b6
e6404d0
 
 
 
 
0e778b6
e6404d0
 
 
0e778b6
e6404d0
0e778b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
e6404d0
 
 
 
 
0e778b6
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
e6404d0
0e778b6
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
0e778b6
e6404d0
 
 
 
0e778b6
e6404d0
 
 
 
0e778b6
 
 
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
e6404d0
 
0e778b6
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
0e778b6
 
e6404d0
 
0e778b6
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
 
 
 
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e778b6
 
 
 
 
 
e6404d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import random
import hashlib
import json as _json
import os as _os
from copy import deepcopy
from src.prompt_parser import ParsedPrompt
from src.tag_warehouse import TagWarehouse, MAX_RATING_MAP
from src.model_formatter import format_prompt, _is_score_tag
from src.tag_format import to_internal_tag, normalize_tag
from src.synonym_filter import apply_synonym_filter, has_synonym_conflict
from src.prompt_rewriter import get_tag_categories
from src.presets import PRESETS, get_preset_bundle_tags
from src.dedup_engine import smart_dedup
from src.synonym_data import _find_synonym_group, get_synonym_groups
from src.tag_searcher import has_human_subject, filter_subject_conflicts, get_cooccurrence_tags
from src.semantic_coherence import (
    semantic_pick_tags, split_core_decorative, detect_intent,
    compute_theme_budget, _THEME_GROUPS, SCORING,
)

CREATIVITY_SETTINGS = {
    "very_low": {
        "tags_per_category": (1, 1),
        "replacement_rate": 0.1,
        "shuffle_general": False,
        "concept_cross": False,
        "diversity_threshold": 0.5,
        "wildcard_categories": 0,
        "substitution_chance": 0.0,
    },
    "low": {
        "tags_per_category": (1, 2),
        "replacement_rate": 0.2,
        "shuffle_general": False,
        "concept_cross": False,
        "diversity_threshold": 0.4,
        "wildcard_categories": 0,
        "substitution_chance": 0.05,
    },
    "medium": {
        "tags_per_category": (2, 4),
        "replacement_rate": 0.3,
        "shuffle_general": False,
        "concept_cross": False,
        "diversity_threshold": 0.3,
        "wildcard_categories": 0,
        "substitution_chance": 0.1,
    },
    "high": {
        "tags_per_category": (3, 6),
        "replacement_rate": 0.4,
        "shuffle_general": True,
        "concept_cross": True,
        "diversity_threshold": 0.25,
        "wildcard_categories": 1,
        "substitution_chance": 0.15,
    },
    "very_high": {
        "tags_per_category": (4, 8),
        "replacement_rate": 0.5,
        "shuffle_general": True,
        "concept_cross": True,
        "diversity_threshold": 0.2,
        "wildcard_categories": 2,
        "substitution_chance": 0.2,
    },
    "extreme": {
        "tags_per_category": (5, 10),
        "replacement_rate": 0.6,
        "shuffle_general": True,
        "concept_cross": True,
        "diversity_threshold": 0.15,
        "wildcard_categories": 3,
        "substitution_chance": 0.3,
    },
}

CONFLICT_GROUPS = [
    {"from above", "from below", "from side", "from behind", "birds-eye view", "worms-eye view"},
    {"smile", "laughing", "serious", "angry", "sad", "crying", "surprised", "expressionless"},
    {"standing", "sitting", "lying", "kneeling", "running", "jumping", "dancing", "crouching"},
    {"simple background", "detailed background", "complex background", "gradient background"},
    {"day", "night", "twilight", "sunset", "sunrise"},
    {"portrait", "full body", "upper body", "lower body", "cowboy shot", "wide shot"},
    {"soft lighting", "hard lighting", "harsh lighting"},
    {"warm colors", "cool colors", "monochrome", "vibrant colors", "pastel colors", "dark colors", "neon palette"},
    {"looking at viewer", "looking away", "looking up", "looking down", "looking back"},
    {"sunlight", "moonlight"},
    {"cloudy sky", "starry sky", "clear sky"},
    {"misty", "foggy"},
    {"indoors", "outdoors"},
    {"innocent", "seductive smile"},
    {"rainy", "snowy"},
    {"close-up", "wide shot", "extreme close-up"},
    {"chibi", "photorealistic"},
    {"bloom", "soft focus"},
    {"underwater", "space", "cityscape"},
    {"hoodie", "poncho", "t-shirt", "crop top", "sweater", "jacket", "coat", "blazer", "vest", "cardigan", "blouse", "shirt", "tank top", "cape", "cloak", "robe", "dress", "kimono", "yukata", "qipao", "overalls", "suit", "armor"},
    {"jeans", "shorts", "skirt", "mini skirt", "leggings", "sweatpants", "trousers", "hot pants", "long skirt", "pleated skirt"},
    {"shoes", "boots", "sandals", "sneakers", "heels", "loafers", "flip-flops", "socks", "thighhighs", "kneehighs"},
    {"hat", "cap", "beanie", "crown", "hood", "veil", "witch hat", "tara", "hairband", "headband", "maid headdress", "cat ears", "fox ears", "animal ears"},
    {"confident", "shy", "timid", "bashful", "embarrassed", "proud", "self-assured"},
]


_CONFLICT_INDEX = None
_CONFLICT_ONLY_INDEX = None


def _build_conflict_index() -> dict[str, set]:
    global _CONFLICT_INDEX
    global _CONFLICT_ONLY_INDEX
    index: dict[str, set] = {}
    only: dict[str, set] = {}
    for group in CONFLICT_GROUPS:
        for member in group:
            ml = member.lower().strip()
            index[ml] = group
            only[ml] = group
    for group in get_synonym_groups():
        for member in group:
            ml = member.lower().strip()
            if ml in index:
                index[ml] = index[ml] | group
            else:
                index[ml] = group
    _CONFLICT_INDEX = index
    _CONFLICT_ONLY_INDEX = only
    return _CONFLICT_INDEX


def _find_conflict_group(tag: str) -> set | None:
    global _CONFLICT_INDEX
    if _CONFLICT_INDEX is None:
        _build_conflict_index()
    return _CONFLICT_INDEX.get(tag.lower().strip())


def _find_conflict_only_group(tag: str) -> set | None:
    """Conflict group WITHOUT synonym members.

    Used for negative-prompt inversion: a synonym of a desired tag shares its
    meaning, so it must NOT be negated (that would fight the positive prompt).
    """
    global _CONFLICT_ONLY_INDEX
    if _CONFLICT_ONLY_INDEX is None:
        _build_conflict_index()
    return _CONFLICT_ONLY_INDEX.get(tag.lower().strip())


def _find_conflicts(tag: str, existing: list[str]) -> set[str]:
    group = _find_conflict_group(tag)
    if group is None:
        return set()
    existing_lower = {e.lower().strip() for e in existing}
    conflicting = group & existing_lower
    return {e for e in existing if e.lower().strip() in conflicting}


def _resolve_and_replace(tag: str, existing: list[str], warehouse=None, protected=None) -> tuple[list[str], bool]:
    tl = tag.lower().strip()
    protected = protected or set()
    existing_lower = {e.lower().strip() for e in existing}
    conflicting = _find_conflicts(tag, existing)
    # Exclude the tag itself (case-insensitive dup) from conflict resolution.
    conflicting = {e for e in conflicting if e.lower().strip() != tl}
    if warehouse:
        for e in existing:
            if warehouse.has_conflict(tag, [e]):
                conflicting.add(e)
    # Never remove a protected (user/core) tag. If the only conflict is protected,
    # drop the incoming tag instead so user intent is always preserved.
    for e in conflicting:
        if e.lower().strip() in protected:
            return existing, False
    already = tl in existing_lower
    if not conflicting and already:
        return existing, False
    out = [e for e in existing if e not in conflicting]
    if not already:
        out.append(tag)
    return out, not already


def _substitute_at(result: list[str], i: int, best: str, warehouse=None, protected=None) -> list[str]:
    """Replace result[i] with best, preserving conflict removal from _resolve_and_replace.

    _resolve_and_replace returns the full list with conflicting tags removed; the
    substitution caller must use that list (not just overwrite position i) or the
    removed conflict would silently reappear at its original position.
    """
    other = [t for j, t in enumerate(result) if j != i]
    out, ok = _resolve_and_replace(best, other, warehouse, protected)
    if not ok:
        return result
    new_result = []
    for j, t in enumerate(result):
        if j == i:
            new_result.append(best)
        elif t in out:
            new_result.append(t)
    return new_result


def _extract_artists_from_general(variant, known_artists: dict[str, str]) -> None:
    """Move tags that match known artist names into ``variant.artists``.

    Operates in place on ``variant.general_tags``. ``known_artists`` MUST be
    built once per generation call (it is independent of the variation loop).
    """
    skip = {
        (variant.subject or "").lower().strip(),
        (variant.character or "").lower().strip(),
        (variant.series or "").lower().strip(),
    }
    skip.discard("")
    remaining = []
    for tag in variant.general_tags:
        tl = tag.lower().strip()
        if tl in skip:
            continue
        matched = known_artists.get(tl)
        if matched and matched not in variant.artists:
            variant.artists.append(matched)
        else:
            remaining.append(tag)
    variant.general_tags = remaining


def _min_diversity_index(tags1: list[str], tags2: list[str]) -> float:
    if not tags1 or not tags2:
        return 1.0
    s1 = {t.lower().strip() for t in tags1}
    s2 = {t.lower().strip() for t in tags2}
    diff = (s1 | s2) - (s1 & s2)
    return len(diff) / max(len(s1 | s2), 1)


# --- Smart balancing helpers (booru best practices) ---

# Restrictive metadata tags stripped from positive prompts
# Auto-stripped "noise / restrictive / metadata" tags (mirrors Booru Prompt
# Gallery's "removes metadata / restrictive tags" behavior + our extensions).
RESTRICTIVE_TAGS = frozenset({
    "white background", "simple background", "black background",
    "transparent background", "grey background", "gray background",
    "censor", "censored", "mosaic censorship", "censorship",
    "web address", "patreon logo", "patreon username",
    "commentary request", "translated", "english text",
    # --- extended metadata / artifact strip (C) ---
    "watermark", "artist name", "signature", "edited", "edit",
    "cropped", "crop", "duplicate", "disapproved", "resized",
    "compressed", "real life", "photograph", "photo", "raw image",
    "source image", "screencap", "screenshot", "scanned",
    "recycled", "upscaled", "downscaled", "downsampling",
    "high resolution", "low resolution", "4k", "8k", "12k",
    "deformed", "bad art", "worst quality", "low quality",
})

# Canonical alias map (Booru Tag Gallery "Alias Resolver", G). Maps common
# non-canonical spellings to the booru-standard tag. Applied during cleaning.
# NOTE: Danbooru canon is `blonde hair` (NOT `yellow hair`) — that is a common
# heuristic mistake; aliases below only canonicalize well-known, unambiguous
# spellings, and never overwrite an official booru tag with a non-booru one.
_BOORU_ALIASES = {
    "blond hair": "blonde hair",
    "blonde hair": "blonde hair",
    "blonde_hair": "blonde hair",
    "blond": "blonde hair",
    "grey hair": "gray hair",
    "grey eyes": "gray eyes",
    "grey background": "gray background",
    "grey skin": "gray skin",
    "platinum hair": "white hair",
    "silver hair": "white hair",
    "violet hair": "purple hair",
    "lavender hair": "purple hair",
    "scarlet hair": "red hair",
    "crimson hair": "red hair",
    "azure hair": "blue hair",
    "light blue hair": "aqua hair",
    "cyan hair": "aqua hair",
    "turquoise hair": "aqua hair",
    "magenta hair": "pink hair",
    "rose hair": "pink hair",
    "pink-colored": "pink",
    "coloured skin": "colored skin",
    "colored eyes": "colored pupils",
    "heterochromia eyes": "heterochromia",
    "mismatched eyes": "heterochromia",
    "two-tone hair": "multicolored hair",
    "two toned hair": "multicolored hair",
    "gradient hair": "multicolored hair",
    "ombre hair": "multicolored hair",
    "multicolor eyes": "heterochromia",
    "expressionless face": "expressionless",
    "looking back": "looking at viewer",  # canonical spike
    "looking_at_viewer": "looking at viewer",  # pose tagger outputs underscore
    "looking_away": "looking away",  # pose tagger outputs underscore
    "looking_up": "looking up",
    "looking_down": "looking down",
    "looking_back": "looking at viewer",
    "closed_eyes": "eyes closed",
    "arms_up": "arms up",
    "arms_behind_head": "arms behind head",
    "arms_at_sides": "arms at sides",
    "arms_crossed": "arms crossed",
    "arms_behind_back": "arms behind back",
    "arms_around_neck": "arms around neck",
    "hands_on_hips": "hands on hips",
    "hand_on_hip": "hand on hip",
    "hand_on_own_face": "hand on own face",
    "hand_on_own_chest": "hand on own chest",
    "hand_on_own_stomach": "hand on own stomach",
    "hand_in_pocket": "hand in pocket",
    "hands_in_pockets": "hands in pockets",
    "covering_face": "covering face",
    "head_tilt": "head tilt",
    "one_arm_up": "one arm up",
    "one_leg_up": "one leg up",
    "standing_on_one_leg": "standing on one leg",
    "on_all_fours": "on all fours",
    "kneeling_on_one_knee": "kneeling on one knee",
    "crossed_legs": "crossed legs",
    "legs_apart": "legs apart",
    "close up": "close-up",
    "extreme close up": "extreme close-up",
    "upper body": "upper body",
    "lower body": "lower body",
    "full body": "full body",
    "cowboy shot": "cowboy shot",
    "dutch angle": "dutch angle",
    "birds eye view": "bird's-eye view",
    "birds-eye view": "bird's-eye view",
    "worms eye view": "worm's-eye view",
    "worms-eye view": "worm's-eye view",
    "white background": "white background",
    "simple background": "simple background",
    "gradient background": "gradient background",
    "detailed background": "detailed background",
    "blurry background": "blurry background",
    "blurred background": "blurry background",
    "starry sky": "starry sky",
    "cloudy sky": "cloudy sky",
    "clear sky": "clear sky",
    "night sky": "night sky",
    "starry sky": "starry sky",  # canonical
    "sunny": "sunny",
    "rainy": "rainy",
    "snowy": "snowy",
    "foggy": "foggy",
    "misty": "foggy",
    "overcast": "cloudy sky",
    "golden hour": "golden hour",
    "blue hour": "dusk",
    "twilight": "dusk",
    "dawn": "sunrise",
    "golden lighting": "golden hour",
    "dramatic lighting": "dramatic lighting",
    "cinematic lighting": "cinematic lighting",
    "volumetric lighting": "volumetric lighting",
    "soft lighting": "soft lighting",
    "hard lighting": "hard lighting",
    "harsh lighting": "hard lighting",
    "studio lighting": "studio lighting",
    "natural lighting": "natural lighting",
    "neon lighting": "neon lighting",
    "glowing": "glowing",
    "lens flare": "lens flare",
    "bloom": "bloom",
    "depth of field": "depth of field",
    "bokeh": "bokeh",
    "chromatic aberration": "chromatic aberration",
    "film grain": "film grain",
    "vignette": "vignette",
    "motion blur": "motion blur",
    "sharp focus": "sharp focus",
    "soft focus": "soft focus",
}

# Token ceiling for one variation (Anima/Illustrious sweet spot ~75).
MAX_TOKENS_DEFAULT = 75

FX_CATEGORIES = ["effects", "special_fx", "lighting", "atmosphere"]

# Negative-quality / source-metadata tags that must never land in a positive prompt.
_NEG_QUALITY_BAD = frozenset({
    "worst quality", "bad quality", "low quality", "worst aesthetic",
    "worst score", "low score", "average score",
    "displeasing", "very displeasing", "bad aesthetic", "normal quality",
})


def _is_negative_quality(tag: str) -> bool:
    tl = tag.lower().strip()
    if tl in _NEG_QUALITY_BAD:
        return True
    if "displeasing" in tl:
        return True
    if tl.startswith("worst") or tl.startswith("low ") or tl.startswith("bad "):
        return True
    if tl.startswith("score_"):
        try:
            num = int(tl.split("_", 1)[1])
        except (ValueError, IndexError):
            return False
        return num < 7
    if tl.startswith("source_"):
        return True
    return False


# Categories whose tags describe the subject's fixed design (identity) rather
# than flexible scene/ambiance. Used by Full Rewrite to keep the concept while
# rebuilding everything else.
_DESIGN_CATS = {
    "quality", "expression", "hair", "body", "pose", "clothing",
    "background", "lighting", "effects", "atmosphere", "colors",
    "composition", "style",
}

# Semantic role priority for final tag ordering (lower = earlier in prompt).
# SD gives earlier tokens more attention, so identity/composition must lead
# and ambiance/effects must trail; unknown categories stay in a stable tail.
_TAG_ORDER_PRIORITY = {
    "quality": 0, "year_meta": 0,
    "composition": 1, "framing": 1,
    "pose": 2, "expression": 2,
    "body": 3, "hair": 3, "eyes": 3, "colors": 3, "face": 3, "makeup": 3,
    "accessory": 4, "clothing": 4,
    "background": 5, "architecture": 5, "season": 5, "atmosphere": 5, "weather": 5,
    "lighting": 6, "color_grading": 6,
    "effects": 7, "special_fx": 7,
    "style": 8, "bloom": 8,
    "object": 9, "food": 9, "weapon": 9, "vehicle": 9,
    "demon": 10, "angelic": 10, "magic": 10,
    "animal": 11, "furry": 11,
    "nsfw": 12,
    "horror": 13, "fantasy": 13, "cyberpunk": 13, "gothic": 13,
    "steampunk": 13, "noir": 13, "retro": 13, "kawaii": 13,
    "watercolor": 13, "space": 13, "underwater": 13, "warrior": 13,
    "magical_girl": 13,
}


def _smart_order_tags(tags: list[str]) -> list[str]:
    """Stable-sort tags by semantic role so identity/composition lead the prompt.

    Stable sort preserves the existing order inside each role group (e.g. the
    order the user wrote their hair/eye tags). Tags with no known category
    (subject names like ``1girl``, character tags) rank at the front so user
    intent keeps attention; genuinely unknown additions fall to the tail.
    """
    def _rank(t: str) -> int:
        cats = get_tag_categories(t)
        if not cats:
            return 1
        return min(_TAG_ORDER_PRIORITY.get(c, 50) for c in cats)

    return sorted(tags, key=_rank)


def _protected_set(parsed: ParsedPrompt, design_only: bool = False) -> set[str]:
    """Tags that must never be removed or overwritten by conflict resolution / budgeting.

    design_only=False (Standard Varry): protect the user's subject, character,
    series, artists, quality tags AND every explicit general tag they wrote, so
    variations only ADD variety and never erase the user's intent.
    design_only=True (Full Rewrite): protect subject/character/series + only the
    design-category general tags, letting the rest of the prompt be rebuilt.
    """
    p: set[str] = set()
    if parsed.subject:
        p.add(parsed.subject.lower().strip())
    if parsed.character:
        for c in parsed.character.split(","):
            c = c.strip()
            if c:
                p.add(c.lower())
    if parsed.series:
        p.add(parsed.series.lower().strip())
    for a in (parsed.artists or []):
        p.add(a.lower().strip())
    for q in (parsed.quality_tags or []):
        p.add(q.lower().strip())
    for t in (parsed.general_tags or []):
        tl = t.lower().strip()
        if design_only:
            cats = get_tag_categories(t)
            if any(c in _DESIGN_CATS for c in cats):
                p.add(tl)
        else:
            p.add(tl)
    return p


def _head(tag: str) -> str:
    """Last whitespace-separated token of a tag (its head noun), lower-cased."""
    parts = tag.split()
    return parts[-1].lower() if parts else tag.lower()


import re as _re

_JUNK_RE = _re.compile(r"(//|cid=|[<>]|[\"'`])")


def _clean_general_tags(tags: list[str]) -> list[str]:
    """Strip crawler/UI artifacts and normalize spaced score tags.

    e.g. '0.4//cid=12>' -> dropped, 'score 9' -> 'score_9'. Keeps the user's
    meaningful tags intact so downstream generation stays clean.
    """
    out = []
    for t in tags:
        tl = t.strip()
        if not tl:
            continue
        m = _re.fullmatch(r"score\s+(\d+)", tl, _re.I)
        if m:
            out.append(f"score_{m.group(1)}")
            continue
        if _re.fullmatch(r"\d+(\.\d+)?", tl):
            continue
        if _JUNK_RE.search(tl):
            continue
        # Normalize booru underscores to the spaced canonical form (except
        # score_N) so category / co-occurrence / conflict lookups match and so
        # user tags and injected tags share one consistent surface form. This
        # is what prevents mixed "looking_at_viewer, magical girl pose" output.
        tl = to_internal_tag(tl)
        # Alias Resolver (G): canonicalize common non-standard spellings.
        alias = _BOORU_ALIASES.get(tl.lower())
        if alias:
            tl = alias
        out.append(tl)
    return out


def _is_known_tag(tag: str) -> bool:
    """True if the tag is a recognized pool/category tag (vs a user-specific name)."""
    return bool(get_tag_categories(tag))


def _normalize_exclude(exclude_tags: list[str] | None) -> set[str]:
    if not exclude_tags:
        return set()
    return {t.lower().strip() for t in exclude_tags if t and t.strip()}


def _apply_strip_flags(
    parsed: "ParsedPrompt",
    warehouse: "TagWarehouse",
    strip_quality: bool = False,
    strip_artist: bool = False,
    strip_lora: bool = False,
    strip_meta: bool = False,
) -> "ParsedPrompt":
    """Apply the B (cleanup toggles) flags to a parsed prompt in place.

    - strip_quality: drop quality tokens from general + quality_tags
    - strip_artist:  drop artist entries (so they are not protected either)
    - strip_lora:    drop LoRA/embed trigger tokens (':', '<', '>')
    - strip_meta:    drop meta tokens
    """
    if strip_quality:
        parsed.quality_tags = []
        parsed.general_tags = [
            t for t in parsed.general_tags
            if not ("quality" in t.lower() or "masterpiece" in t.lower() or _is_score_tag(t))
        ]
    if strip_artist:
        known_artists = {a["tag"].lower().strip() for a in warehouse.get_all_artists()}
        parsed.artists = []
        parsed.general_tags = [
            t for t in parsed.general_tags if t.lower().strip() not in known_artists
        ]
    if strip_lora:
        def _is_lora(t: str) -> bool:
            tl = t.lower()
            if ":" in tl or "<" in tl or ">" in tl:
                return True
            if "lora" in tl or "loha" in tl or "lycoris" in tl or "embedding" in tl:
                return True
            return False
        parsed.general_tags = [t for t in parsed.general_tags if not _is_lora(t)]
    if strip_meta:
        parsed.meta_tags = []
    return parsed


def _apply_blacklist(tags: list[str], exclude: set[str]) -> list[str]:
    if not exclude:
        return tags
    return [t for t in tags if t.lower().strip() not in exclude]


def _ensure_min_tags(
    tags: list[str],
    min_tags: int,
    warehouse: "TagWarehouse",
    protected: set[str],
    user_heads: set[str],
    exclude: set[str],
    max_rating: str,
    rng: "random.Random",
    parsed: "ParsedPrompt | None" = None,
    intent: str | None = None,
) -> list[str]:
    """Top up a tag list to at least `min_tags` (D).

    Candidates are drawn from the tag pools and selected through the semantic
    picker (intent/co-occurrence/harmony), so the fill tags are contextually
    relevant instead of being random pool noise.
    """
    if min_tags <= 0:
        return tags
    out = list(tags)
    used = {t.lower().strip() for t in out} | exclude
    candidates: list[str] = []
    cats = [c for c in warehouse.pools if c not in ("nsfw", "furry")]
    rng.shuffle(cats)
    for cat in cats:
        if len(candidates) >= min_tags * 4:
            break
        pool = warehouse.get_pool(cat)
        if pool is None:
            continue
        for tag in pool.get_all_tags(max_rating=max_rating):
            tl = tag.lower().strip()
            if tl in used:
                continue
            if _is_negative_quality(tag):
                continue
            if has_synonym_conflict(tag, out + candidates):
                continue
            if _head(tag) in user_heads and tl not in protected:
                continue
            candidates.append(tag)
            used.add(tl)
            if len(candidates) >= min_tags * 4:
                break
    if not candidates:
        return out
    need = min_tags - len(out)
    if need <= 0:
        return out
    attempts = 0
    while len(out) < min_tags and candidates and attempts < min_tags * 6:
        attempts += 1
        if parsed is None:
            picked = rng.sample(candidates, min(need, len(candidates)))
        else:
            picked = semantic_pick_tags(candidates, need, parsed, rng, set(), list(out), intent=intent)
        added_any = False
        for tag in picked:
            if len(out) >= min_tags:
                break
            new_out, was_added = _resolve_and_replace(tag, out, warehouse, protected)
            if was_added:
                out = new_out
                added_any = True
        if not added_any:
            # All current picks were rejected (conflicts) — drop them and retry.
            candidates = [c for c in candidates if c not in picked]
        need = min_tags - len(out)
    return out


def _remove_intra_conflicts(tags: list[str], warehouse: TagWarehouse, protected: set[str]) -> list[str]:
    """Final safety pass: ensure no two tags in the result conflict.

    Protected (user/core) tags win; a later non-protected conflicting tag is
    dropped, and a later protected tag removes an earlier non-protected conflict.
    When BOTH tags are protected (the user's own explicit choices) we keep both
    rather than silently dropping one of the user's tags. Generation paths that
    append directly (tandems, artist signatures, fx) may bypass per-add conflict
    resolution, so this guarantees a clean prompt.
    """
    from src.semantic_coherence import _scene_conflict

    kept: list[str] = []
    for t in tags:
        tl = t.lower().strip()
        drop = False
        for k in list(kept):
            if warehouse.has_conflict(t, [k]) or _scene_conflict(tl, k.lower().strip()):
                kp = k.lower().strip()
                if tl in protected and kp in protected:
                    continue  # both are user intent: keep both
                if tl in protected and kp not in protected:
                    kept.remove(k)
                else:
                    drop = True
                    break
        if not drop:
            kept.append(t)
    return kept


def _estimate_tokens(tags: list[str]) -> int:
    """CLIP-style estimate: booru tag ≈ words×0.75 + 1 separator token."""
    n = 0
    for t in tags:
        words = len(t.replace("_", " ").split())
        n += max(1, int(words * 0.75)) + 1
    return n


def _category_token_budget(
    resolved_categories: list[str],
    settings: dict,
    warehouse: TagWarehouse,
    max_rating: str,
    max_tokens: int,
) -> dict[str, int]:
    """Allocate per-category tag counts so the estimated token cost fits max_tokens.

    Categories with longer tags (more tokens) get fewer slots; the allocation is
    proportional to the category's base share so no single category can blow the
    budget before _balance_variation has to pop tags from the tail.
    """
    budgets: dict[str, int] = {}
    if not resolved_categories or max_tokens <= 0:
        return budgets
    min_t, max_t = settings["tags_per_category"]
    base = (min_t + max_t) / 2.0
    weights: dict[str, float] = {}
    for cat in resolved_categories:
        pool = warehouse.get_pool(cat)
        if pool is None:
            continue
        sample = pool.get_all_tags(max_rating=max_rating)[:200]
        if not sample:
            continue
        avg_cost = sum(_estimate_tokens([t]) for t in sample) / len(sample)
        weights[cat] = max(avg_cost, 1.0)
    if not weights:
        return budgets
    total_weight = sum(base * w for w in weights.values())
    if total_weight <= 0:
        return budgets
    scale = max_tokens / total_weight
    for cat, w in weights.items():
        budgets[cat] = max(min_t, min(max_t, int(base * scale)))
    return budgets


def _tag_theme(tag: str) -> str:
    cats = set(get_tag_categories(tag))
    for theme, cset in _THEME_GROUPS.items():
        if cats & cset:
            return theme
    return "misc"


def _balance_variation(
    tags: list[str],
    protected_lower: set[str],
    theme_budget: dict[str, int] | None,
    max_tokens: int,
) -> list[str]:
    """Trim decorative tags so no theme dominates and the token budget is respected.
    Protected (subject/character/series/artist/quality) tags are always kept."""
    protected = [t for t in tags if t.lower().strip() in protected_lower]
    decorative = [t for t in tags if t.lower().strip() not in protected_lower]

    if theme_budget:
        theme_of: dict[str, str] = {}
        counts: dict[str, int] = {}
        for t in decorative:
            th = _tag_theme(t)
            theme_of[t.lower().strip()] = th
            counts[th] = counts.get(th, 0) + 1
        for th, budget in theme_budget.items():
            over = counts.get(th, 0) - budget
            if over <= 0:
                continue
            removed = 0
            kept = []
            for t in reversed(decorative):
                if removed < over and theme_of.get(t.lower().strip()) == th:
                    removed += 1
                    continue
                kept.append(t)
            decorative = list(reversed(kept))

    if max_tokens and _estimate_tokens(protected + decorative) > max_tokens:
        while decorative and _estimate_tokens(protected + decorative) > max_tokens:
            decorative.pop()

    return protected + decorative


def _apply_fx_layer(
    new_general: list[str],
    parsed: ParsedPrompt,
    warehouse: TagWarehouse,
    rng: random.Random,
    fx_count: int,
    protected_lower: set[str],
    used: set[str],
    max_rating: str,
) -> list[str]:
    """Add an FX tag layer (effects/special_fx/lighting/atmosphere), co-occurrence
    matched to the prompt where possible. Protected tags are never displaced."""
    if fx_count <= 0:
        return new_general
    fx_cats = [c for c in FX_CATEGORIES if warehouse.get_pool(c)]
    if not fx_cats:
        return new_general
    related: set[str] = set()
    if parsed.general_tags:
        for g in parsed.general_tags:
            for r in get_cooccurrence_tags(g, limit=10):
                rt = (r.get("tag") or "").lower().strip()
                if rt:
                    related.add(rt)
    added = 0
    attempts = 0
    while added < fx_count and attempts < fx_count * 8 and fx_cats:
        cat = rng.choice(fx_cats)
        pool = warehouse.get_pool(cat)
        cands = pool.get_all_tags(max_rating=max_rating)
        if not cands:
            attempts += 1
            continue
        preferred = [c for c in cands if c.lower().strip() in related]
        pool_choice = preferred if preferred and rng.random() < 0.7 else cands
        tag = rng.choice(pool_choice)
        tl = tag.lower().strip()
        if tl in used or tl in protected_lower or _is_negative_quality(tag):
            attempts += 1
            continue
        new_general, ok = _resolve_and_replace(tag, new_general, warehouse, protected_lower)
        if ok:
            added += 1
            used.add(tl)
        attempts += 1
    return new_general


def _score_tag_context(
    tag: str,
    parsed: ParsedPrompt,
) -> float:
    """Word-boundary context match between tag and user intent fields."""
    score = 0.0
    tag_words = set(tag.lower().replace("_", " ").split())
    context_sources: list[str] = []
    if parsed.subject:
        context_sources.append(parsed.subject.lower().strip())
    if parsed.character:
        context_sources.append(parsed.character.lower().strip())
    if parsed.series:
        context_sources.append(parsed.series.lower().strip())
    tag_cats = get_tag_categories(tag)
    for ctx in context_sources:
        ctx_words = set(ctx.replace("_", " ").split())
        if ctx_words & tag_words:
            score += 2.0
        ctx_cats = get_tag_categories(ctx)
        if tag_cats and ctx_cats and (set(tag_cats) & set(ctx_cats)):
            score += 1.0
    return min(score, SCORING["context_score_cap"])


def _cooccurrence_bonus(tag: str, context_tags: list[str]) -> float:
    """Sum of co-occurrence weights between tag and already-selected tags."""
    if not context_tags:
        return 0.0
    related = get_cooccurrence_tags(tag, limit=20)
    if not related:
        return 0.0
    related_map = {}
    for r in related:
        rt = (r.get("tag") or "").lower().strip()
        if rt:
            related_map[rt] = r.get("weight", 1.0)
    bonus = 0.0
    for ctx_tag in context_tags:
        cl = ctx_tag.lower().strip()
        if cl in related_map:
            bonus += float(related_map[cl])
    return min(bonus, 5.0)


def _pick_tags_weighted(
    candidates: list[str],
    count: int,
    parsed: ParsedPrompt,
    rng: random.Random,
    used_globals: set[str],
    selected_tags: list[str] | None = None,
    intent: str | None = None,
) -> list[str]:
    """Unified tag picker: delegates to semantic_pick_tags for context-aware selection."""
    return semantic_pick_tags(candidates, count, parsed, rng, used_globals, selected_tags, intent=intent)


def _smart_substitution(
    tags: list[str],
    chance: float,
    rng: random.Random,
    parsed: ParsedPrompt | None = None,
    warehouse: TagWarehouse | None = None,
    resolved_categories: list[str] | None = None,
    core_tags: set[str] | None = None,
    protected: set[str] | None = None,
) -> list[str]:
    """Context-aware substitution with cross-category fallback and scoring."""
    result = list(tags)
    result_lower = {t.lower().strip() for t in result}

    # Pre-compute category pools (tag + categories) once
    pool_cache: dict[str, list[tuple[str, list[str]]]] = {}
    if warehouse:
        for cat in (resolved_categories or []):
            pool = warehouse.get_pool(cat)
            if pool is None:
                continue
            entries = [(pt, pt.lower().strip(), get_tag_categories(pt))
                       for pt in pool.get_all_tags(max_rating="explicit")]
            pool_cache[cat] = entries

    for i, tag in enumerate(result):
        # Protect core + user-intent tags from substitution
        if core_tags and tag.lower().strip() in core_tags:
            continue
        if protected and tag.lower().strip() in protected:
            continue
        if rng.random() >= chance:
            continue
        tl = tag.lower().strip()
        candidates = []

        # 1. Synonym alternatives from same group
        group = _find_synonym_group(tag)
        substituted = False
        if group:
            for t in group:
                alt = t.lower().strip()
                if alt != tl and alt not in result_lower:
                    candidates.append(t)
            if len(candidates) >= 5:
                rng.shuffle(candidates)
                best = max(candidates, key=lambda c: (
                    _score_tag_context(c, parsed) if parsed else 0.0
                ))
                result = _substitute_at(result, i, best, warehouse, protected)
                result_lower = {t.lower().strip() for t in result}
                substituted = True
        if substituted:
            continue

        # 2. Cross-category: scan only categories the tag belongs to (not all resolved)
        if pool_cache:
            tag_cats = get_tag_categories(tag)
            if tag_cats:
                for cat in pool_cache:
                    if cat not in tag_cats:
                        continue
                    for pt, ptl, pt_cats in pool_cache[cat][:30]:
                        if ptl == tl or ptl in result_lower:
                            continue
                        if not (set(tag_cats) & set(pt_cats)):
                            continue
                        candidates.append(pt)

        if not candidates:
            continue

        # 3. Score and pick best
        other_tags = [t for j, t in enumerate(result) if j != i]
        best = None
        best_score = float("-inf")
        for cand in candidates:
            base = _score_tag_context(cand, parsed) if parsed else 0.0
            cooc = _cooccurrence_bonus(cand, other_tags)
            penalty = 0.0
            cand_syn = _find_synonym_group(cand)
            if cand_syn:
                for ot in other_tags:
                    if ot.lower().strip() in cand_syn:
                        penalty = 3.0
                        break
            syn_bonus = 1.0 if group and cand in group else 0.0
            total = base + cooc + syn_bonus - penalty + rng.uniform(0, 0.3)
            if total > best_score:
                best_score = total
                best = cand

        if best is None:
            continue

        result = _substitute_at(result, i, best, warehouse, protected)
        result_lower = {t.lower().strip() for t in result}

    return result


def _pick_random_tandem(rng: random.Random, warehouse: TagWarehouse) -> list[str]:
    tandems = warehouse.get_all_tandems()
    if not tandems:
        return []
    tandem = rng.choice(tandems)
    artists = tandem.get("artists", [])
    tags = list(artists)
    for aname in artists:
        sig = warehouse.get_artist_signature_tags(aname)
        tags.extend(sig)
    return tags


def _pick_style_tandem(rng: random.Random, warehouse: TagWarehouse, artist_style: str) -> list[str]:
    """Pick a tandem matching the given art style; fall back to random."""
    tandems = warehouse.get_all_tandems()
    if not tandems:
        return []
    if artist_style:
        style_artists = warehouse.get_artists_by_style(artist_style)
        if style_artists:
            style_names = {a["tag"].lower().strip() for a in style_artists}
            matching = [t for t in tandems if any(a.lower().strip() in style_names for a in t.get("artists", []))]
            if matching:
                tandem = rng.choice(matching)
                artists = tandem.get("artists", [])
                tags = list(artists)
                for aname in artists:
                    sig = warehouse.get_artist_signature_tags(aname)
                    tags.extend(sig)
                return tags
    return _pick_random_tandem(rng, warehouse)


def _compute_tag_weights(
    warehouse: TagWarehouse,
    selected_artists: list[str] | None,
) -> dict[str, float]:
    all_a = warehouse.get_all_artists()
    max_pop = max((a.get("popularity", 0) for a in all_a), default=100)
    weights = {}
    for a in all_a:
        pop = a.get("popularity", 0)
        name = a["tag"].lower().strip()
        w = 1.0 + (pop / max_pop) * 0.4
        weights[name] = round(min(max(w, 1.0), 1.4), 2)
    if selected_artists:
        for name in selected_artists:
            w = weights.get(name.lower().strip(), 1.2)
            weights[name.lower().strip()] = max(w, 1.2)
    return weights


def _pick_wildcard_categories(
    available: list[str],
    count: int,
    parsed: ParsedPrompt,
    rng: random.Random,
) -> list[str]:
    """Pick wildcard categories contextually based on user prompt tags.

    Noise is low enough (0.2) that category alignment still dominates but the
    choice is not fully deterministic across variations.
    """
    if not available or count <= 0:
        return []
    cat_scores: dict[str, float] = {}
    for tag in parsed.general_tags:
        for cat in get_tag_categories(tag):
            cat_scores[cat] = cat_scores.get(cat, 0) + 2.0
    if parsed.subject:
        for cat in get_tag_categories(parsed.subject):
            cat_scores[cat] = cat_scores.get(cat, 0) + 1.0
    scored = [(cat, cat_scores.get(cat, 0.0) + rng.uniform(0, SCORING["noise_max"])) for cat in available]
    scored.sort(key=lambda x: -x[1])
    return [c for c, _ in scored[:count]]


def _adjust_settings_by_prompt_length(
    settings: dict,
    parsed: ParsedPrompt,
    total_avail_pools: int,
) -> dict:
    """Adjust creativity settings based on prompt length."""
    adjusted = dict(settings)
    tag_count = len(parsed.general_tags or [])
    if tag_count <= 2:
        min_t, max_t = adjusted["tags_per_category"]
        adjusted["tags_per_category"] = (min_t + 1, max(max_t + 1, min_t + 2))
        adjusted["wildcard_categories"] = min(adjusted["wildcard_categories"] + 1, total_avail_pools)
        adjusted["replacement_rate"] = min(adjusted["replacement_rate"] + 0.1, 0.8)
    elif tag_count >= 12:
        min_t, max_t = adjusted["tags_per_category"]
        adjusted["tags_per_category"] = (max(1, min_t - 1), max(1, max_t - 1))
        adjusted["replacement_rate"] = max(0.0, adjusted["replacement_rate"] - 0.1)
    return adjusted


def generate_variations(
    parsed: ParsedPrompt,
    selected_categories: list[str],
    num_variations: int = 5,
    creativity: str = "medium",
    model: str = "anima",
    rating: str = "pg",
    warehouse: TagWarehouse = None,
    artist_style: str = "",
    selected_artists: list[str] | None = None,
    use_tandems: bool = False,
    selected_tandem: dict | None = None,
    weight_mode: str = "off",
    mode: str = "standard",
    web_enrich: bool = False,
    selected_presets: list[str] | None = None,
    fx_count: int = 0,
    seed: int | None = None,
    exclude_tags: list[str] | None = None,
    strip_quality: bool = False,
    strip_artist: bool = False,
    strip_lora: bool = False,
    strip_meta: bool = False,
    min_tags: int = 0,
    output_format: str = "prompt",
) -> list[str]:
    if warehouse is None:
        warehouse = TagWarehouse()

    exclude = _normalize_exclude(exclude_tags)
    parsed.general_tags = _clean_general_tags(parsed.general_tags)
    parsed.general_tags = _apply_blacklist(parsed.general_tags, exclude)
    parsed = _apply_strip_flags(
        parsed, warehouse, strip_quality, strip_artist, strip_lora, strip_meta
    )

    if mode == "rewrite":
        return full_rewrite(
            parsed=parsed,
            warehouse=warehouse,
            model=model,
            rating=rating,
            creativity=creativity,
            num_variations=num_variations,
            seed=seed,
            selected_categories=selected_categories,
            selected_presets=selected_presets,
            fx_count=fx_count,
            weight_mode=weight_mode,
            artist_style=artist_style,
            selected_artists=selected_artists,
            use_tandems=use_tandems,
            selected_tandem=selected_tandem,
            web_enrich=web_enrich,
            exclude_tags=exclude_tags,
            strip_quality=strip_quality,
            strip_artist=strip_artist,
            strip_lora=strip_lora,
            strip_meta=strip_meta,
            min_tags=min_tags,
            output_format=output_format,
        )

    settings = CREATIVITY_SETTINGS.get(creativity, CREATIVITY_SETTINGS["medium"])
    settings = _adjust_settings_by_prompt_length(settings, parsed, len(warehouse.pools))
    max_rating = MAX_RATING_MAP.get(rating, "sfw")
    results = []
    all_new_tags_per_variation: list[list[str]] = []

    base_general = list(parsed.general_tags)

    if selected_categories:
        parsed = apply_synonym_filter(parsed, selected_categories, warehouse, model, rating)
        base_general = list(parsed.general_tags)

    protected_lower = _protected_set(parsed)
    # Preset bundle tags are user-intended additions: protect them from the
    # balancing/dedup passes so an applied preset is never silently dropped.
    for _p in (selected_presets or []):
        for _t in get_preset_bundle_tags(_p):
            protected_lower.add(_t.lower().strip())

    # Head nouns the user already specified (e.g. "hair" from "blue hair"); we
    # avoid stacking a second same-head tag like "purple hair" on top of it.
    user_heads = {_head(t) for t in base_general if len(t.split()) >= 2}

    # Cross-category injection: add related categories via rewrite_map
    resolved_categories = list(selected_categories)
    AUTO_EXCLUDE = {"furry", "nsfw"}
    if settings["concept_cross"] and parsed.general_tags:
        for tag in parsed.general_tags:
            tag_cats = get_tag_categories(tag)
            for cat in tag_cats:
                if cat not in resolved_categories and warehouse.get_pool(cat) is not None:
                    resolved_categories.append(cat)

        resolved_categories = [
            c for c in resolved_categories
            if c in selected_categories or c not in AUTO_EXCLUDE
        ]

    # Wildcard categories: add context-relevant extra categories
    if settings["wildcard_categories"] > 0:
        all_avail = [c for c in warehouse.pools if c not in resolved_categories and c not in AUTO_EXCLUDE]
        wild_rng = random.Random(seed) if seed is not None else random.Random()
        extra = _pick_wildcard_categories(all_avail, settings["wildcard_categories"], parsed, wild_rng)
        resolved_categories.extend(extra)

    _skip_animal = has_human_subject(base_general) and "animal" not in selected_categories

    # Artist lookup map is loop-invariant — build once, reuse per variation.
    known_artists_map = {a["tag"].lower().strip(): a["tag"] for a in warehouse.get_all_artists()}

    core_tags, decorative_tags = split_core_decorative(base_general)
    core_set = {t.lower().strip() for t in core_tags}

    # Theme budget for adaptive decorative tag allocation (intent is computed ONCE
    # per generation call and threaded through the per-category picker).
    intent = detect_intent(parsed)
    theme_budget = compute_theme_budget(intent, resolved_categories, settings["tags_per_category"])
    cat_to_theme: dict[str, str] = {}
    for theme, cats in _THEME_GROUPS.items():
        for cat in cats:
            cat_to_theme[cat] = theme

    # Per-category token budget (loop-invariant): keeps the whole variation under
    # MAX_TOKENS_DEFAULT before tags are even picked, instead of trimming at the end.
    cat_token_budget = _category_token_budget(
        resolved_categories, settings, warehouse, max_rating, MAX_TOKENS_DEFAULT
    )

    base_seed = seed
    for var_idx in range(num_variations):
        var_seed = (base_seed + var_idx * 7919) if base_seed is not None else random.randint(0, 2**31 - 1) + var_idx * 7919
        rng = random.Random(var_seed)

        variant = deepcopy(parsed)
        new_general = list(base_general)
        new_added = []

        if use_tandems and not selected_tandem and not selected_artists:
            tandem_tags = _pick_style_tandem(rng, warehouse, artist_style)
            existing_lower = {t.lower().strip() for t in new_general}
            for t in tandem_tags:
                if t.lower().strip() not in existing_lower:
                    new_general.append(t)
                    new_added.append(t)
                    existing_lower.add(t.lower().strip())

        if use_tandems and selected_tandem and not selected_artists:
            tandem_artists = selected_tandem.get("artists", [])
            existing_lower = {t.lower().strip() for t in new_general}
            for aname in tandem_artists:
                if aname.lower().strip() not in existing_lower:
                    new_general.append(aname)
                    new_added.append(aname)
                    existing_lower.add(aname.lower().strip())
                sig = warehouse.get_artist_signature_tags(aname)
                for st in sig:
                    if warehouse.tag_exceeds_rating(st, max_rating):
                        continue
                    if st.lower().strip() not in existing_lower:
                        new_general.append(st)
                        new_added.append(st)
                        existing_lower.add(st.lower().strip())

        if artist_style and not selected_artists and not use_tandems and not selected_tandem:
            style_artists = warehouse.get_artists_by_style(artist_style)
            if style_artists:
                pool = rng.sample(style_artists, min(3, len(style_artists)))
                for a in pool:
                    new_general.append(a["tag"])
                    new_added.append(a["tag"])

        if selected_artists:
            for aname in selected_artists:
                if aname not in new_general:
                    new_general.append(aname)
                    new_added.append(aname)
                sig_tags = warehouse.get_artist_signature_tags(aname)
                existing_lower = {t.lower().strip() for t in new_general}
                for st in sig_tags:
                    if warehouse.tag_exceeds_rating(st, max_rating):
                        continue
                    if st.lower().strip() not in existing_lower:
                        new_general.append(st)
                        new_added.append(st)
                        existing_lower.add(st.lower().strip())

        # Replacement rate: remove some existing user tags proportionally
        # Quality tags are weighted lower to preserve them; core tags are protected
        if settings["replacement_rate"] > 0 and base_general:
            # Never remove the user's protected intent (subject design / explicit
            # category tags) or core tags; only replace flexible user tags so that
            # variations stay true to what the user actually asked for.
            user_tags = [
                t for t in new_general
                if t in base_general
                and t.lower().strip() not in core_set
                and t.lower().strip() not in protected_lower
            ]
            if user_tags:
                n_replace = max(1, int(len(user_tags) * settings["replacement_rate"]))
                quality_keywords = {"score", "masterpiece", "quality", "aesthetic", "detailed"}
                weights = []
                for t in user_tags:
                    tl = t.lower().strip()
                    is_quality = any(kw in tl for kw in quality_keywords)
                    weights.append(0.2 if is_quality else 1.0)
                to_remove = rng.choices(user_tags, weights=weights, k=min(n_replace, len(user_tags)))
                to_remove = list(dict.fromkeys(to_remove))
                for t in to_remove:
                    if t in new_general:
                        new_general.remove(t)

        used_globals = {t.lower().strip() for t in new_general}

        # Track per-variation theme usage
        var_theme_usage: dict[str, int] = {}

        for cat in resolved_categories:
            if cat == "animal" and _skip_animal:
                continue
            pool = warehouse.get_pool(cat)
            if pool is None:
                continue

            min_t, max_t = settings["tags_per_category"]
            theme = cat_to_theme.get(cat, "misc")
            theme_max = theme_budget.get(theme, max_t * 2)
            used_this_theme = var_theme_usage.get(theme, 0)

            # Reduce count if theme budget is exceeded (and never exceed the
            # category's pre-allocated token budget).
            local_max = max(min_t, min(max_t, theme_max - used_this_theme))
            local_max = min(local_max, cat_token_budget.get(cat, local_max))
            count = rng.randint(min_t, local_max) if local_max >= min_t else min_t

            candidates = pool.get_all_tags(max_rating=max_rating)
            if not candidates:
                continue

            picked = _pick_tags_weighted(candidates, count, parsed, rng, used_globals, new_general, intent=intent)
            for tag in picked:
                if _is_negative_quality(tag):
                    continue
                if has_synonym_conflict(tag, new_general):
                    continue
                # Don't stack a second same-head tag on a tag the user already gave.
                if _head(tag) in user_heads and tag.lower().strip() not in protected_lower:
                    continue
                new_general, was_added = _resolve_and_replace(tag, new_general, warehouse, protected_lower)
                if was_added:
                    new_added.append(tag)
                    used_globals.add(tag.lower().strip())
                    var_theme_usage[theme] = used_this_theme + 1
                    used_this_theme += 1

        # Smart substitution pass: context-aware replacement with cross-category fallback
        if settings["substitution_chance"] > 0:
            new_general = _smart_substitution(new_general, settings["substitution_chance"], rng,
                                              parsed, warehouse, resolved_categories, core_set, protected_lower)

        # Preset overlay (protected additions) + FX tag layer (Standard Varry).
        for pname in (selected_presets or []):
            for tag in get_preset_bundle_tags(pname):
                new_general, _ = _resolve_and_replace(tag, new_general, warehouse, protected_lower)
        new_general = _apply_fx_layer(new_general, parsed, warehouse, rng, fx_count, protected_lower, used_globals, max_rating)

        # Web enrichment: co-occurrence + Danbooru tags keyed on the user's
        # subject/character (falls back to local co-occurrence data offline).
        if web_enrich:
            from src.tag_searcher import enrich_prompt_tags
            enrich = enrich_prompt_tags(variant, warehouse, max_tags=5, user_tags=parsed.general_tags)
            for t in enrich:
                new_general, _ = _resolve_and_replace(t, new_general, warehouse, protected_lower)

        variant.general_tags = new_general

        for prev_tags in all_new_tags_per_variation:
            diversity = _min_diversity_index(new_added, prev_tags)
            if diversity < settings["diversity_threshold"] and num_variations > 1:
                extra_seed = rng.randint(0, 2**31 - 1)
                re_rng = random.Random(extra_seed)
                extra_candidates = []
                for cat in resolved_categories:
                    pool = warehouse.get_pool(cat)
                    if pool is None:
                        continue
                    for tag in pool.get_all_tags(max_rating=max_rating):
                        if _is_negative_quality(tag):
                            continue
                        if _head(tag) in user_heads and tag.lower().strip() not in protected_lower:
                            continue
                        if tag.lower().strip() in used_globals:
                            continue
                        extra_candidates.append(tag)
                if extra_candidates:
                    picked = semantic_pick_tags(
                        extra_candidates, 2, parsed, re_rng,
                        set(), variant.general_tags, intent=intent,
                    )
                    for tag in picked:
                        variant.general_tags, _ = _resolve_and_replace(tag, variant.general_tags, warehouse, protected_lower)
                break

        all_new_tags_per_variation.append(new_added)
        variant.general_tags = filter_subject_conflicts(variant.general_tags, base_general)
        variant.general_tags = smart_dedup(variant.general_tags, model=model)
        variant.general_tags = [t for t in variant.general_tags if not _is_negative_quality(t)]
        variant.general_tags = _remove_intra_conflicts(variant.general_tags, warehouse, protected_lower)

        # Move artist tags into variant.artists (loop-invariant lookup map).
        _extract_artists_from_general(variant, known_artists_map)

        # Smart balancing: cap per-theme dominance + token budget, strip metadata noise.
        variant.general_tags = _balance_variation(variant.general_tags, protected_lower, theme_budget, MAX_TOKENS_DEFAULT)
        variant.general_tags = [t for t in variant.general_tags if t.lower().strip() not in RESTRICTIVE_TAGS]
        variant.general_tags = _apply_blacklist(variant.general_tags, exclude)
        if min_tags > 0:
            variant.general_tags = _ensure_min_tags(
                variant.general_tags, min_tags, warehouse, protected_lower, user_heads, exclude, max_rating, rng,
                parsed=parsed, intent=intent,
            )

        # Principled ordering: identity/composition lead, ambiance/effects trail
        # (SD attends to earlier tokens more, so random shuffle is harmful).
        variant.general_tags = _smart_order_tags(variant.general_tags)

        tag_weights = None
        if weight_mode != "off":
            tag_weights = _compute_tag_weights(warehouse, selected_artists)

        result = format_prompt(
            variant, model=model, rating=rating,
            quality_enabled=("quality" in selected_categories and not strip_quality),
            weight_mode=weight_mode, tag_weights=tag_weights,
            output_format=output_format,
        )
        results.append(result)

    return results


def full_rewrite(
    parsed: ParsedPrompt,
    warehouse: TagWarehouse,
    model: str = "anima",
    rating: str = "pg",
    creativity: str = "medium",
    num_variations: int = 5,
    seed: int | None = None,
    selected_categories: list[str] | None = None,
    selected_presets: list[str] | None = None,
    fx_count: int = 0,
    weight_mode: str = "off",
    artist_style: str = "",
    selected_artists: list[str] | None = None,
    use_tandems: bool = False,
    selected_tandem: dict | None = None,
    web_enrich: bool = False,
    exclude_tags: list[str] | None = None,
    strip_quality: bool = False,
    strip_artist: bool = False,
    strip_lora: bool = False,
    strip_meta: bool = False,
    min_tags: int = 0,
    output_format: str = "prompt",
) -> list[str]:
    """Full Rewrite mode: keep subject + character (the original concept), rebuild
    every other tag from scratch so each variation is a genuinely different but
    on-theme prompt. A per-variation 'angle' preset shifts mood/style/setting."""
    if warehouse is None:
        warehouse = TagWarehouse()
    exclude = _normalize_exclude(exclude_tags)
    parsed.general_tags = _clean_general_tags(parsed.general_tags)
    parsed.general_tags = _apply_blacklist(parsed.general_tags, exclude)
    parsed = _apply_strip_flags(
        parsed, warehouse, strip_quality, strip_artist, strip_lora, strip_meta
    )
    selected_presets = selected_presets or []
    selected_categories = selected_categories or []
    settings = CREATIVITY_SETTINGS.get(creativity, CREATIVITY_SETTINGS["medium"])
    settings = _adjust_settings_by_prompt_length(settings, parsed, len(warehouse.pools))
    max_rating = MAX_RATING_MAP.get(rating, "sfw")
    original_intent = detect_intent(parsed)
    protected = _protected_set(parsed, design_only=True)
    # Preserve user-specific names (characters/series/artists not in our pools)
    # so Full Rewrite keeps the identity instead of discarding it.
    named = {
        t.lower().strip()
        for t in parsed.general_tags
        if t.lower().strip() not in protected and not _is_known_tag(t)
    }
    protected |= named
    # Head nouns the user already specified (e.g. "hair" from "blue hair"); we
    # avoid stacking a second same-head tag like "neon hair" on top of it.
    user_heads = {_head(t) for t in parsed.general_tags if len(t.split()) >= 2}
    all_preset_keys = list(PRESETS.keys())
    results: list[str] = []

    cats = [c for c in selected_categories if c not in ("nsfw", "furry") and warehouse.get_pool(c)]
    if not cats:
        cats = [c for c in warehouse.pools if c not in ("nsfw", "furry")]

    cat_to_theme: dict[str, str] = {}
    for theme, cs in _THEME_GROUPS.items():
        for c in cs:
            cat_to_theme[c] = theme

    cat_token_budget = _category_token_budget(
        cats, settings, warehouse, max_rating, MAX_TOKENS_DEFAULT
    )

    base_seed = seed
    for var_idx in range(num_variations):
        var_seed = (base_seed + var_idx * 7919) if base_seed is not None else random.randint(0, 2 ** 31 - 1) + var_idx * 7919
        rng = random.Random(var_seed)

        work = deepcopy(parsed)
        # Keep the user's protected design tags (hair/eyes/clothing/etc.); rebuild
        # everything else from scratch so the concept is preserved but fresh.
        preserved = [t for t in parsed.general_tags if t.lower().strip() in protected]
        work.general_tags = list(preserved)
        preserved_cats = set()
        for t in preserved:
            preserved_cats.update(get_tag_categories(t))

        angle = rng.choice(all_preset_keys)
        presets_this = list(selected_presets) + [angle]

        new_general: list[str] = list(preserved)
        used: set[str] = {t.lower().strip() for t in preserved}
        theme_budget = compute_theme_budget(original_intent, cats, settings["tags_per_category"])

        for cat in cats:
            if cat in preserved_cats:
                continue
            pool = warehouse.get_pool(cat)
            if pool is None:
                continue
            min_t, max_t = settings["tags_per_category"]
            theme = cat_to_theme.get(cat, "misc")
            theme_max = theme_budget.get(theme, max_t * 2)
            count = rng.randint(min_t, max(min_t, min(max_t, theme_max)))
            count = min(count, cat_token_budget.get(cat, count))
            cands = pool.get_all_tags(max_rating=max_rating)
            if not cands:
                continue
            picked = _pick_tags_weighted(cands, count, work, rng, used, new_general, intent=original_intent)
            for tag in picked:
                if _is_negative_quality(tag):
                    continue
                if has_synonym_conflict(tag, new_general):
                    continue
                if _head(tag) in user_heads and tag.lower().strip() not in protected:
                    continue
                new_general, _ = _resolve_and_replace(tag, new_general, warehouse, protected)
                used.add(tag.lower().strip())

        for p in presets_this:
            for tag in get_preset_bundle_tags(p):
                new_general, _ = _resolve_and_replace(tag, new_general, warehouse, protected)

        new_general = _apply_fx_layer(new_general, parsed, warehouse, rng, fx_count, protected, used, max_rating)

        # Web enrichment: co-occurrence + Danbooru tags keyed on the user's
        # subject/character (falls back to local co-occurrence data offline).
        if web_enrich:
            from src.tag_searcher import enrich_prompt_tags
            enrich = enrich_prompt_tags(work, warehouse, max_tags=5, user_tags=parsed.general_tags)
            for t in enrich:
                new_general, _ = _resolve_and_replace(t, new_general, warehouse, protected)

        new_general = _balance_variation(new_general, protected, theme_budget, MAX_TOKENS_DEFAULT)
        new_general = [t for t in new_general if t.lower().strip() not in RESTRICTIVE_TAGS]
        new_general = [t for t in new_general if not _is_negative_quality(t)]
        new_general = _apply_blacklist(new_general, exclude)
        new_general = _remove_intra_conflicts(new_general, warehouse, protected)
        if min_tags > 0:
            new_general = _ensure_min_tags(
                new_general, min_tags, warehouse, protected, user_heads, exclude, max_rating, rng,
                parsed=work, intent=original_intent,
            )

        # Principled ordering: identity/composition lead, ambiance/effects trail.
        new_general = _smart_order_tags(new_general)

        work.general_tags = new_general
        quality_on = "quality" in selected_categories and not strip_quality
        tag_weights = None
        if weight_mode != "off":
            tag_weights = _compute_tag_weights(warehouse, selected_artists)
        result = format_prompt(
            work, model=model, rating=rating,
            quality_enabled=quality_on, weight_mode=weight_mode, tag_weights=tag_weights,
            output_format=output_format,
        )
        results.append(result)

    return results


_NEG_TEMPLATES_PATH = _os.path.join(
    _os.path.dirname(_os.path.dirname(__file__)), "data", "negative_templates.json"
)


def _load_negative_templates() -> dict:
    try:
        with open(_NEG_TEMPLATES_PATH, "r", encoding="utf-8") as f:
            return _json.load(f)
    except (FileNotFoundError, _json.JSONDecodeError):
        return {}


_NEG = _load_negative_templates()

NEGATIVE_PROMPTS: list[str] = _NEG.get("templates", [])

_RATING_SAFETY_ADDONS: dict[str, str] = _NEG.get("rating_addons", {})

_SFWMODEL_NEGATIVE_ADDON: str = _NEG.get("sfwmodel_addon", "")

_ILLUSTRIOUS_NEGATIVE_ADDON: str = _NEG.get("illustrious_addon", "")

_ANIMAL_NEGATIVE_ADDON: str = _NEG.get("animal_addon", "")

_HUMAN_NEGATIVE_ADDON: str = _NEG.get("human_addon", "")

# Intent → tags that fight the detected scene type. These get negated so the
# negative prompt opposes what will be generated (portrait → not a wide shot,
# environment → not a close-up, etc.). Values are validated against the tag
# pools so no phantom tags leak into the output.
_INTENT_NEGATIVE_MAP = {
    "portrait": ["wide shot", "full body", "dutch angle"],
    "action": ["lying", "sitting"],
    "environment": ["close-up", "extreme close-up", "face focus"],
    "horror": ["cheerful", "bright colors", "pastel colors", "innocent"],
    "romantic": ["dark atmosphere", "horror"],
    "fantasy": ["photorealistic", "realistic"],
}


def _get_inverted_conflicts(
    tags: list[str],
    max_count: int = 3,
    rng: random.Random | None = None,
) -> list[str]:
    """Generate negative tags by inverting user tags' conflict/synonym groups."""
    if not tags:
        return []
    seen = set()
    conflicts: list[str] = []
    for tag in tags:
        tl = tag.lower().strip()
        if tl in seen:
            continue
        seen.add(tl)
        group = _find_conflict_only_group(tag)
        if group and len(group) > 1:
            for gt in group:
                gtl = gt.lower().strip()
                if gtl != tl and gtl not in seen:
                    conflicts.append(gt)
                    seen.add(gtl)
                    if len(conflicts) >= max_count * 3:
                        break
        if len(conflicts) >= max_count * 3:
            break
    if rng and len(conflicts) > max_count:
        return rng.sample(conflicts, max_count)
    return conflicts[:max_count]


def generate_negative_prompt(
    parsed: ParsedPrompt,
    selected_categories: list[str],
    num_variations: int = 5,
    rating: str = "pg",
    warehouse: TagWarehouse = None,
    model: str = "anima",
    positive_tags: list[str] | None = None,
    extra_negative: list[str] | None = None,
    output_format: str = "prompt",
) -> list[str]:
    results: list[str] = []
    max_rating = MAX_RATING_MAP.get(rating, "sfw")
    has_human = bool(parsed.subject and parsed.subject not in ("no_humans", "no humans"))
    is_animal = "animal" in selected_categories

    # Intent inversion source: tags that fight the detected scene type are
    # negated so the negative prompt opposes what will be generated.
    intent = detect_intent(parsed)
    conflict_neg_intent: list[str] = list(_INTENT_NEGATIVE_MAP.get(intent, []))

    base_pool = list(NEGATIVE_PROMPTS)

    # Build a conflict-inversion source from the user prompt AND a sample of
    # the selected category pools, so the negative prompt opposes what will be
    # generated (not just the literal user tags).
    conflict_source: list[str] = list(parsed.general_tags or [])
    if warehouse is not None and selected_categories:
        for cat in selected_categories:
            pool = warehouse.get_pool(cat)
            if pool is None:
                continue
            for t in pool.get_all_tags(max_rating=max_rating)[:5]:
                if t.lower().strip() not in {c.lower().strip() for c in conflict_source}:
                    conflict_source.append(t)

    positive_lower = set()
    for pt in (positive_tags or []):
        for tok in str(pt).split(","):
            tl = tok.strip().lower()
            if tl:
                if tl.startswith("(") and tl.endswith(")") and ":" in tl:
                    tl = tl[1:-1].rsplit(":", 1)[0].strip()
                positive_lower.add(tl)

    for var_idx in range(num_variations):
        seed_bytes = f"neg:{var_idx}:{rating}:{model}:{','.join(sorted(selected_categories))}".encode()
        seed = int.from_bytes(hashlib.sha256(seed_bytes).digest()[:4], "big") & 0x7FFFFFFF
        rng = random.Random(seed)

        primary_idx = rng.randint(0, len(base_pool) - 1)
        primary = base_pool[primary_idx]

        secondary_idx = rng.randint(0, len(base_pool) - 1)
        while secondary_idx == primary_idx and len(base_pool) > 1:
            secondary_idx = rng.randint(0, len(base_pool) - 1)
        secondary = base_pool[secondary_idx]

        parts = primary.split(", ")
        secondary_parts = secondary.split(", ")
        extra = rng.sample(secondary_parts, min(3, len(secondary_parts)))
        for e in extra:
            if e not in parts:
                parts.append(e)

        # Rating-specific safety addons
        safety_pool = _RATING_SAFETY_ADDONS.get(max_rating, _RATING_SAFETY_ADDONS.get("sfw", ""))
        if safety_pool:
            safety_tags = safety_pool.split(", ")
            parts.extend(rng.sample(safety_tags, min(2, len(safety_tags))))

        if model == "anima" and rng.random() < 0.4:
            swf_addons = _SFWMODEL_NEGATIVE_ADDON.split(", ")
            parts.extend(rng.sample(swf_addons, min(2, len(swf_addons))))

        if model == "illustrious" and rng.random() < 0.3:
            ill_addons = _ILLUSTRIOUS_NEGATIVE_ADDON.split(", ")
            parts.extend(rng.sample(ill_addons, min(2, len(ill_addons))))

        if has_human and not is_animal:
            human_addons = _HUMAN_NEGATIVE_ADDON.split(", ")
            parts.extend(rng.sample(human_addons, min(3, len(human_addons))))

        if is_animal:
            animal_addons = _ANIMAL_NEGATIVE_ADDON.split(", ")
            for a in animal_addons:
                if a in parts:
                    parts.remove(a)

        # Conflict inversion: add 1-2 opposing tags per variation
        if conflict_source:
            conflict_neg = _get_inverted_conflicts(conflict_source, max_count=2, rng=rng)
            parts.extend(conflict_neg)

        # Intent inversion: negate tags that fight the detected scene type.
        if conflict_neg_intent and rng.random() < 0.6:
            neg_pool = [t for t in conflict_neg_intent if t.lower() not in positive_lower]
            if neg_pool:
                parts.extend(rng.sample(neg_pool, min(2, len(neg_pool))))

        seen = set()
        deduped = []
        for p in parts:
            pl = p.strip().lower()
            if not pl:
                continue
            if pl in seen:
                continue
            # Never negate a tag that is actually present in the positive prompt.
            if pl in positive_lower:
                continue
            seen.add(pl)
            deduped.append(p.strip())

        # Mirror user blacklist into the negative prompt when requested (A).
        if extra_negative:
            for en in extra_negative:
                enl = en.strip().lower()
                if enl and enl not in positive_lower and enl not in seen:
                    seen.add(enl)
                    deduped.append(en.strip())

        deduped = [normalize_tag(p, output_format) for p in deduped]
        results.append(", ".join(deduped))

    return results