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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953646d
 
 
 
 
 
3e72399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
import base64
import copy
import inspect
import io
import json
import os
import random
import re
from itertools import combinations
from pathlib import Path
from typing import Dict, Any, List, Tuple, Optional
import requests  # new

BACKEND_URL = os.getenv("ATTRLLM_BACKEND_URL", "http://127.0.0.1:8000")

_DEFAULT_GRADIO_DIR = Path(os.environ.get("GRADIO_TEMP_DIR", Path.cwd() / ".gradio_tmp"))
os.environ.setdefault("GRADIO_TEMP_DIR", str(_DEFAULT_GRADIO_DIR))
_DEFAULT_GRADIO_DIR.mkdir(parents=True, exist_ok=True)


def _get_request_timeout() -> float:
    value = os.getenv("ATTRLLM_REQUEST_TIMEOUT")
    if not value:
        return 900.0
    try:
        return float(value)
    except ValueError:
        return 900.0


def _env_flag(name: str, default: bool = False) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    return value.strip().lower() in {"1", "true", "yes", "y", "on"}


def _is_hf_spaces() -> bool:
    return bool(os.getenv("SPACE_ID") or os.getenv("HF_SPACE"))


def _supports_kwarg(callable_obj, kwarg_name: str) -> bool:
    """Return whether a callable appears to accept a named keyword argument."""
    try:
        return kwarg_name in inspect.signature(callable_obj).parameters
    except (TypeError, ValueError):
        return False


def _public_only_mode() -> bool:
    # Keep the text tab visible on Spaces unless explicitly overridden.
    return _env_flag("ATTRLLM_PUBLIC_ONLY", False)


def _mm_only_mode() -> bool:
    return _env_flag("ATTRLLM_MM_ONLY", False)


def _show_auxiliary_tabs() -> bool:
    return _env_flag("ATTRLLM_SHOW_AUX_TABS", False)


def _public_results_file(
    dataset_key: str,
    ex_id: str,
    scalarizer: str,
    level: str,
    method: str,
) -> Path:
    results_dir = _get_results_dir()
    return (
        results_dir
        / "public"
        / dataset_key
        / ex_id
        / scalarizer
        / level
        / f"{method}.json"
    )


def _reference_results_file(
    model_size: str,
    dataset_key: str,
    ex_id: str,
    scalarizer: str,
    level: str,
) -> Path:
    results_dir = _get_results_dir()
    return (
        results_dir
        / "reference_answer"
        / model_size
        / dataset_key
        / ex_id
        / scalarizer
        / f"{level}.json"
    )


def _find_available_model_size(
    dataset_key: str,
    ex_id: str,
    scalarizer: str,
    level: str,
) -> Optional[str]:
    for size in ("large", "medium", "small"):
        if _reference_results_file(size, dataset_key, ex_id, scalarizer, level).exists():
            return size
    return None


# Fallback order when requested (scalarizer, level) is not present (e.g. on HF Space with partial results).
_FALLBACK_SCALARIZER_LEVELS: List[Tuple[str, str]] = [
    ("geomean_jointprob", "word"),
    ("semantic_similarity", "word"),
    ("geomean_jointprob", "sentence"),
    ("semantic_similarity", "sentence"),
    ("geomean_jointprob", "paragraph"),
    ("semantic_similarity", "paragraph"),
]


def _find_any_available_result(
    dataset_key: str,
    ex_id: str,
    get_res: Any,
    method: str = "shapley",
) -> Tuple[Optional[str], Optional[str], Optional[str], Optional[Dict]]:
    """Try (model_size, scalarizer, level) fallbacks; return (size, scalarizer, level, result_dict) or (None,)*4."""
    for size in ("small", "medium", "large"):
        for scalarizer, level in _FALLBACK_SCALARIZER_LEVELS:
            try:
                result = get_res(size, dataset_key, ex_id, scalarizer=scalarizer, feature_level=level) or {}
                payload = result.get(method, {})
                if payload and (payload.get("features") or payload.get("heatmap")):
                    return (size, scalarizer, level, result)
            except Exception:
                continue
    return (None, None, None, None)


def _parse_sparse_key(raw_key: str) -> Tuple[int, ...]:
    key = str(raw_key).strip()
    if not key:
        return ()
    return tuple(int(part) for part in key.split(",") if part != "")


def _normalize_public_payload_fallback(data: Dict[str, Any], method: str, top_k: int = 10) -> Dict[str, Any]:
    """Convert your JSON (features list + meta + mobius_dict) to UI display format. mobius_dict can be empty."""
    if not isinstance(data, dict):
        return {}
    features = data.get("features")
    mobius_raw = data.get("mobius_dict") if isinstance(data.get("mobius_dict"), dict) else {}
    if not isinstance(features, list) or not features:
        return {}
    method = (method or "shapley").lower()
    if method not in {"shapley", "banzhaf", "influence"}:
        method = "shapley"
    mobius_sparse: Dict[Tuple[int, ...], float] = {}
    for key, raw_val in mobius_raw.items():
        try:
            val = float(raw_val)
        except Exception:
            continue
        try:
            loc = _parse_sparse_key(str(key))
        except Exception:
            continue
        mobius_sparse[tuple(sorted(loc))] = val
    token_scores: Dict[str, float] = {}
    index_scores: Dict[int, float] = {}
    pairwise_acc: Dict[Tuple[int, int], float] = {}
    if mobius_sparse and mobius_to_shapley is not None:
        if method == "shapley":
            singleton_dict = mobius_to_shapley(mobius_sparse)
            pair_list = shapley_interactions(mobius_sparse, order=2, top_k=top_k) or []
        elif method == "banzhaf":
            singleton_dict = mobius_to_banzhaf(mobius_sparse)
            pair_list = banzhaf_interactions(mobius_sparse, order=2, top_k=top_k) or []
        elif mobius_to_influence is not None and influence_interactions is not None:
            singleton_dict = mobius_to_influence(mobius_sparse)
            pair_list = influence_interactions(mobius_sparse, order=2, top_k=top_k) or []
        else:
            singleton_dict = {}
            pair_list = []

        for loc, val in singleton_dict.items():
            if len(loc) != 1:
                continue
            idx = int(loc[0])
            if 0 <= idx < len(features):
                feat_name = str(features[idx])
                val_f = float(val)
                token_scores[feat_name] = token_scores.get(feat_name, 0.0) + val_f
                index_scores[idx] = index_scores.get(idx, 0.0) + val_f

        for loc, val in pair_list:
            if len(loc) != 2:
                continue
            i, j = int(loc[0]), int(loc[1])
            if 0 <= i < len(features) and 0 <= j < len(features):
                key = (i, j) if i <= j else (j, i)
                pairwise_acc[key] = float(val)
    else:
        # Best-effort fallback when attribution helpers are unavailable.
        for loc, val in mobius_sparse.items():
            k = len(loc)
            if k == 0:
                continue
            if method == "shapley":
                sw = 1.0 / float(k)
            elif method == "banzhaf":
                sw = 1.0 / float(2 ** (k - 1))
            else:
                sw = 1.0 / float(k)
            for idx in loc:
                if 0 <= idx < len(features):
                    feat_name = str(features[idx])
                    token_scores[feat_name] = token_scores.get(feat_name, 0.0) + sw * val
                    index_scores[idx] = index_scores.get(idx, 0.0) + sw * val
            if k >= 2:
                if method == "shapley":
                    pw = 1.0 / float(k - 1)
                elif method == "banzhaf":
                    pw = 1.0 / float(2 ** (k - 2))
                else:
                    pw = 1.0 / float(k - 1)
                for i, j in combinations(sorted(loc), 2):
                    pairwise_acc[(i, j)] = pairwise_acc.get((i, j), 0.0) + pw * val
    unique_feature_labels = [str(x) for x in features]
    sorted_pairs = sorted(pairwise_acc.items(), key=lambda kv: abs(kv[1]), reverse=True)
    if top_k and top_k > 0:
        sorted_pairs = sorted_pairs[:top_k]
    pairwise = {
        "%s|%s" % (unique_feature_labels[i], unique_feature_labels[j]): float(v)
        for (i, j), v in sorted_pairs
        if 0 <= i < len(unique_feature_labels) and 0 <= j < len(unique_feature_labels)
    }
    pairwise_interactions = [
        {"features": [unique_feature_labels[i], unique_feature_labels[j]], "value": float(v)}
        for (i, j), v in sorted_pairs
        if 0 <= i < len(unique_feature_labels) and 0 <= j < len(unique_feature_labels)
    ]
    normalized = dict(data)
    normalized["token_scores"] = token_scores
    normalized["pairwise"] = pairwise
    normalized["pairwise_interactions"] = pairwise_interactions
    normalized["features"] = [
        {"feature": str(features[i]), "value": float(index_scores.get(i, 0.0)), "index": i}
        for i in range(len(features))
    ]
    normalized["feature_texts"] = [str(x) for x in features]
    return normalized


def _public_get_model_answer_short_from_file(
    model_size: str,
    dataset: str,
    ex_id: str,
    scalarizer: str = "geomean_jointprob",
    feature_level: str = "word",
) -> Dict[str, Any]:
    """Load model_answer_short payload (the wrong-answer attribution) for the
    Public Mode dual-heatmap branch. Returns a per-method dict shaped like
    `_public_get_result_from_file`, or {} when the file is missing.
    """
    results_dir = _get_results_dir()
    path = (
        results_dir
        / "model_answer_short"
        / model_size
        / dataset
        / ex_id
        / scalarizer
        / f"{feature_level}.json"
    )
    if not path.exists():
        return {}
    try:
        with path.open("r", encoding="utf-8") as f:
            data = json.load(f)
    except Exception:
        return {}
    if not isinstance(data, dict):
        return {}
    norm_s = _normalize_public_payload_fallback(copy.deepcopy(data), "shapley")
    norm_b = _normalize_public_payload_fallback(copy.deepcopy(data), "banzhaf")
    norm_i = _normalize_public_payload_fallback(copy.deepcopy(data), "influence")
    if not norm_s and not norm_b and not norm_i:
        return {}
    return {
        "shapley": norm_s,
        "banzhaf": norm_b,
        "influence": norm_i,
        "meta": {
            "dataset": dataset,
            "example_id": ex_id,
            "model_size": model_size,
            "target_mode": "model_answer_short",
            "source_layout": "results/model_answer_short/{model_size}/{dataset}/{example_id}/{scalarizer}/{feature_level}.json",
        },
    }


def _public_get_result_from_file(
    model_size: str,
    dataset: str,
    ex_id: str,
    scalarizer: Optional[str] = None,
    feature_level: Optional[str] = None,
) -> Dict[str, Any]:
    """Load reference_answer result from disk when loader.results.get_result_by_id is unavailable (e.g. on Space)."""
    scalarizer = (scalarizer or "").strip()
    feature_level = (feature_level or "").strip()
    if not scalarizer or not feature_level:
        return {}
    levels_to_try = [feature_level] + [l for l in ("word", "sentence", "paragraph") if l != feature_level]
    for lvl in levels_to_try:
        path = _reference_results_file(model_size, dataset, ex_id, scalarizer, lvl)
        if not path.exists() or os.getenv("SPACE_ID"):
            try:
                from loader.results import _maybe_download_from_space
                path = _maybe_download_from_space(path, force_download=True) or path
            except Exception:
                pass
        if not path.exists():
            continue
        try:
            with path.open("r", encoding="utf-8") as f:
                data = json.load(f)
        except Exception:
            continue
        if not isinstance(data, dict):
            continue
        # Your JSON: features (list) + meta + mobius_dict (can be empty). Always convert to UI format.
        norm_s = _normalize_public_payload_fallback(copy.deepcopy(data), "shapley")
        norm_b = _normalize_public_payload_fallback(copy.deepcopy(data), "banzhaf")
        norm_i = _normalize_public_payload_fallback(copy.deepcopy(data), "influence")
        if not norm_s and not norm_b and not norm_i:
            continue
        return {
            "shapley": norm_s,
            "banzhaf": norm_b,
            "influence": norm_i,
            "meta": {
                "dataset": dataset,
                "example_id": ex_id,
                "model_size": model_size,
                "source_layout": "results/reference_answer/{model_size}/{dataset}/{example_id}/{scalarizer}/{feature_level}.json",
            },
        }
    return {}


_FALLBACK_DATASET_FILES: Dict[str, str] = {
    "bar_exam": "BarExam_qa.csv",
    "causal_judgment": "bbh_causal_judgement.csv",
    "snarks": "bbh_snarks.csv",
    "bbq_disamb": "BBQ_disamb.csv",
    "cnn_dailymail": "CNN_dailymail.csv",
    "drop": "drop.csv",
    "esnli": "eSNLI.csv",
    "fever": "fever.csv",
    "hotpot_qa": "hotpot_qa.csv",
    "medical_qa": "medical_qa.csv",
}


def _fallback_datasets_dir() -> Path:
    return (_REPO_ROOT / "datasets").resolve()


def _fallback_pick_first_nonempty(raw: Dict[str, str], candidates: List[str]) -> str:
    for c in candidates:
        val = raw.get(c)
        if val is not None and str(val).strip() != "":
            return str(val)
    return ""


def _fallback_load_dataset(dataset_key: str, max_rows: int = 10) -> List[Dict[str, str]]:
    import csv

    filename = _FALLBACK_DATASET_FILES.get(dataset_key)
    if not filename:
        return []
    path = _fallback_datasets_dir() / filename
    if not path.exists():
        return []

    rows: List[Dict[str, str]] = []
    with path.open("r", encoding="utf-8", errors="replace", newline="") as f:
        reader = csv.DictReader(f)
        for i, raw in enumerate(reader, start=1):
            ex_id = raw.get("id") or raw.get("example_id") or raw.get("uid") or f"example_{i}"
            context = _fallback_pick_first_nonempty(raw, [
                "Context", "context",
                "passage", "article", "story", "premise",
                "paragraph", "document", "sentence1", "sent1", "background",
            ])
            prompt = _fallback_pick_first_nonempty(raw, [
                "Prompt", "prompt",
                "question", "input", "query",
                "sentence2", "sent2", "hypothesis",
                "qa_question", "title",
            ])
            answer = _fallback_pick_first_nonempty(raw, [
                "Answer", "answer",
                "target", "gold", "label", "output", "reference",
                "highlights",
            ])
            ex = {
                "id": str(ex_id),
                "context": context,
                "prompt": prompt,
            }
            if answer:
                ex["answer"] = answer
            rows.append(ex)
            if len(rows) >= max_rows:
                break
    return rows


REQUEST_TIMEOUT = _get_request_timeout()

SCALARIZER_CHOICES = [
    ("Semantic Similarity (y vs y_S)", "semantic_similarity"),
    ("LogProb", "logprob"),
    ("JointProb", "jointprob"),
    ("GeoMean JointProb", "geomean_jointprob"),
    ("Half SimLog", "half_simlog"),
]

PUBLIC_SCALARIZER_CHOICES = [
    ("Semantic Similarity", "semantic_similarity"),
    ("Perplexity", "geomean_jointprob"),
]

DATASET_DISPLAY_LABELS = {
    "bar_exam": "Bar Exam Questions",
    "bbq_disamb": "BBQ Disambiguation",
    "causal_judgment": "Causal Judgment",
    "cnn_dailymail": "CNN / DailyMail Summaries",
    "drop": "DROP Reading Comprehension",
    "esnli": "e-SNLI Natural Language Inference",
    "fever": "FEVER Fact Checking",
    "hotpot_qa": "HotpotQA Multi-hop Questions",
    "medical_qa": "Medical Questions",
    "snarks": "Snarks",
}

import sys
_REPO_ROOT = Path(__file__).resolve().parents[1]
if str(_REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(_REPO_ROOT))


def _get_results_dir() -> Path:
    """Resolve results directory: env, repo root, or on HF Space fallback to cwd/results."""
    env_dir = os.getenv("ATTRLLM_RESULTS_DIR")
    if env_dir:
        return Path(env_dir).resolve()
    default = (_REPO_ROOT / "results").resolve()
    if default.exists():
        return default
    if _is_hf_spaces():
        cwd_results = (Path.cwd() / "results").resolve()
        if cwd_results.exists():
            return cwd_results
    return default


import gradio as gr
from PIL import Image

from .components.model_selector import (
    create_model_selector,
    create_multimodal_model_selector,
    create_feature_level_selector,
    create_attribution_method_toggle,
)
from .components.example_browser import create_dataset_selector, create_example_browser
from .components.results_display import create_results_display, update
from .plotting.heatmap import create_interactive_text_heatmap
from .plotting.interactions import (
    plot_top_interactions,
    plot_interaction_matrix,
    create_interaction_token_view,
)
from .plotting.text_interactions import create_text_interaction_html
from .plotting.mm_interactions import create_multimodal_interaction_html
from .plotting.coalition_viewer import compute_coalition_viewer_data, render_coalition_viewer_html
from .build_info import BUILD_ID, BUILD_TS

# Medical image precomputed results (optional)
try:
    from .medical_loader import (
        MEDICAL_EXAMPLES,
        load_medical_example,
        get_masked_image_path,
        BENCHMARK_EXAMPLES,
        get_examples_by_modality,
        list_available_modalities,
        load_benchmark_example,
        extract_segment_regions,
    )
    from .plotting.medical_charts import (
        create_shapley_bar_chart,
        create_influence_heatmap,
        create_cross_modal_bar_chart,
        draw_grid_overlay,
        draw_segment_labels,
        generate_interpretation_text,
        rename_patch_labels,
        align_segments_to_reference,
        remap_region_values,
        merge_subword_token_values,
        _tok_to_word,
    )
    from .plotting.benchmark_interaction import create_benchmark_interaction_html
    _MEDICAL_AVAILABLE = True
except ImportError:
    _MEDICAL_AVAILABLE = False
    MEDICAL_EXAMPLES = {}
    BENCHMARK_EXAMPLES = {}

# MIMIC-CXR precomputed results (optional)
try:
    from .mimic_loader import (
        MIMIC_EXAMPLES,
        load_mimic_example,
        get_mimic_image_path,
    )
    _MIMIC_AVAILABLE = bool(MIMIC_EXAMPLES)
except ImportError:
    _MIMIC_AVAILABLE = False
    MIMIC_EXAMPLES = {}

# Dermoscopy ISIC precomputed results (optional)
try:
    from .isic_loader import (
        ISIC_EXAMPLES,
        load_isic_example,
        get_isic_image_path,
    )
    _ISIC_AVAILABLE = bool(ISIC_EXAMPLES)
except ImportError:
    _ISIC_AVAILABLE = False
    ISIC_EXAMPLES = {}

# MS-COCO precomputed results (optional)
try:
    from .coco_loader import COCO_EXAMPLES, load_coco_example, get_coco_masked_image_path
    _COCO_AVAILABLE = True
except ImportError:
    _COCO_AVAILABLE = False
    COCO_EXAMPLES = {}

# CLIP cross-modal pipeline for live compute (optional β€” runs on CPU)
try:
    from attribution.set_mm import (
        PipelineConfig,
        CrossModalCLIPScorer,
        ImageRegion,
        TokenPlayer,
        featurise,
        tokenise_caption,
        build_cross_modal_set_function,
        run_proxyspex,
        mobius_to_shapley,
        mobius_to_banzhaf,
        extract_interactions,
        extract_cross_per_token,
        apply_image_mask,
        render_overlay,
        render_segmentation_map,
        mask_token_ids,
    )
    _CLIP_PIPELINE_AVAILABLE = True
except ImportError:
    _CLIP_PIPELINE_AVAILABLE = False

# Module-level cache for CLIP scorers (keyed by model name)
_clip_scorer_cache: Dict[str, Any] = {}


def _raise_backend_error(resp: requests.Response, label: str) -> None:
    detail = resp.text
    try:
        detail = resp.json().get("detail", detail)
    except Exception:
        pass
    raise gr.Error(f"{label} failed ({resp.status_code}). {detail}")

# backend API imports
try:  # loader data APIs are required for public mode
    from loader.data import (
        get_example_by_id,
        get_examples,
        list_datasets,
        list_datasets_with_display_names,
        list_dataset_display_names,
        get_dataset_display_name,
        get_dataset_key_from_display_name,
    )
except Exception:  # pragma: no cover - optional at runtime
    get_example_by_id = None
    get_examples = None
    list_datasets = None
    list_datasets_with_display_names = None
    list_dataset_display_names = None
    get_dataset_display_name = None
    get_dataset_key_from_display_name = None

try:
    from loader.results import get_result_by_id
except Exception:  # pragma: no cover
    get_result_by_id = None

try:
    from loader.models import get_model
except Exception:  # pragma: no cover
    get_model = None

try:  # attribution stack is optional (dev mode)
    from attribution.masker import get_masker, mask_text
    from attribution.proxyspex import run_proxyspex
    from attribution.image_masker import supports_superpixel
    from attribution.utils import (
        influence_interactions,
        mobius_to_influence,
        mobius_to_shapley,
        shapley_interactions,
        mobius_to_banzhaf,
        banzhaf_interactions,
    )
except Exception:  # pragma: no cover
    get_masker = None
    mask_text = None
    run_proxyspex = None
    supports_superpixel = None
    influence_interactions = None
    mobius_to_influence = None
    mobius_to_shapley = None
    shapley_interactions = None
    mobius_to_banzhaf = None
    banzhaf_interactions = None


_ANSWER_FIELDS = (
    "correct_answer",
    "answer",
    "target",
    "completion",
    "label",
)
_ALLOWED_METHODS = {"shapley", "banzhaf", "influence"}
_ALLOWED_LEVELS = {"word", "sentence", "paragraph"}


def _ensure_backend(name: str, fn: Optional[Any]):
    if fn is None:
        raise RuntimeError(
            f"{name} is unavailable. Ensure the backend modules are installed and importable."
        )
    return fn


def _html_component(label: str, visible: bool = True) -> gr.HTML:
    try:
        return gr.HTML(label=label, sanitize_html=False, visible=visible)
    except TypeError:
        return gr.HTML(label=label, visible=visible)


def _encode_image_to_b64(image: Image.Image) -> str:
    buffer = io.BytesIO()
    image.save(buffer, format="PNG")
    return base64.b64encode(buffer.getvalue()).decode("utf-8")


def _extract_answer(record: Dict[str, Any]) -> str:
    for field in _ANSWER_FIELDS:
        val = record.get(field)
        if val:
            return str(val)
    return ""


def _coerce_feature_tuple(raw_key: Any) -> Tuple[str, ...]:
    if isinstance(raw_key, tuple):
        return tuple(str(item) for item in raw_key)
    if isinstance(raw_key, list):
        return tuple(str(item) for item in raw_key)
    if isinstance(raw_key, str):
        for sep in ("Β·", "|", ",", "Γ—"):
            if sep in raw_key:
                parts = [chunk.strip() for chunk in raw_key.split(sep) if chunk.strip()]
                if parts:
                    return tuple(parts)
        return (raw_key.strip(),)
    return (str(raw_key),)


# def _normalize_interactions(raw: Any) -> List[Tuple[Tuple[str, ...], float]]:
#     items: List[Any]
#     if raw is None:
#         return []
#     if isinstance(raw, dict):
#         items = list(raw.items())
#     else:
#         items = list(raw)

#     normalized: List[Tuple[Tuple[str, ...], float]] = []
#     for feats, value in items:
#         try:
#             numeric = float(value)
#         except Exception:
#             continue
#         normalized.append((_coerce_feature_tuple(feats), numeric))
#     return normalized
def _normalize_interactions(raw: Any) -> List[Tuple[Tuple[str, ...], float]]:
    """
    Make a best-effort guess at interaction structure.

    Supported shapes:
      - { key: float }
      - { key: {"value": float, "score": ...} }
      - [ (key, float), ... ]
      - [ (key, {"value": float}), ... ]
      - [ {"features": [...], "value": float}, ... ]  (this is mostly handled elsewhere)
    """
    if raw is None:
        return []

    items: List[Any] = []

    if isinstance(raw, dict):
        # e.g. { key: float } or { key: {"value": ...} }
        for k, v in raw.items():
            items.append((k, v))
    elif isinstance(raw, list):
        items = list(raw)
    else:
        return []

    normalized: List[Tuple[Tuple[str, ...], float]] = []

    for item in items:
        # Case 1: dict-style item with explicit fields
        if isinstance(item, dict):
            feats = item.get("features") or item.get("indices") or item.get("pair") or item.get("key")
            val = item.get("value", item.get("score", 0.0))
        else:
            # Case 2: tuple/list pair (feats, value)
            try:
                feats, val = item
            except Exception:
                continue

        # If value itself is a dict, dig out "value" / "score"
        if isinstance(val, dict):
            val = val.get("value", val.get("score", 0.0))

        try:
            numeric = float(val)
        except Exception:
            continue

        feats_tuple = _coerce_feature_tuple(feats)
        if feats_tuple:
            normalized.append((feats_tuple, numeric))

    return normalized

def _resolve_marginals(payload: Dict[str, Any]) -> Dict[str, float]:
    for key in ("marginals", "token_scores", "values", "scores"):
        data = payload.get(key)
        if isinstance(data, dict):
            normalized: Dict[str, float] = {}
            for k, v in data.items():
                try:
                    normalized[str(k)] = float(v)
                except Exception:
                    continue
            return normalized
    return {}


def _resolve_features(payload: Dict[str, Any], marginals: Dict[str, float]) -> List[str]:
    features = payload.get("features")
    if isinstance(features, list):
        return [str(f) for f in features]
    if marginals:
        return list(marginals.keys())
    return []


def _extract_interactions_from_response(
    data_int: Dict[str, Any],
    method: str,
    features: List[str],
) -> List[Tuple[Tuple[str, ...], float]]:
    inter_list: List[Tuple[Tuple[str, ...], float]] = []

    method_key = (method or "shapley").lower()
    method_block = data_int.get(method_key) or data_int

    raw_interactions = None
    if isinstance(method_block, dict):
        for key in ("interactions", "pairwise_interactions", "interactions_2", "pairwise", "data"):
            if key in method_block:
                raw_interactions = method_block.get(key)
                break
        if raw_interactions is None:
            raw_interactions = method_block
    else:
        raw_interactions = method_block

    # List-of-dicts or list-of-pairs shape
    if isinstance(raw_interactions, list) and raw_interactions:
        if isinstance(raw_interactions[0], dict):
            for item in raw_interactions:
                feats = (
                    item.get("feature_list")
                    or item.get("features")
                    or item.get("indices")
                    or item.get("pair")
                    or []
                )
                val = None
                for key_val in ("value", "score", "attribution", "weight"):
                    if key_val in item:
                        try:
                            val = float(item[key_val])
                            break
                        except Exception:
                            continue
                if val is None:
                    continue

                if isinstance(feats, list) and feats and isinstance(feats[0], int):
                    feat_names = tuple(
                        features[i] for i in feats
                        if isinstance(i, int) and 0 <= i < len(features)
                    )
                else:
                    feat_names = _coerce_feature_tuple(feats)

                if feat_names:
                    inter_list.append((feat_names, val))
        elif (
            isinstance(raw_interactions[0], (list, tuple))
            and len(raw_interactions[0]) == 2
        ):
            for item in raw_interactions:
                if not isinstance(item, (list, tuple)) or len(item) != 2:
                    continue
                feats_raw, val_raw = item
                try:
                    val = float(val_raw)
                except Exception:
                    continue

                feat_names: Tuple[str, ...] = ()
                if isinstance(feats_raw, (list, tuple)) and feats_raw:
                    if all(isinstance(i, int) for i in feats_raw):
                        feat_names = tuple(
                            features[i] for i in feats_raw
                            if 0 <= i < len(features)
                        )
                    else:
                        feat_names = _coerce_feature_tuple(feats_raw)
                elif isinstance(feats_raw, str):
                    feat_names = _coerce_feature_tuple(feats_raw)

                if feat_names:
                    inter_list.append((feat_names, val))

    # Dict shape, e.g. {"(0,2)": 528.0, ...}
    if not inter_list and isinstance(raw_interactions, dict):
        metadata_keys = {"method", "order", "scalarizer", "embedding_model"}
        for k, v in raw_interactions.items():
            if str(k) in metadata_keys:
                continue
            val = None
            if isinstance(v, (int, float)):
                val = float(v)
            elif isinstance(v, dict):
                for key_val in ("value", "score", "attribution", "weight"):
                    if key_val in v:
                        try:
                            val = float(v[key_val])
                            break
                        except Exception:
                            continue
            if val is None:
                continue

            k_str = str(k)
            idxs = []
            try:
                import re as _re
                idxs = [int(x) for x in _re.findall(r"\d+", k_str)]
            except Exception:
                idxs = []

            if idxs:
                names: List[str] = []
                for idx in idxs:
                    if 0 <= idx < len(features):
                        names.append(features[idx])
                if names:
                    feat_names = tuple(names)
                else:
                    feat_names = _coerce_feature_tuple(k_str)
            else:
                feat_names = _coerce_feature_tuple(k_str)

            inter_list.append((feat_names, val))

    # Flatten numerics arbitrarily (last resort)
    if not inter_list and raw_interactions is not None:
        flat: List[Tuple[Tuple[str, ...], float]] = []

        def _collect(obj: Any, prefix: Tuple[str, ...] = ()) -> None:
            if isinstance(obj, (int, float)):
                flat.append((prefix or ("<interaction>",), float(obj)))
            elif isinstance(obj, list):
                for i, item in enumerate(obj):
                    _collect(item, prefix + (f"[{i}]",))
            elif isinstance(obj, dict):
                for kk, vv in obj.items():
                    _collect(vv, prefix + (str(kk),))

        _collect(raw_interactions)
        inter_list = flat

    return inter_list


def _labels_from_regions(regions: List[Dict[str, Any]]) -> List[str]:
    labels: List[str] = [""] * len(regions)
    for region in regions:
        try:
            idx = int(region.get("index", 0))
        except Exception:
            continue
        if idx < 0 or idx >= len(labels):
            continue
        labels[idx] = str(region.get("label") or f"Region {idx + 1}")
    for idx, label in enumerate(labels):
        if not label:
            labels[idx] = f"Region {idx + 1}"
    return labels


def _interaction_dicts_to_pairs(
    interactions: List[Dict[str, Any]],
    labels: List[str],
    *,
    order: int | None = None,
) -> List[Tuple[Tuple[str, ...], float]]:
    pairs: List[Tuple[Tuple[str, ...], float]] = []
    for item in interactions:
        indices = item.get("indices")
        if not indices:
            continue
        if order is not None and len(indices) != order:
            continue
        try:
            value = float(item.get("value", 0.0))
        except Exception:
            continue
        feats = tuple(labels[int(i)] for i in indices if int(i) < len(labels))
        if feats:
            pairs.append((feats, value))
    return pairs


def _interaction_dicts_to_table(
    interactions: List[Dict[str, Any]],
    labels: List[str],
) -> List[List[Any]]:
    rows: List[List[Any]] = []
    for item in interactions:
        indices = item.get("indices")
        if not indices:
            continue
        try:
            value = float(item.get("value", 0.0))
        except Exception:
            continue
        feats = [labels[int(i)] for i in indices if int(i) < len(labels)]
        if feats:
            rows.append([" Γ— ".join(feats), value, len(indices)])
    return rows


def _feature_display_label(
    feature: Dict[str, Any],
    region_labels: List[str],
) -> str:
    raw = str(feature.get("feature", ""))
    modality = feature.get("modality") or ""
    ref_index = int(feature.get("ref_index", 0))
    label = raw.split(":", 1)[1] if ":" in raw else raw
    if modality == "image":
        if 0 <= ref_index < len(region_labels):
            return region_labels[ref_index]
    return label or raw


def _extract_feature_series(payload: Dict[str, Any]) -> Tuple[List[str], List[float]]:
    """
    Try to recover an ordered pair of (feature labels, values) from a backend payload.
    This keeps duplicates in order (appending suffixes later) so word-level tokens
    don't collapse to a single entry.
    """
    features: List[str] = []
    values: List[float] = []

    feature_entries = payload.get("features")
    if isinstance(feature_entries, list) and feature_entries and isinstance(feature_entries[0], dict):
        for idx, entry in enumerate(feature_entries, start=1):
            raw_feat = (
                entry.get("feature")
                or entry.get("token")
                or entry.get("text")
                or entry.get("label")
                or ""
            )
            if not raw_feat:
                raw_feat = f"feature_{idx}"

            val = entry.get("value")
            if val is None:
                for key in ("score", "attribution", "weight"):
                    if key in entry:
                        val = entry[key]
                        break
            try:
                values.append(float(val if val is not None else 0.0))
            except Exception:
                values.append(0.0)
            features.append(str(raw_feat))

    if not features:
        heat = payload.get("heatmap") or {}
        tokens = heat.get("tokens") or heat.get("features")
        scores = heat.get("values") or heat.get("scores")
        if isinstance(tokens, list) and isinstance(scores, list) and len(tokens) == len(scores):
            features = [str(token if token is not None else f"feature_{idx + 1}") for idx, token in enumerate(tokens)]
            tmp_vals: List[float] = []
            for score in scores:
                try:
                    tmp_vals.append(float(score))
                except Exception:
                    tmp_vals.append(0.0)
            values = tmp_vals

    if not features:
        marginals = _resolve_marginals(payload)
        if marginals:
            features = list(marginals.keys())
            values = [float(marginals[key]) for key in features]

    if not features:
        return [], []

    unique_features = _assign_unique_labels(features)
    return unique_features, values


def _resolve_interactions(payload: Dict[str, Any], order: int) -> List[Tuple[Tuple[str, ...], float]]:
    candidates = [f"interactions_{order}"]
    if order == 2:
        candidates += ["pairwise", "pairwise_interactions", "interactions2"]
    elif order == 3:
        candidates += ["higher_order", "triple_interactions", "interactions3"]

    for key in candidates:
        raw = payload.get(key)
        normalized = _normalize_interactions(raw)
        if normalized:
            return normalized
    return []


def _fallback_pairwise_from_values(
    features: List[str],
    values: List[float],
    max_edges: int = 40,
) -> List[Tuple[Tuple[str, ...], float]]:
    """
    Generate synthetic pairwise links by connecting neighboring tokens.
    Used when the backend provides no explicit interactions.
    """
    n = min(len(features), len(values))
    if n < 2:
        return []
    edges: List[Tuple[Tuple[str, ...], float]] = []
    for idx in range(n - 1):
        weight = 0.5 * (values[idx] + values[idx + 1])
        edges.append(((features[idx], features[idx + 1]), weight))
    edges.sort(key=lambda item: abs(item[1]), reverse=True)
    return edges[:max_edges]


def _resolve_pairwise(
    payload: Dict[str, Any],
    features: Optional[List[str]] = None,
    feature_values: Optional[List[float]] = None,
) -> List[Tuple[Tuple[str, ...], float]]:
    """Convenience helper to always pull order-2 interactions if present."""
    pairwise = _resolve_interactions(payload, 2)
    if pairwise:
        return pairwise
    # Some payloads store generic "interactions" lists that mix orders.
    mixed = payload.get("interactions")
    normalized = _normalize_interactions(mixed)
    if normalized:
        return [item for item in normalized if len(item[0]) == 2]
    if features and feature_values:
        return _fallback_pairwise_from_values(features, feature_values)
    return []


def _normalize_method(method: Optional[str]) -> str:
    method = (method or "shapley").lower()
    return method if method in _ALLOWED_METHODS else "shapley"


def _normalize_level(level: Optional[str]) -> str:
    level = (level or "sentence").lower()
    return level if level in _ALLOWED_LEVELS else "sentence"


def _normalize_model_size(model_size: Optional[str]) -> str:
    raw = (model_size or "small").strip()
    lowered = raw.lower()
    if lowered in {"small", "medium", "large"}:
        return lowered
    if "small" in lowered:
        return "small"
    if "medium" in lowered:
        return "medium"
    if "large" in lowered:
        return "large"
    return "small"


def _assign_unique_labels(chunks: List[str]) -> List[str]:
    counts: Dict[str, int] = {}
    labels: List[str] = []
    for idx, chunk in enumerate(chunks):
        normalized = " ".join((chunk or "").split())
        if not normalized:
            normalized = f"<chunk {idx + 1}>"
        counts[normalized] = counts.get(normalized, 0) + 1
        suffix = f" ({counts[normalized]})" if counts[normalized] > 1 else ""
        labels.append(f"{normalized}{suffix}")
    return labels


def _strip_occurrence_suffix(text: str) -> str:
    text = text or ""
    if text.endswith(")") and " (" in text:
        base, _, tail = text.rpartition(" (")
        if tail[:-1].isdigit():
            return base
    return text


def _pairwise_to_index_interactions(
    pairwise: List[Tuple[Tuple[str, ...], float]],
    features: List[str],
) -> List[Dict[str, Any]]:
    feature_index = {feat: idx for idx, feat in enumerate(features)}
    base_index: Dict[str, int] = {}
    for idx, feat in enumerate(features):
        base_index.setdefault(_strip_occurrence_suffix(feat), idx)

    interactions: List[Dict[str, Any]] = []
    for feats, val in pairwise:
        if len(feats) != 2:
            continue
        a, b = feats
        a_idx = None
        b_idx = None
        if isinstance(a, (int, float)) and isinstance(b, (int, float)):
            a_idx = int(a)
            b_idx = int(b)
        else:
            try:
                a_idx = int(str(a))
                b_idx = int(str(b))
            except ValueError:
                a_idx = feature_index.get(a) or base_index.get(_strip_occurrence_suffix(str(a)))
                b_idx = feature_index.get(b) or base_index.get(_strip_occurrence_suffix(str(b)))
        if a_idx is None or b_idx is None:
            continue
        if a_idx < 0 or b_idx < 0 or a_idx >= len(features) or b_idx >= len(features):
            continue
        interactions.append({"indices": [a_idx, b_idx], "value": float(val)})
    return interactions


def _locate_spans(text: str, segments: List[str]) -> List[Tuple[int, int]]:
    spans: List[Tuple[int, int]] = []
    cursor = 0
    for segment in segments:
        if not segment:
            continue
        idx = text.find(segment, cursor)
        if idx == -1:
            idx = cursor
        end = idx + len(segment)
        spans.append((idx, end))
        cursor = end
    return spans


def _chunk_text_for_visualization(
    context: str,
    level: str,
) -> Tuple[List[str], List[Tuple[int, int]], str]:
    """
    Split input text into feature chunks and spans for visualization.
    Falls back to the demo text if context is empty.
    """
    text = context or _DEMO_TEXT
    level = _normalize_level(level)

    if level == "word":
        matches = list(re.finditer(r"\S+", text))
        chunks = [m.group(0) for m in matches]
        spans = [(m.start(), m.end()) for m in matches]
    elif level == "paragraph":
        parts = [seg for seg in re.split(r"\n\s*\n+", text) if seg.strip()]
        spans = _locate_spans(text, parts)
        chunks = parts[: len(spans)]
    else:  # sentence-level default
        parts = [seg for seg in re.split(r"(?<=[.!?])\s+", text) if seg.strip()]
        spans = _locate_spans(text, parts)
        chunks = parts[: len(spans)]

    if not chunks:
        chunks = [text]
        spans = [(0, len(text))]

    features = _assign_unique_labels(chunks)
    return features, spans, text


def _generate_synthetic_marginals(
    features: List[str],
    rng: random.Random,
) -> Dict[str, float]:
    if not features:
        return {}
    max_len = max(len(f) for f in features) or 1
    marginals: Dict[str, float] = {}
    denom = max(1, len(features) - 1)
    for idx, feat in enumerate(features):
        length_factor = len(feat) / max_len
        position_factor = 1 - (idx / denom if denom else 0)
        noise = rng.uniform(-0.25, 0.25)
        value = (length_factor - 0.5) * 0.6 + (position_factor - 0.5) * 0.4 + noise
        marginals[feat] = round(value, 4)
    return marginals


def _generate_synthetic_interactions(
    features: List[str],
    marginals: Dict[str, float],
    rng: random.Random,
) -> Dict[int, List[Tuple[Tuple[str, ...], float]]]:
    interactions: Dict[int, List[Tuple[Tuple[str, ...], float]]] = {2: [], 3: []}
    for i in range(len(features) - 1):
        pair = (features[i], features[i + 1])
        base = (marginals.get(pair[0], 0.0) + marginals.get(pair[1], 0.0)) / 2
        interactions[2].append((pair, round(base + rng.uniform(-0.1, 0.1), 4)))
    for i in range(len(features) - 2):
        triple = (features[i], features[i + 1], features[i + 2])
        base = sum(marginals.get(feat, 0.0) for feat in triple) / 3
        interactions[3].append((triple, round(base + rng.uniform(-0.1, 0.1), 4)))
    return interactions


def _synthetic_attribution_pipeline(
    context: str,
    prompt: str,
    answer: str,
    *,
    method: str,
    level: str,
    order: int,
    reason: Optional[str] = None,
) -> Tuple[Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any]:
    text_source = context or prompt or answer or _DEMO_TEXT
    features, spans, text = _chunk_text_for_visualization(text_source, level)
    seed = hash((text_source, method, level, order)) & 0xFFFFFFFF
    rng = random.Random(seed)
    marginals = _generate_synthetic_marginals(features, rng)
    interactions = _generate_synthetic_interactions(features, marginals, rng)

    html = None
    if len(spans) == len(features):
        html = create_interactive_text_heatmap(
            text,
            spans,
            [marginals.get(f, 0.0) for f in features],
            method=method,
        )

    meta = {
        "mode": "synthetic",
        "reason": reason or "Attribution backend unavailable; showing mock data.",
        "method": method,
        "feature_level": level,
        "interaction_order": order,
        "feature_count": len(features),
    }

    inter_list = interactions.get(order, [])
    pairwise_for_tokens = interactions.get(2, []) if order != 2 else inter_list
    if not pairwise_for_tokens:
        pairwise_for_tokens = _fallback_pairwise_from_values(
            features,
            [marginals.get(f, 0.0) for f in features],
        )
    text_interaction_html = create_text_interaction_html(
        features,
        [marginals.get(f, 0.0) for f in features],
        _pairwise_to_index_interactions(pairwise_for_tokens, features),
        method=method,
        top_k=20,
        threshold=0.0,
    )
    figs = {
        "interactions": plot_top_interactions(inter_list, order=order, method=method),
    }

    return update(
        figs=figs,
        meta=meta,
        html=html,
        interaction_text_html=text_interaction_html,
        scoring_target_source="answer_input" if answer else "model_output",
        scoring_target_text=answer or "",
        reference_answer=answer or "",
        unmasked_answer="",
        debug_scores=None,
        scalarizer_used="logprob",
        score_full=None,
        score_empty=None,
        y_len_tokens=None,
    )


# def _compute_live_attributions(**kwargs) -> Tuple[Any, Any, Any, Any, Any]:
#     """
#     Placeholder for the real ProxySPEX + perplexity pipeline.
#     Raises until the attribution backend is implemented.
#     """
#     missing = [
#         name
#         for name, fn in {
#             "get_model": get_model,
#             "get_masker": get_masker,
#             "mask_text": mask_text,
#             "run_proxyspex": run_proxyspex,
#             "mobius_to_shapley": mobius_to_shapley,
#             "mobius_to_banzhaf": mobius_to_banzhaf,
#             "shapley_interactions": shapley_interactions,
#             "banzhaf_interactions": banzhaf_interactions,
#         }.items()
#         if fn is None
#     ]
#     if missing:
#         raise RuntimeError(
#             "Missing backend dependencies: " + ", ".join(sorted(missing))
#         )
#     raise NotImplementedError(
#         "Live attribution pipeline not wired yet. Integrate once ProxySPEX is ready."
#     )
def _compute_live_attributions(
    *,
    context: str,
    prompt: str,
    correct_answer: str,
    model_size: str,
    level: str,
    method: str,
    order: int,
    scalarizer: str = "logprob",
    embedding_model: str | None = None,
    progress=None,
) -> Tuple[Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any]:
    """
    Call the FastAPI /api/attributions + /api/interactions backends and turn
    the JSON into figures / table / HTML for Gradio.
    This version is very defensive and tries hard to extract interactions
    from whatever shape the backend returns.
    """
    method = _normalize_method(method)
    level = _normalize_level(level)
    order = 3 if int(order or 2) >= 3 else 2

    context = context or ""
    prompt = prompt or ""
    correct_answer = correct_answer or ""
    text_source = context or prompt or correct_answer or _DEMO_TEXT

    payload = {
        "context": context,
        "answer": correct_answer,
        "reference_answer": correct_answer,
        "prompt": prompt,
        "method": method,
        "mask_level": level,
        "order": int(order),
        "model_size": model_size,
        "scalarizer": scalarizer,
        "embedding_model": embedding_model,
        "debug": False,
    }

    if progress is not None:
        progress(0.1, desc="Calling attribution backend")

    # ---------- 1. /api/attributions  ----------
    url_attr = BACKEND_URL.rstrip("/") + "/api/attributions"
    try:
        resp_attr = requests.post(url_attr, json=payload, timeout=REQUEST_TIMEOUT)
    except requests.exceptions.ReadTimeout as exc:
        raise gr.Error(
            "Attribution request timed out. The backend may still be running. "
            "Consider reducing feature granularity or set ATTRLLM_REQUEST_TIMEOUT to a higher value."
        ) from exc
    if resp_attr.status_code >= 400:
        _raise_backend_error(resp_attr, "Attribution request")
    data_attr = resp_attr.json()

    if progress is not None:
        progress(0.35, desc="Received attribution payload")

    # ---------- 2. FEATURES + MARGINAL VALUES ----------
    features, feature_values = _extract_feature_series(data_attr)
    if not features:
        features = ["<no features>"]
        feature_values = [0.0]
    marginals = {feat: float(feature_values[idx]) for idx, feat in enumerate(features)}

    # ---------- 3. /api/interactions  ----------
    if progress is not None:
        progress(0.45, desc="Calling interactions backend")

    url_int = BACKEND_URL.rstrip("/") + "/api/interactions"
    try:
        resp_int = requests.post(url_int, json=payload, timeout=REQUEST_TIMEOUT)
    except requests.exceptions.ReadTimeout as exc:
        raise gr.Error(
            "Interaction request timed out. The backend may still be running. "
            "Consider reducing order or set ATTRLLM_REQUEST_TIMEOUT to a higher value."
        ) from exc
    if resp_int.status_code >= 400:
        _raise_backend_error(resp_int, "Interaction request")
    data_int = resp_int.json()

    # DEBUG: see top-level keys
    print("data_int keys:", list(data_int.keys()))

    inter_list_all = _extract_interactions_from_response(data_int, method, features)
    pairwise_for_network = [item for item in inter_list_all if len(item[0]) == 2]
    used_pairwise_fallback = False

    inter_list = inter_list_all
    if inter_list:
        filtered: List[Tuple[Tuple[str, ...], float]] = []
        for feats, val in inter_list:
            if len(feats) == order:
                filtered.append((feats, val))
        if filtered:
            inter_list = filtered

    if order != 2 and not pairwise_for_network:
        try:
            payload_pair = dict(payload)
            payload_pair["order"] = 2
            try:
                resp_pair = requests.post(url_int, json=payload_pair, timeout=REQUEST_TIMEOUT)
            except requests.exceptions.ReadTimeout as exc:
                raise gr.Error(
                    "Interaction request timed out. The backend may still be running. "
                    "Consider reducing order or set ATTRLLM_REQUEST_TIMEOUT to a higher value."
                ) from exc
            if resp_pair.status_code >= 400:
                _raise_backend_error(resp_pair, "Interaction request")
            data_pair = resp_pair.json()
            pairwise_for_network = [
                item for item in _extract_interactions_from_response(data_pair, method, features)
                if len(item[0]) == 2
            ]
        except Exception as exc:
            print("Pairwise interaction fetch failed:", exc)
    if not pairwise_for_network:
        if method == "influence":
            pairwise_for_network = []
        else:
            used_pairwise_fallback = True
            pairwise_for_network = _fallback_pairwise_from_values(features, feature_values)

    print("LIVE features:", features)
    print("LIVE inter_list (first 3):", inter_list[:3])
    if method == "influence":
        top_singletons = sorted(
            list(zip(features, feature_values)),
            key=lambda kv: abs(float(kv[1])),
            reverse=True,
        )[:10]
        top_pairs = sorted(
            pairwise_for_network,
            key=lambda kv: abs(float(kv[1])),
            reverse=True,
        )[:10]
        print(
            "[influence-ui-debug] "
            f"pairwise_source={'fallback_neighbors' if used_pairwise_fallback else 'backend'} "
            f"feature_count={len(features)} pair_count={len(pairwise_for_network)}"
        , flush=True)
        print("[influence-ui-debug] top_singletons:", top_singletons, flush=True)
        print("[influence-ui-debug] top_pairwise:", top_pairs, flush=True)

    text_interaction_html = create_text_interaction_html(
        features,
        feature_values,
        _pairwise_to_index_interactions(pairwise_for_network, features),
        method=method,
        top_k=20,
        threshold=0.0,
    )

    # ---------- 4. RESCALE VERY SMALL VALUES ----------
    max_abs = max((abs(v) for v in marginals.values()), default=0.0)
    scale = 1.0
    if 0 < max_abs < 1e-3:
        scale = 1e3
    if scale != 1.0:
        marginals = {k: v * scale for k, v in marginals.items()}
        inter_list = [(feats, val * scale) for feats, val in inter_list]
        feature_values = [val * scale for val in feature_values]

    # ---------- 5. INLINE TEXT HEATMAP ----------
    spans = None
    masking = data_attr.get("masking") or data_attr.get("mask") or {}
    if isinstance(masking, dict):
        spans = masking.get("feature_spans") or masking.get("spans")

    html = None
    if spans and len(spans) == len(feature_values):
        html = create_interactive_text_heatmap(
            context or text_source,
            spans,
            feature_values,
            method=method,
        )

    # ---------- 6. PLOTS + TABLES + META ----------
    inter_fig = plot_top_interactions(inter_list, order=order, method=method)

    if progress is not None:
        progress(0.8, desc="Rendering visualizations")

    y_len_tokens = data_attr.get("y_len_tokens")
    scoring_target_source = data_attr.get("scoring_target_source") or "model_output"
    scoring_target_text = data_attr.get("scoring_target_text")
    if scoring_target_text is None:
        scoring_target_text = correct_answer or data_attr.get("y_full") or ""

    meta = {
        "mode": "live",
        "backend_url_attr": url_attr,
        "backend_url_int": url_int,
        "method": method,
        "feature_level": level,
        "interaction_order": order,
        "model_size": model_size,
        "feature_count": len(features),
        "max_abs_value": max_abs,
        "scale_applied": scale,
        "scalarizer": data_attr.get("scalarizer_used", payload.get("scalarizer")),
        "scoring_target_source": scoring_target_source,
        "scoring_target_text_preview": str(scoring_target_text)[:200],
        "score_full": data_attr.get("score_full"),
        "score_empty": data_attr.get("score_empty"),
        "y_len_tokens": y_len_tokens,
        "logprob_full": data_attr.get("logprob_full"),
        "logprob_empty": data_attr.get("logprob_empty"),
        "min_logprob_seen": data_attr.get("min_logprob_seen"),
        "reference_answer_received": data_attr.get("reference_answer_received"),
        "answer_received": data_attr.get("answer_received"),
        "raw_attr_keys": list(data_attr.keys()),
        "raw_int_keys": list(data_int.keys()),
    }
    reference_answer = correct_answer
    unmasked_answer = data_attr.get("y_full") or data_attr.get("unmasked_answer") or ""
    debug_scores = data_attr.get("debug_scores") or None

    interaction_chips_html = create_interaction_token_view(
        features,
        feature_values,
        pairwise_for_network,
        method=method,
        layout="sentence" if level == "sentence" else "token",
    )
    figs = {
        "interactions": inter_fig,
    }

    if progress is not None:
        progress(1.0, desc="Done")

    return update(
        figs=figs,
        meta=meta,
        html=html,
        interaction_html=interaction_chips_html,
        interaction_text_html=text_interaction_html,
        scoring_target_source=scoring_target_source,
        scoring_target_text=str(scoring_target_text),
        reference_answer=reference_answer,
        unmasked_answer=unmasked_answer,
        debug_scores=debug_scores,
        scalarizer_used=data_attr.get("scalarizer_used", payload.get("scalarizer")),
        score_full=data_attr.get("score_full"),
        score_empty=data_attr.get("score_empty"),
        y_len_tokens=y_len_tokens,
    )


# ═══════════════════════════════════════════════════════════════════════════
# CLIP-based live compute helpers  (Custom Image / Custom Multimodal tabs)
# ═══════════════════════════════════════════════════════════════════════════

_CLIP_MODEL_MAP: Dict[str, str] = {
    "CLIP (openai/clip-vit-base-patch32)": "openai/clip-vit-base-patch32",
    "BiomedCLIP": "microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224",
}


def _get_clip_scorer(model_display: str) -> "CrossModalCLIPScorer":
    """Load or return cached CLIP scorer.  Apply dot-mask fix."""
    model_name = _CLIP_MODEL_MAP.get(model_display, model_display)
    if model_name in _clip_scorer_cache:
        return _clip_scorer_cache[model_name]

    import torch as _torch
    device = "cuda" if _torch.cuda.is_available() else "cpu"
    cfg = PipelineConfig(clip_model_name=model_name, device=device)
    scorer = CrossModalCLIPScorer(cfg)

    # Dot-mask fix: use "." (ID 269) instead of EOS to avoid CLIP argmax-pooling shift
    _neutral_ids = scorer.processor.tokenizer.encode(".", add_special_tokens=False)
    if _neutral_ids:
        scorer.unk_token_id = _neutral_ids[0]

    _clip_scorer_cache[model_name] = scorer
    return scorer


def _run_clip_attribution(
    image: Image.Image,
    caption: str,
    clip_model: str,
    seg_mode: str,
    grid_size: int,
    method: str,
    seed: int,
    progress=None,
) -> Dict[str, Any]:
    """
    Core CLIP cross-modal attribution pipeline shared by both custom tabs.

    Returns a dict with regions, token_players, values, interactions,
    overlay images, masked images, and influence matrix.
    """
    import numpy as np

    if not _CLIP_PIPELINE_AVAILABLE:
        raise gr.Error(
            "CLIP pipeline not available. Ensure attribution.set_mm is importable "
            "(requires transformers, lightgbm, numpy, scipy)."
        )

    method = _normalize_method(method)

    # Check LaMa availability, fall back to blur
    try:
        from simple_lama_inpainting import SimpleLama  # noqa: F401
        mask_style = "lama"
    except ImportError:
        mask_style = "blur"

    import torch as _torch
    device = "cuda" if _torch.cuda.is_available() else "cpu"
    model_name = _CLIP_MODEL_MAP.get(clip_model, clip_model)

    cfg = PipelineConfig(
        mode="patch" if seg_mode == "Patch Grid" else "unsam",
        grid_size=int(grid_size),
        mask_style=mask_style,
        clip_model_name=model_name,
        max_tokens=15,
        method=method,
        max_order=2,
        top_k_interactions=15,
        random_seed=int(seed),
        device=device,
    )

    if progress is not None:
        progress(0.05, desc="Loading CLIP model...")
    scorer = _get_clip_scorer(clip_model)

    # Step 1: Featurise image
    if progress is not None:
        progress(0.10, desc="Segmenting image...")
    try:
        regions = featurise(image, cfg)
    except Exception as exc:
        if seg_mode != "Patch Grid":
            raise gr.Error(
                f"UnSAM segmentation failed: {exc}. "
                "Try using 'Patch Grid' instead."
            ) from exc
        raise

    # Step 2: Tokenise caption
    if progress is not None:
        progress(0.15, desc="Tokenising caption...")
    token_players, full_token_ids = tokenise_caption(
        caption, scorer.processor, cfg, offset=len(regions)
    )

    n_img = len(regions)
    n_tok = len(token_players)
    n_total = n_img + n_tok

    # Step 3: Build cross-modal set function
    if progress is not None:
        progress(0.20, desc="Building set function...")
    game = build_cross_modal_set_function(
        image, regions, token_players, full_token_ids, scorer, cfg
    )

    # Step 4: Run ProxySPEX (run_proxyspex wraps the set function for 2D batch calls)
    _raw_labels = [r.label for r in regions] + [tp.label for tp in token_players]
    # all_labels is rebuilt after tok_vals disambiguation below; _raw_labels for ProxySPEX
    if progress is not None:
        progress(0.25, desc=f"Running ProxySPEX (n={n_total})...")
    mobius = run_proxyspex(game, _raw_labels, max_order=2, seed=int(seed))

    # Step 5: Derive Shapley/Banzhaf values
    if progress is not None:
        progress(0.70, desc="Computing values...")
    if method == "banzhaf":
        values = mobius_to_banzhaf(mobius)
    else:
        values = mobius_to_shapley(mobius)

    # Split into image and token values
    # Disambiguate duplicate labels (e.g., two "the" tokens) by appending #N
    img_vals = {regions[i].label: float(values.get((i,), 0.0)) for i in range(n_img)}
    tok_vals = {}
    _tok_label_counts: Dict[str, int] = {}
    for j, tp in enumerate(token_players):
        label = tp.label
        count = _tok_label_counts.get(label, 0)
        _tok_label_counts[label] = count + 1
        key = f"{label}#{count}" if count > 0 else label
        tok_vals[key] = float(values.get((n_img + j,), 0.0))

    # Rebuild all_labels with disambiguated token labels
    all_labels = list(img_vals.keys()) + list(tok_vals.keys())

    # Step 6: Extract interactions
    interactions = extract_interactions(mobius, order=2, top_k=15)
    cross_per_token, cross_global_top5 = extract_cross_per_token(mobius, n_img, n_tok)

    # Image-image and token-token interactions
    img_filter = lambda loc: all(i < n_img for i in loc)
    tok_filter = lambda loc: all(i >= n_img for i in loc)
    interactions_img = extract_interactions(mobius, order=2, top_k=10, player_filter=img_filter)
    interactions_tok = extract_interactions(mobius, order=2, top_k=10, player_filter=tok_filter)

    # Cross-modal interactions (for bar chart)
    cross_filter = lambda loc: any(i < n_img for i in loc) and any(i >= n_img for i in loc)
    cross_interactions = extract_interactions(mobius, order=2, top_k=15, player_filter=cross_filter)

    # Step 7: Build influence matrix [n_img x n_tok]
    influence_matrix = np.zeros((n_img, n_tok))
    for loc, val in cross_interactions:
        img_indices = [i for i in loc if i < n_img]
        tok_indices = [i - n_img for i in loc if i >= n_img]
        for ii in img_indices:
            for tj in tok_indices:
                if 0 <= ii < n_img and 0 <= tj < n_tok:
                    influence_matrix[ii, tj] += float(val)

    # Step 8: Render overlay and segmap
    if progress is not None:
        progress(0.75, desc="Rendering overlay...")
    img_val_list = [float(values.get((i,), 0.0)) for i in range(n_img)]
    overlay_rgba = render_overlay(image, regions, img_val_list)
    base_rgba = image.convert("RGBA")
    overlay_img = Image.alpha_composite(base_rgba, overlay_rgba).convert("RGB")
    overlay_b64 = _encode_image_to_b64(overlay_img)

    segmap_img = render_segmentation_map(image, regions)
    segmap_b64 = _encode_image_to_b64(segmap_img)

    # Step 9: Build segment bboxes (% coordinates for interactive view)
    w, h = image.size
    segment_bboxes = []
    for reg in regions:
        x0, y0, x1, y1 = reg.bbox
        segment_bboxes.append({
            "x0_pct": 100.0 * x0 / w,
            "y0_pct": 100.0 * y0 / h,
            "w_pct": 100.0 * (x1 - x0) / w,
            "h_pct": 100.0 * (y1 - y0) / h,
            "cx_pct": 100.0 * (x0 + x1) / 2 / w,
            "cy_pct": 100.0 * (y0 + y1) / 2 / h,
        })

    # Step 10: Generate masked images for browser
    if progress is not None:
        progress(0.80, desc="Generating masked images...")
    masked_images: Dict[str, Image.Image] = {}
    for i, reg in enumerate(regions):
        # "removed" β€” mask only this region
        coal_removed = [1] * n_img
        coal_removed[i] = 0
        removed_img = apply_image_mask(
            image, regions, coal_removed, style=cfg.mask_style,
            blur_radius=cfg.blur_radius, cfg=cfg,
        )
        masked_images[f"{reg.label} removed"] = removed_img

    if progress is not None:
        progress(0.90, desc="Done computing.")

    return {
        "regions": regions,
        "token_players": token_players,
        "all_labels": all_labels,
        "image_values": img_vals,
        "token_values": tok_vals,
        "values": values,
        "mobius": mobius,
        "interactions": interactions,
        "interactions_img": interactions_img,
        "interactions_tok": interactions_tok,
        "cross_interactions": cross_interactions,
        "cross_per_token": cross_per_token,
        "cross_global_top5": cross_global_top5,
        "influence_matrix": influence_matrix,
        "overlay_img": overlay_img,
        "overlay_b64": overlay_b64,
        "segmap_img": segmap_img,
        "segmap_b64": segmap_b64,
        "segment_bboxes": segment_bboxes,
        "masked_images": masked_images,
        "method": method,
        "n_img": n_img,
        "n_tok": n_tok,
        "mask_style": mask_style,
        "seg_mode": seg_mode,
        "grid_size": int(grid_size),
    }


def _build_masked_choices(masked_images: Dict[str, Image.Image]) -> List[str]:
    """Return sorted list of masked image choice labels."""
    return sorted(masked_images.keys())


def _on_masked_image_select(choice: str, state: Dict) -> Optional[Image.Image]:
    """Return the masked PIL image for a dropdown choice."""
    if not state or not choice:
        return None
    return state.get(choice)


def _compute_image_attributions_clip(
    image: Image.Image,
    caption: str,
    clip_model: str,
    seg_mode: str,
    grid_size: int,
    method: str,
    seed: int,
    progress=None,
):
    """Compute image-only attributions using CLIP pipeline.  Returns UI outputs."""
    if image is None:
        raise gr.Error("Please upload an image.")
    if not caption or not caption.strip():
        raise gr.Error("Please provide a caption or description.")

    result = _run_clip_attribution(
        image, caption.strip(), clip_model, seg_mode, int(grid_size),
        method, int(seed or 0), progress=progress,
    )

    # Build region bar chart
    seg_labels = list(result["image_values"].keys())
    seg_vals = list(result["image_values"].values())
    region_chart = create_shapley_bar_chart(seg_labels, seg_vals, "Region Attribution")

    # Build masked image state and dropdown choices
    masked_state = result["masked_images"]
    choices = _build_masked_choices(masked_state)

    meta = {
        "mode": "image_clip",
        "method": result["method"],
        "clip_model": clip_model,
        "seg_mode": result["seg_mode"],
        "grid_size": result["grid_size"],
        "mask_style": result["mask_style"],
        "n_regions": result["n_img"],
        "n_tokens": result["n_tok"],
    }

    if progress is not None:
        progress(1.0, desc="Done")

    # Returns: original_img, overlay_img, region_chart, masked_dropdown, masked_img, masked_state, meta
    return (
        image,
        result["overlay_img"],
        region_chart,
        gr.update(choices=choices, value=choices[0] if choices else None),
        masked_state.get(choices[0]) if choices else None,
        masked_state,
        meta,
    )


def _compute_mm_attributions_clip(
    image: Image.Image,
    caption: str,
    clip_model: str,
    seg_mode: str,
    grid_size: int,
    method: str,
    seed: int,
    progress=None,
):
    """Compute cross-modal attributions using CLIP pipeline.  Returns UI outputs."""
    import numpy as np

    if image is None:
        raise gr.Error("Please upload an image.")
    if not caption or not caption.strip():
        raise gr.Error("Please provide a caption or description.")

    result = _run_clip_attribution(
        image, caption.strip(), clip_model, seg_mode, int(grid_size),
        method, int(seed or 0), progress=progress,
    )

    all_labels = result["all_labels"]
    n_img = result["n_img"]
    n_tok = result["n_tok"]

    # Region bar chart
    seg_labels = list(result["image_values"].keys())
    seg_vals = list(result["image_values"].values())
    region_chart = create_shapley_bar_chart(seg_labels, seg_vals, "Region Attribution")

    # Token bar chart
    tok_labels = list(result["token_values"].keys())
    tok_vals = list(result["token_values"].values())
    token_chart = create_shapley_bar_chart(tok_labels, tok_vals, "Token Attribution")

    # Cross-modal bar chart β€” expects List[Tuple[Tuple[str, str], float]]
    cross_pairs = []
    for loc, val in result["cross_interactions"]:
        img_parts = [all_labels[i] for i in loc if i < n_img]
        tok_parts = [all_labels[i] for i in loc if i >= n_img]
        if img_parts and tok_parts:
            cross_pairs.append(((img_parts[0], tok_parts[0]), float(val)))
    cross_chart = create_cross_modal_bar_chart(cross_pairs, "Cross-Modal Interactions", top_k=15)

    # Influence heatmap
    heatmap = create_influence_heatmap(
        seg_labels, tok_labels, result["influence_matrix"],
        "Influence Heatmap (Regions x Tokens)"
    )

    # Interactive cross-modal HTML view
    # Build clip_summary dict matching what benchmark_interaction expects
    clip_summary = {
        "image_region_values": [
            {"label": seg_labels[i], "value": float(seg_vals[i])} for i in range(n_img)
        ],
        "token_values": [
            {"label": tok_labels[j], "value": float(tok_vals[j])} for j in range(n_tok)
        ],
        "cross_modal_interactions": [
            {"label": " x ".join(all_labels[i] for i in loc), "value": float(val)}
            for loc, val in result["cross_global_top5"]
        ],
    }
    image_b64 = _encode_image_to_b64(image)
    interaction_html = create_benchmark_interaction_html(
        image_b64=image_b64,
        clip_summary=clip_summary,
        vllm_logprob=None,
        caption=caption,
        all_cross_modal_pairs=[
            {
                "pair": (
                    all_labels[loc[0]] if loc[0] < n_img else all_labels[loc[1]],
                    all_labels[loc[1]] if loc[1] >= n_img else all_labels[loc[0]],
                ),
                "value": float(val),
            }
            for loc, val in result["cross_interactions"]
        ],
        segmap_b64=result["segmap_b64"],
        overlay_b64=result["overlay_b64"],
        segment_bboxes=result["segment_bboxes"],
        label_map_b64="",
        image_width=image.size[0],
        image_height=image.size[1],
        title="Cross-Modal Interaction View",
    )

    # Masked image state
    masked_state = result["masked_images"]
    choices = _build_masked_choices(masked_state)

    meta = {
        "mode": "multimodal_clip",
        "method": result["method"],
        "clip_model": clip_model,
        "seg_mode": result["seg_mode"],
        "grid_size": result["grid_size"],
        "mask_style": result["mask_style"],
        "n_regions": n_img,
        "n_tokens": n_tok,
    }

    if progress is not None:
        progress(1.0, desc="Done")

    # Returns: original_img, overlay_img, region_chart, token_chart,
    #          cross_chart, heatmap, interaction_html,
    #          masked_dropdown, masked_img, masked_state, meta
    return (
        image,
        result["overlay_img"],
        region_chart,
        token_chart,
        cross_chart,
        heatmap,
        interaction_html,
        gr.update(choices=choices, value=choices[0] if choices else None),
        masked_state.get(choices[0]) if choices else None,
        masked_state,
        meta,
    )

def on_select_example(
    dataset,
    ex_id,
    model_size,
    order,
    method,
    scalarizer=None,
    feature_level=None,
):
    """
    Public mode handler: load a precomputed example and render figures.

    Args:
        dataset (str): dataset name
        ex_id (str): example id
        model_size (str): "small" | "medium" | "large"
        order (int): interaction order (2 or 3)
        method (str): "shapley" | "banzhaf" | "influence"

    Returns:
        tuple ordered as:
            (
                context,
                prompt,
                answer,
                interactions_plot,
                interactions_token_html,
                text_html,
                meta_json,
            )
    """
    get_res = get_result_by_id if get_result_by_id is not None else _public_get_result_from_file
    model_size = _normalize_model_size(model_size)
    example = {"context": "", "prompt": "", "answer": ""}
    if get_example_by_id is not None:
        try:
            example = get_example_by_id(dataset, ex_id)
        except Exception:
            pass
    result = get_res(
        model_size,
        dataset,
        ex_id,
        scalarizer=scalarizer,
        feature_level=feature_level,
    ) or {}
    payload = result.get(method, {})
    # Your JSON: features (list of strings) + mobius_dict. Convert to UI format if needed.
    feats = payload.get("features") if isinstance(payload, dict) else None
    if isinstance(feats, list) and feats and not isinstance(feats[0], dict):
        payload = _normalize_public_payload_fallback(payload, method)

    features, feature_values = _extract_feature_series(payload)
    if not features:
        features = ["<no features>"]
        feature_values = [0.0]
    # Influence scores are non-negative (squared Fourier coefficients)
    if method == "influence":
        feature_values = [abs(v) for v in feature_values]
    marginals = {feat: float(feature_values[idx]) for idx, feat in enumerate(features)}
    interactions = _resolve_interactions(payload, order)
    if method == "influence":
        interactions = [(feats, abs(val)) for feats, val in interactions]
        pairwise = _resolve_interactions(payload, 2)
        if not pairwise:
            mixed = payload.get("interactions")
            normalized = _normalize_interactions(mixed)
            if normalized:
                pairwise = [item for item in normalized if len(item[0]) == 2]
        pairwise = [(feats, abs(val)) for feats, val in pairwise]
    else:
        pairwise = _resolve_pairwise(payload, features, feature_values)
    if method == "influence":
        top_singletons = sorted(
            list(zip(features, feature_values)),
            key=lambda kv: abs(float(kv[1])),
            reverse=True,
        )[:10]
        top_pairs = sorted(
            pairwise,
            key=lambda kv: abs(float(kv[1])),
            reverse=True,
        )[:10]
        print(
            "[influence-ui-debug][public] "
            f"dataset={dataset} ex_id={ex_id} feature_count={len(features)} pair_count={len(pairwise)}"
        , flush=True)
        print("[influence-ui-debug][public] top_singletons:", top_singletons, flush=True)
        print("[influence-ui-debug][public] top_pairwise:", top_pairs, flush=True)
    payload_level = (
            payload.get("mask_level")
        or payload.get("feature_level")
        or payload.get("level")
        or (result.get("meta", {}) if isinstance(result, dict) else {}).get("feature_level")
    )
    layout_mode = "sentence" if _normalize_level(payload_level) == "sentence" else "token"

    inter = plot_top_interactions(interactions, order=order, method=method)

    spans = payload.get("feature_spans") or payload.get("spans")
    if not spans:
        # Precomputed JSON payloads may not include explicit spans.
        # Reconstruct spans from context + feature level so Text View can render.
        _, fallback_spans, _ = _chunk_text_for_visualization(
            example.get("context", ""),
            _normalize_level(payload_level),
        )
        if fallback_spans and len(fallback_spans) == len(feature_values):
            spans = fallback_spans
    html = None
    if spans and len(spans) == len(feature_values):
        html = create_interactive_text_heatmap(
            example.get("context", ""),
            spans,
            feature_values,
            method=method,
        )

    # Compute the wrong-answer payload up-front so the dual heatmap branch
    # (which rewrites text_interaction_html below) has it ready.
    _wrong_values_for_dual: Optional[List[float]] = None
    _wrong_pairwise_for_dual: Optional[List[Any]] = None
    _wrong_features_for_dual: Optional[List[str]] = None
    try:
        from visualization.wrong_answer_examples import has_wrong_answer_view as _has_wrong_view
    except Exception:
        _has_wrong_view = None
    _is_wrong_view = bool(
        _has_wrong_view is not None
        and html is not None
        and spans
        and _has_wrong_view(dataset, ex_id, scalarizer or "", feature_level or "")
    )
    if _is_wrong_view:
        wrong_result = _public_get_model_answer_short_from_file(
            model_size, dataset, ex_id, scalarizer or "geomean_jointprob",
            feature_level or "word",
        )
        wrong_payload = wrong_result.get(method, {}) if wrong_result else {}
        wrong_features_local, wrong_values_local = _extract_feature_series(wrong_payload)
        if method == "influence":
            wrong_values_local = [abs(v) for v in wrong_values_local]
        if wrong_features_local and len(wrong_values_local) == len(feature_values):
            # Build wrong-side pairwise edges, mirroring the GT logic above.
            wrong_pairwise = _resolve_interactions(wrong_payload, 2)
            if not wrong_pairwise:
                mixed = wrong_payload.get("interactions") if isinstance(wrong_payload, dict) else None
                normalized = _normalize_interactions(mixed)
                if normalized:
                    wrong_pairwise = [item for item in normalized if len(item[0]) == 2]
            if method == "influence":
                wrong_pairwise = [(f, abs(v)) for f, v in (wrong_pairwise or [])]
            else:
                # Best-effort: if no explicit pairwise, derive from wrong feature values
                if not wrong_pairwise:
                    wrong_pairwise = _resolve_pairwise(wrong_payload, wrong_features_local, wrong_values_local)
            _wrong_values_for_dual = wrong_values_local
            _wrong_pairwise_for_dual = wrong_pairwise or []
            _wrong_features_for_dual = wrong_features_local
        else:
            _is_wrong_view = False

    meta = {
        "dataset": dataset,
        "example_id": ex_id,
        "model_size": model_size,
        "method": method,
        "order": order,
        "feature_count": len(features),
        "payload_keys": sorted(payload.keys()),
    }
    if "meta" in result:
        meta["source_meta"] = result["meta"]

    interaction_chips_html = create_interaction_token_view(
        features,
        feature_values,
        pairwise or [item for item in interactions if len(item[0]) == 2],
        method=method,
        layout=layout_mode,
    )
    text_interaction_html = create_text_interaction_html(
        features,
        feature_values,
        _pairwise_to_index_interactions(
            pairwise or [item for item in interactions if len(item[0]) == 2],
            features,
        ),
        method=method,
        top_k=20,
        threshold=0.0,
    )

    # For the 30 wrong-answer examples, replace the visible Text Interaction
    # view with two chip+arc panels side-by-side (vs Ground Truth | vs Model
    # Answer (Wrong)) plus a single shared legend + RAW TEXT below.
    if (
        _is_wrong_view
        and _wrong_values_for_dual is not None
        and _wrong_features_for_dual is not None
    ):
        gt_view = create_text_interaction_html(
            features,
            feature_values,
            _pairwise_to_index_interactions(
                pairwise or [item for item in interactions if len(item[0]) == 2],
                features,
            ),
            method=method,
            top_k=20,
            threshold=0.0,
        )
        wrong_view = create_text_interaction_html(
            _wrong_features_for_dual,
            _wrong_values_for_dual,
            _pairwise_to_index_interactions(
                _wrong_pairwise_for_dual or [],
                _wrong_features_for_dual,
            ),
            method=method,
            top_k=20,
            threshold=0.0,
        )

        method_label = (method or "attribution").title()
        gt_max_abs = max((abs(v) for v in feature_values), default=0.0) or 1.0
        wrong_max_abs = max((abs(v) for v in _wrong_values_for_dual), default=0.0) or 1.0

        from html import escape as _escape
        raw_text = example.get("context", "") or ""
        raw_text_html = _escape(raw_text).replace("\n", "<br/>") if raw_text else ""

        # CSS scoped to .dual-heatmap-row hides the per-side legend so we can
        # show one shared legend below; tightens the per-card max width so two
        # views fit comfortably side-by-side.
        dual_css = (
            "<style>"
            ".dual-heatmap-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;align-items:start;}"
            ".dual-heatmap-row .text-interaction-side-panel{display:none !important;}"
            ".dual-heatmap-row .text-interaction-root{flex:1 1 100%;}"
            ".dual-heatmap-row .text-interaction-card{flex:1 1 100%;max-width:100%;}"
            ".dual-heatmap-shared{margin-top:16px;display:grid;grid-template-columns:1fr 1fr;gap:16px;}"
            ".dual-heatmap-shared .shared-card{background:#f8f5ff;border:1px solid #e2d6f3;"
            "border-radius:12px;padding:12px 14px;box-shadow:0 4px 10px rgba(80,50,140,0.05);}"
            ".dual-heatmap-shared .shared-legend-bar{display:flex;align-items:center;gap:8px;margin:6px 0;}"
            ".dual-heatmap-shared .shared-legend-label{font-size:12px;color:#6f5a72;text-transform:uppercase;letter-spacing:.04em;}"
            ".dual-heatmap-shared .shared-legend-gradient{flex:1;height:10px;border-radius:999px;"
            "background:linear-gradient(90deg,#dd1313 0%,#d8c6f0 50%,#4a1c87 100%);}"
            ".dual-heatmap-shared .shared-legend-note{font-size:12px;color:#6f5a72;margin:4px 0 0 0;}"
            ".dual-heatmap-shared .shared-raw-text p{margin:6px 0 0 0;line-height:1.5;color:#3a2b4a;}"
            "@media (prefers-color-scheme: dark){"
            ".dual-heatmap-shared .shared-card{background:#111a2b;border-color:#33435f;}"
            ".dual-heatmap-shared .shared-legend-label,.dual-heatmap-shared .shared-legend-note,"
            ".dual-heatmap-shared .shared-raw-text p{color:#a9b6cb;}}"
            "@media (max-width: 900px){"
            ".dual-heatmap-row,.dual-heatmap-shared{grid-template-columns:1fr;}}"
            "</style>"
        )

        shared_block = (
            '<div class="dual-heatmap-shared">'
            '<div class="shared-card">'
            f'<strong>{method_label} legend</strong>'
            '<div class="shared-legend-bar">'
            '<span class="shared-legend-label">Negative</span>'
            '<div class="shared-legend-gradient"></div>'
            '<span class="shared-legend-label">Positive</span>'
            '</div>'
            '<p class="shared-legend-note">'
            f'Ground-truth max |value| = {gt_max_abs:.4f}; '
            f'wrong-answer max |value| = {wrong_max_abs:.4f}. '
            'Hover tokens for exact scores.'
            '</p>'
            '</div>'
            '<div class="shared-card shared-raw-text">'
            '<strong>Raw text</strong>'
            f'<p>{raw_text_html or "<em>No context available.</em>"}</p>'
            '</div>'
            '</div>'
        )

        text_interaction_html = (
            f'{dual_css}'
            '<div class="dual-heatmap-row">'
            '<div>'
            '<div class="heatmap-caption" '
            'style="font-weight:600;margin-bottom:6px;">vs Ground Truth</div>'
            f'{gt_view}'
            '</div>'
            '<div>'
            '<div class="heatmap-caption" '
            'style="font-weight:600;margin-bottom:6px;">vs Model Answer (Wrong)</div>'
            f'{wrong_view}'
            '</div>'
            '</div>'
            f'{shared_block}'
        )
        print(
            f"[wrong-answer] dual chip+lines view rendered for {dataset}/{ex_id} "
            f"(gt_features={len(features)} wrong_features={len(_wrong_features_for_dual)} "
            f"gt_pairs={len(pairwise or [])} wrong_pairs={len(_wrong_pairwise_for_dual or [])})",
            flush=True,
        )

    figs = {
        "interactions": inter,
    }
    outputs = update(
        figs=figs,
        meta=meta,
        html=html,
        interaction_html=interaction_chips_html,
        interaction_text_html=text_interaction_html,
    )
    return (
        example.get("context", ""),
        example.get("prompt", ""),
        _extract_answer(example),
        *outputs,
    )


def on_click_compute(
    context,
    prompt,
    correct_answer,
    model_size,
    level,
    method,
    scalarizer,
    embedding_model,
    progress=gr.Progress(track_tqdm=True),
):
#     """
#     Developer mode handler: compute (or mock) attributions and render figures.
#     """
#     method = _normalize_method(method)
#     level = _normalize_level(level)
#     order = 3 if int(order or 2) >= 3 else 2

#     context = context or ""
#     prompt = prompt or ""
#     correct_answer = correct_answer or ""

#     try:
#         return _compute_live_attributions(
#             context=context,
#             prompt=prompt,
#             correct_answer=correct_answer,
#             model_size=model_size,
#             level=level,
#             method=method,
#             order=order,
#             progress=progress,
#         )
#     except Exception as exc:  # pragma: no cover - best-effort fallback
#         return _synthetic_attribution_pipeline(
#             context,
#             prompt,
#             correct_answer,
#             method=method,
#             level=level,
#             order=order,
#             reason=str(exc),
#         )

    method = _normalize_method(method)
    level = _normalize_level(level)
    model_size = _normalize_model_size(model_size)
    order = 2

    context = context or ""
    prompt = prompt or ""
    correct_answer = correct_answer or ""

    return _compute_live_attributions(
        context=context,
        prompt=prompt,
        correct_answer=correct_answer,
        model_size=model_size,
        level=level,
        method=method,
        order=order,
        scalarizer=scalarizer,
        embedding_model=embedding_model,
        progress=progress,
    )


# ---------------------------------------------------------------------------
# Multimodal precomputed example handlers (MIMIC-CXR, ISIC, MS-COCO)
# ---------------------------------------------------------------------------

# ── MIMIC-CXR Tab Handlers ────────────────────────────────────────────────

_MIMIC_METHOD_NAMES = [
    "BiomedCLIP Cross-Modal",
    "LLaVA-Med Log-Prob",
    "LLaVA-Med Generation",
]


def _on_select_mimic_example(example_id, method_label: str = "Influence"):
    """Load a MIMIC-CXR example and return data for the MIMIC tab."""
    # 15 outputs: caption, original, findings, interpretation,
    #   biomedclip_overlay, biomedclip_token_plot, biomedclip_region_plot,
    #   llavamed_unsam_lp_overlay, llavamed_unsam_lp_plot,
    #   llavamed_unsam_gen_overlay, llavamed_unsam_gen_plot,
    #   biomedclip_interaction_html, meta, results_state, compare_method_a
    n_outputs = 15
    empty = tuple([""] + [None] * (n_outputs - 1))
    if not _MIMIC_AVAILABLE or not example_id:
        return empty

    method = (method_label or "Influence").lower()
    method_display = "Influence" if method == "influence" else "Shapley"

    _base_chart = globals()["create_shapley_bar_chart"]
    _base_html = globals()["create_benchmark_interaction_html"]

    def create_shapley_bar_chart(labels, values, title="Shapley Values", **kwargs):  # noqa: F811
        kwargs.setdefault("method_label", method_display)
        return _base_chart(labels, values, title.replace("Shapley", method_display), **kwargs)

    def create_benchmark_interaction_html(**kwargs):  # noqa: F811
        kwargs.setdefault("method_label", method_display)
        return _base_html(**kwargs)

    try:
        data = load_mimic_example(example_id, method=method)
    except Exception:
        return empty

    caption = data.get("caption", "")
    findings = data.get("findings", "")
    original_img = data.get("original_image_path")
    meta = data.get("meta", {})
    category = meta.get("category", "")

    # ── BiomedCLIP ───────────────────────────────────────────────────
    biomedclip_overlay_labeled = None
    biomedclip_region_plot = None
    biomedclip_token_plot = None
    biomedclip_interaction_html = ""

    segment_bboxes = None
    label_map_b64 = ""

    if data.get("has_biomedclip"):
        bc_summary = data["biomedclip"]["summary"]
        bc_overlay_raw = data["biomedclip"]["image_paths"].get("overlay")
        bc_original = data["biomedclip"]["image_paths"].get("original", "")
        bc_segmap = data["biomedclip"]["image_paths"].get("segmap", "")
        bc_n_segs = len(bc_summary.get("image_region_values", []))

        bc_bboxes, bc_label_map_b64 = None, ""
        if bc_original and bc_segmap and bc_n_segs > 0:
            try:
                bc_bboxes, bc_label_map_b64 = extract_segment_regions(
                    bc_original, bc_segmap, bc_n_segs)
            except Exception:
                pass

        if bc_overlay_raw:
            biomedclip_overlay_labeled = draw_segment_labels(
                bc_overlay_raw, bc_summary.get("image_region_values", []),
                segment_bboxes=bc_bboxes,
                label_map_b64=bc_label_map_b64,
                original_path=bc_original)

        bc_r_labels = [v["label"] for v in bc_summary.get("image_region_values", [])]
        bc_r_values = [v["value"] for v in bc_summary.get("image_region_values", [])]
        if bc_r_labels:
            biomedclip_region_plot = create_shapley_bar_chart(
                bc_r_labels, bc_r_values, "BiomedCLIP β€” Image Region Shapley Values")

        bc_merged = merge_subword_token_values(bc_summary.get("token_values", []), caption)
        bc_t_labels = [v["label"] for v in bc_merged]
        bc_t_values = [v["value"] for v in bc_merged]
        if bc_t_labels:
            biomedclip_token_plot = create_shapley_bar_chart(
                bc_t_labels, bc_t_values, "BiomedCLIP β€” Caption Word Shapley Values")

        # Interactive cross-modal HTML
        bc_image_b64 = data["biomedclip"].get("image_b64", {}).get("original", "")
        bc_overlay_b64 = data["biomedclip"].get("image_b64", {}).get("overlay", "")
        bc_all_cross = data["biomedclip"].get("all_cross_modal_pairs", [])
        bc_segmap_b64 = ""
        if bc_segmap:
            import os as _os
            if _os.path.exists(bc_segmap):
                import base64 as _b64
                with open(bc_segmap, "rb") as _f:
                    bc_segmap_b64 = _b64.b64encode(_f.read()).decode("ascii")
        biomedclip_interaction_html = create_benchmark_interaction_html(
            image_b64=bc_image_b64,
            clip_summary=bc_summary,
            vllm_logprob=None,
            caption=caption,
            all_cross_modal_pairs=bc_all_cross,
            segmap_b64=bc_segmap_b64,
            overlay_b64=bc_overlay_b64,
            segment_bboxes=bc_bboxes,
            label_map_b64=bc_label_map_b64,
            title="BiomedCLIP Cross-Modal Interaction View β€” click segments or words",
        )
        segment_bboxes = bc_bboxes
        label_map_b64 = bc_label_map_b64

    # ── LLaVA-Med UnSAM ─────────────────────────────────────────────
    # Draw two separate overlays β€” one colored by Log-Prob values, one by
    # Generation values β€” since the signs often differ between methods.
    llavamed_unsam_lp_overlay_img = None
    llavamed_unsam_gen_overlay_img = None
    llavamed_unsam_lp_plot = None
    llavamed_unsam_gen_plot = None

    if data.get("has_llavamed_unsam_logprob") or data.get("has_llavamed_unsam_gen"):
        lu_segmap = data.get("llavamed_unsam_segmap_path", "")
        lu_original = data.get("llavamed_unsam_original_path", "") or (original_img or "")
        lu_bboxes, lu_label_map_b64 = None, ""
        if lu_segmap and lu_original:
            n_lu_segs = 0
            if data.get("has_llavamed_unsam_logprob"):
                n_lu_segs = len(data["llavamed_unsam_logprob"].get("image_region_values", []))
            elif data.get("has_llavamed_unsam_gen"):
                n_lu_segs = len(data["llavamed_unsam_gen"].get("image_region_values", []))
            if n_lu_segs > 0:
                try:
                    lu_bboxes, lu_label_map_b64 = extract_segment_regions(
                        lu_original, lu_segmap, n_lu_segs)
                except Exception:
                    pass

        if data.get("has_llavamed_unsam_logprob"):
            lu_lp = rename_patch_labels(
                data["llavamed_unsam_logprob"].get("image_region_values", []))
            if lu_lp:
                llavamed_unsam_lp_plot = create_shapley_bar_chart(
                    [v["label"] for v in lu_lp],
                    [v["value"] for v in lu_lp],
                    "LLaVA-Med Log-Prob β€” Segment Shapley Values",
                )
                overlay_path = data["llavamed_unsam_logprob"].get("overlay_path", "")
                if overlay_path:
                    llavamed_unsam_lp_overlay_img = draw_segment_labels(
                        overlay_path, lu_lp,
                        segment_bboxes=lu_bboxes,
                        label_map_b64=lu_label_map_b64,
                        original_path=lu_original)

        if data.get("has_llavamed_unsam_gen"):
            lu_gen = rename_patch_labels(
                data["llavamed_unsam_gen"].get("image_region_values", []))
            if lu_gen:
                llavamed_unsam_gen_plot = create_shapley_bar_chart(
                    [v["label"] for v in lu_gen],
                    [v["value"] for v in lu_gen],
                    "LLaVA-Med Generation β€” Segment Shapley Values",
                )
                # Use the log-prob overlay as the base image and recolor by gen values
                overlay_path = (data["llavamed_unsam_gen"].get("overlay_path", "")
                                or data.get("llavamed_unsam_logprob", {}).get("overlay_path", ""))
                if overlay_path:
                    llavamed_unsam_gen_overlay_img = draw_segment_labels(
                        overlay_path, lu_gen,
                        segment_bboxes=lu_bboxes,
                        label_map_b64=lu_label_map_b64,
                        original_path=lu_original)

    # ── Interpretation text ──────────────────────────────────────────
    interpretation = ""
    try:
        bc_data = data.get("biomedclip", {}).get("summary") if data.get("has_biomedclip") else None
        interpretation = generate_interpretation_text(
            clip_summary=bc_data,
            vllm_logprob=data.get("llavamed_unsam_logprob") if data.get("has_llavamed_unsam_logprob") else None,
            modality="Chest X-ray",
            body_part=category,
            caption=caption,
            cross_method_name="BiomedCLIP",
            vlm_method_name="LLaVA-Med",
            vlm_region_type="UnSAM segments",
        )
    except Exception:
        pass

    # If no precomputed results at all, show informative message
    if not any(data.get(k) for k in ("has_biomedclip", "has_llavamed_unsam_logprob",
                                      "has_llavamed_unsam_gen", "has_clip")):
        interpretation = (
            "**No precomputed attribution results yet.**\n\n"
            "Run the attribution pipeline on this MIMIC-CXR example to see results here. "
            "The image and report are shown above for reference."
        )

    # ── Build results state for comparison ───────────────────────────
    _results_state = {}
    if biomedclip_overlay_labeled:
        _results_state["BiomedCLIP Cross-Modal"] = {
            "overlay": biomedclip_overlay_labeled, "plot": biomedclip_region_plot}
    if llavamed_unsam_lp_overlay_img:
        _results_state["LLaVA-Med Log-Prob"] = {
            "overlay": llavamed_unsam_lp_overlay_img, "plot": llavamed_unsam_lp_plot}
    if llavamed_unsam_gen_overlay_img:
        _results_state["LLaVA-Med Generation"] = {
            "overlay": llavamed_unsam_gen_overlay_img, "plot": llavamed_unsam_gen_plot}

    return (
        caption,                        # 1
        original_img,                   # 2
        findings,                       # 3
        interpretation,                 # 4
        biomedclip_overlay_labeled,     # 5
        biomedclip_token_plot,          # 6
        biomedclip_region_plot,         # 7
        llavamed_unsam_lp_overlay_img,  # 8
        llavamed_unsam_lp_plot,         # 9
        llavamed_unsam_gen_overlay_img, # 10a
        llavamed_unsam_gen_plot,        # 10b
        biomedclip_interaction_html,    # 11
        {  # 12 β€” metadata
            "example_id": example_id,
            "category": category,
            "has_biomedclip": data.get("has_biomedclip", False),
            "has_llavamed_unsam_logprob": data.get("has_llavamed_unsam_logprob", False),
            "has_llavamed_unsam_gen": data.get("has_llavamed_unsam_gen", False),
        },
        _results_state,                 # 13
        gr.update(),                    # 14 (placeholder)
    )


def _on_mimic_compare_methods(method_a, method_b, results_state):
    """Pick two MIMIC methods from state and display side by side."""
    if not method_a or not method_b or not results_state:
        return None, None, None, None
    a = results_state.get(method_a, {})
    b = results_state.get(method_b, {})
    return a.get("overlay"), b.get("overlay"), a.get("plot"), b.get("plot")


# ── ISIC Dermoscopy Tab Handlers ──────────────────────────────────────────

_ISIC_METHOD_NAMES = [
    "BiomedCLIP Cross-Modal",
    "LLaVA-Med Log-Prob",
    "LLaVA-Med Generation",
]


def _on_select_isic_example(example_id, method_label: str = "Influence"):
    """Load an ISIC dermoscopy example and return data for the ISIC tab.

    Mirrors _on_select_mimic_example β€” same 14 outputs, same layout.
    ISIC has no separate "findings" field, so slot 3 (findings) is empty.
    """
    n_outputs = 14
    empty = tuple([""] + [None] * (n_outputs - 1))
    if not _ISIC_AVAILABLE or not example_id:
        return empty

    method = (method_label or "Influence").lower()
    method_display = "Influence" if method == "influence" else "Shapley"

    _base_chart = globals()["create_shapley_bar_chart"]
    _base_html = globals()["create_benchmark_interaction_html"]

    def create_shapley_bar_chart(labels, values, title="Shapley Values", **kwargs):  # noqa: F811
        kwargs.setdefault("method_label", method_display)
        return _base_chart(labels, values, title.replace("Shapley", method_display), **kwargs)

    def create_benchmark_interaction_html(**kwargs):  # noqa: F811
        kwargs.setdefault("method_label", method_display)
        return _base_html(**kwargs)

    try:
        data = load_isic_example(example_id, method=method)
    except Exception:
        return empty

    caption = data.get("caption", "")
    original_img = data.get("original_image_path")
    meta = data.get("meta", {})
    category = meta.get("category", "")

    # ── BiomedCLIP ───────────────────────────────────────────────────
    biomedclip_overlay_labeled = None
    biomedclip_region_plot = None
    biomedclip_token_plot = None
    biomedclip_interaction_html = ""

    if data.get("has_biomedclip"):
        bc_summary = data["biomedclip"]["summary"]
        bc_overlay_raw = data["biomedclip"]["image_paths"].get("overlay")
        bc_original = data["biomedclip"]["image_paths"].get("original", "")
        bc_segmap = data["biomedclip"]["image_paths"].get("segmap", "")
        bc_n_segs = len(bc_summary.get("image_region_values", []))

        bc_bboxes, bc_label_map_b64 = None, ""
        if bc_original and bc_segmap and bc_n_segs > 0:
            try:
                bc_bboxes, bc_label_map_b64 = extract_segment_regions(
                    bc_original, bc_segmap, bc_n_segs)
            except Exception:
                pass

        if bc_overlay_raw:
            biomedclip_overlay_labeled = draw_segment_labels(
                bc_overlay_raw, bc_summary.get("image_region_values", []),
                segment_bboxes=bc_bboxes,
                label_map_b64=bc_label_map_b64,
                original_path=bc_original)

        bc_r_labels = [v["label"] for v in bc_summary.get("image_region_values", [])]
        bc_r_values = [v["value"] for v in bc_summary.get("image_region_values", [])]
        if bc_r_labels:
            biomedclip_region_plot = create_shapley_bar_chart(
                bc_r_labels, bc_r_values, "BiomedCLIP β€” Image Region Shapley Values")

        bc_merged = merge_subword_token_values(bc_summary.get("token_values", []), caption)
        bc_t_labels = [v["label"] for v in bc_merged]
        bc_t_values = [v["value"] for v in bc_merged]
        if bc_t_labels:
            biomedclip_token_plot = create_shapley_bar_chart(
                bc_t_labels, bc_t_values, "BiomedCLIP β€” Caption Word Shapley Values")

        bc_image_b64 = data["biomedclip"].get("image_b64", {}).get("original", "")
        bc_overlay_b64 = data["biomedclip"].get("image_b64", {}).get("overlay", "")
        bc_all_cross = data["biomedclip"].get("all_cross_modal_pairs", [])
        bc_segmap_b64 = ""
        if bc_segmap:
            import os as _os
            if _os.path.exists(bc_segmap):
                import base64 as _b64
                with open(bc_segmap, "rb") as _f:
                    bc_segmap_b64 = _b64.b64encode(_f.read()).decode("ascii")
        biomedclip_interaction_html = create_benchmark_interaction_html(
            image_b64=bc_image_b64,
            clip_summary=bc_summary,
            vllm_logprob=None,
            caption=caption,
            all_cross_modal_pairs=bc_all_cross,
            segmap_b64=bc_segmap_b64,
            overlay_b64=bc_overlay_b64,
            segment_bboxes=bc_bboxes,
            label_map_b64=bc_label_map_b64,
            title="BiomedCLIP Cross-Modal Interaction View β€” click segments or words",
        )

    # ── LLaVA-Med UnSAM ─────────────────────────────────────────────
    llavamed_unsam_lp_overlay_img = None
    llavamed_unsam_gen_overlay_img = None
    llavamed_unsam_lp_plot = None
    llavamed_unsam_gen_plot = None

    if data.get("has_llavamed_unsam_logprob") or data.get("has_llavamed_unsam_gen"):
        lu_segmap = data.get("llavamed_unsam_segmap_path", "")
        lu_original = data.get("llavamed_unsam_original_path", "") or (original_img or "")
        lu_bboxes, lu_label_map_b64 = None, ""
        if lu_segmap and lu_original:
            n_lu_segs = 0
            if data.get("has_llavamed_unsam_logprob"):
                n_lu_segs = len(data["llavamed_unsam_logprob"].get("image_region_values", []))
            elif data.get("has_llavamed_unsam_gen"):
                n_lu_segs = len(data["llavamed_unsam_gen"].get("image_region_values", []))
            if n_lu_segs > 0:
                try:
                    lu_bboxes, lu_label_map_b64 = extract_segment_regions(
                        lu_original, lu_segmap, n_lu_segs)
                except Exception:
                    pass

        if data.get("has_llavamed_unsam_logprob"):
            lu_lp = rename_patch_labels(
                data["llavamed_unsam_logprob"].get("image_region_values", []))
            if lu_lp:
                llavamed_unsam_lp_plot = create_shapley_bar_chart(
                    [v["label"] for v in lu_lp],
                    [v["value"] for v in lu_lp],
                    "LLaVA-Med Log-Prob β€” Segment Shapley Values",
                )
                overlay_path = data["llavamed_unsam_logprob"].get("overlay_path", "")
                if overlay_path:
                    llavamed_unsam_lp_overlay_img = draw_segment_labels(
                        overlay_path, lu_lp,
                        segment_bboxes=lu_bboxes,
                        label_map_b64=lu_label_map_b64,
                        original_path=lu_original)

        if data.get("has_llavamed_unsam_gen"):
            lu_gen = rename_patch_labels(
                data["llavamed_unsam_gen"].get("image_region_values", []))
            if lu_gen:
                llavamed_unsam_gen_plot = create_shapley_bar_chart(
                    [v["label"] for v in lu_gen],
                    [v["value"] for v in lu_gen],
                    "LLaVA-Med Generation β€” Segment Shapley Values",
                )
                overlay_path = (data["llavamed_unsam_gen"].get("overlay_path", "")
                                or data.get("llavamed_unsam_logprob", {}).get("overlay_path", ""))
                if overlay_path:
                    llavamed_unsam_gen_overlay_img = draw_segment_labels(
                        overlay_path, lu_gen,
                        segment_bboxes=lu_bboxes,
                        label_map_b64=lu_label_map_b64,
                        original_path=lu_original)

    # ── Interpretation text ──────────────────────────────────────────
    interpretation = ""
    try:
        bc_data = data.get("biomedclip", {}).get("summary") if data.get("has_biomedclip") else None
        interpretation = generate_interpretation_text(
            clip_summary=bc_data,
            vllm_logprob=data.get("llavamed_unsam_logprob") if data.get("has_llavamed_unsam_logprob") else None,
            modality="Dermoscopy",
            body_part=category,
            caption=caption,
            cross_method_name="BiomedCLIP",
            vlm_method_name="LLaVA-Med",
            vlm_region_type="UnSAM segments",
        )
    except Exception:
        pass

    if not any(data.get(k) for k in ("has_biomedclip", "has_llavamed_unsam_logprob",
                                      "has_llavamed_unsam_gen", "has_clip")):
        interpretation = (
            "**No precomputed attribution results yet.**\n\n"
            "Run the attribution pipeline on this ISIC example to see results here. "
            "The image and caption are shown above for reference."
        )

    # ── Results state for comparison dropdowns ──────────────────────
    _results_state = {}
    if biomedclip_overlay_labeled:
        _results_state["BiomedCLIP Cross-Modal"] = {
            "overlay": biomedclip_overlay_labeled, "plot": biomedclip_region_plot}
    if llavamed_unsam_lp_overlay_img:
        _results_state["LLaVA-Med Log-Prob"] = {
            "overlay": llavamed_unsam_lp_overlay_img, "plot": llavamed_unsam_lp_plot}
    if llavamed_unsam_gen_overlay_img:
        _results_state["LLaVA-Med Generation"] = {
            "overlay": llavamed_unsam_gen_overlay_img, "plot": llavamed_unsam_gen_plot}

    return (
        caption,                        # 1
        original_img,                   # 2
        interpretation,                 # 3
        biomedclip_overlay_labeled,     # 4
        biomedclip_token_plot,          # 5
        biomedclip_region_plot,         # 6
        llavamed_unsam_lp_overlay_img,  # 7
        llavamed_unsam_lp_plot,         # 8
        llavamed_unsam_gen_overlay_img, # 9
        llavamed_unsam_gen_plot,        # 10
        biomedclip_interaction_html,    # 11
        {  # 12 β€” metadata
            "example_id": example_id,
            "category": category,
            "has_biomedclip": data.get("has_biomedclip", False),
            "has_llavamed_unsam_logprob": data.get("has_llavamed_unsam_logprob", False),
            "has_llavamed_unsam_gen": data.get("has_llavamed_unsam_gen", False),
        },
        _results_state,                 # 13
        gr.update(),                    # 14 (placeholder for compare dropdown)
    )


def _on_isic_compare_methods(method_a, method_b, results_state):
    """Pick two ISIC methods from state and display side by side."""
    if not method_a or not method_b or not results_state:
        return None, None, None, None
    a = results_state.get(method_a, {})
    b = results_state.get(method_b, {})
    return a.get("overlay"), b.get("overlay"), a.get("plot"), b.get("plot")


def _on_select_coco_example(example_id, method_label: str = "Influence"):
    """Load a precomputed MS-COCO example and return outputs for the COCO tab."""
    n_outputs = 12
    empty = ("",) + (None,) * (n_outputs - 2) + (gr.update(),)
    if not _COCO_AVAILABLE or not _MEDICAL_AVAILABLE or not example_id:
        return empty

    method = (method_label or "Influence").lower()
    method_display = "Influence" if method == "influence" else "Shapley"

    _base_chart = globals()["create_shapley_bar_chart"]
    _base_html = globals()["create_benchmark_interaction_html"]

    def create_shapley_bar_chart(labels, values, title="Shapley Values", **kwargs):  # noqa: F811
        kwargs.setdefault("method_label", method_display)
        return _base_chart(labels, values, title.replace("Shapley", method_display), **kwargs)

    def create_benchmark_interaction_html(**kwargs):  # noqa: F811
        kwargs.setdefault("method_label", method_display)
        return _base_html(**kwargs)

    try:
        data = load_coco_example(example_id, method=method)
    except Exception as exc:
        print(f"[coco] Error loading {example_id}: {exc}")
        return empty

    caption = data.get("caption", "")
    summary = data.get("summary", {})
    original_img = data.get("image_paths", {}).get("original")
    overlay_img = data.get("image_paths", {}).get("overlay")

    # Segment bboxes from segmap
    segment_bboxes, label_map_b64 = None, ""
    clip_original = data["image_paths"].get("original", "")
    clip_segmap = data["image_paths"].get("segmap", "")
    n_segs = len(summary.get("image_region_values", []))
    if clip_original and clip_segmap and n_segs > 0:
        try:
            segment_bboxes, label_map_b64 = extract_segment_regions(
                clip_original, clip_segmap, n_segs)
        except Exception:
            pass

    # Draw segment labels on overlay
    overlay_labeled = overlay_img
    if overlay_img:
        try:
            labeled = draw_segment_labels(
                overlay_img,
                summary.get("image_region_values", []),
                segment_bboxes=segment_bboxes,
            )
            if labeled:
                overlay_labeled = labeled
        except Exception:
            pass

    # Bar charts
    r_vals = summary.get("image_region_values", [])
    r_labels = [v["label"] for v in r_vals]
    r_values = [v["value"] for v in r_vals]
    region_plot = create_shapley_bar_chart(
        r_labels, r_values, "CLIP β€” Image Region Shapley Values") if r_labels else None

    t_vals = summary.get("token_values", [])
    merged_toks = merge_subword_token_values(t_vals, caption)
    t_labels = [v["label"] for v in merged_toks]
    t_values = [v["value"] for v in merged_toks]
    token_plot = create_shapley_bar_chart(
        t_labels, t_values, "CLIP β€” Caption Word Shapley Values") if t_labels else None

    # Cross-modal pairs + chart + table
    all_cross = data.get("all_cross_modal_pairs", [])
    cross_plot = None
    cross_table = []
    if all_cross:
        cross_pairs = [
            ((item["pair"][0], _tok_to_word(item["pair"][1], caption)), item["value"])
            for item in all_cross
        ]
        cross_plot = create_cross_modal_bar_chart(
            cross_pairs, "CLIP β€” Top Image x Word Interactions", top_k=20)
        cross_table = [
            [item["pair"][0], _tok_to_word(item["pair"][1], caption), f"{item['value']:+.4f}"]
            for item in all_cross[:30]
        ]

    # Heatmap
    heatmap = None
    influence_matrix = data.get("influence_matrix")
    tok_labels_hm = [t.replace("tok:", "").lstrip("#") for t in data.get("tok_labels", [])]
    if influence_matrix is not None and influence_matrix.size > 0:
        heatmap = create_influence_heatmap(
            data.get("seg_labels", r_labels), tok_labels_hm, influence_matrix,
            "Image Regions x Caption Words β€” Influence Scores")

    # Interactive cross-modal HTML
    image_b64 = data.get("image_b64", {}).get("original", "")
    overlay_b64 = data.get("image_b64", {}).get("overlay", "")
    segmap_b64 = data.get("image_b64", {}).get("segmap", "")

    interaction_html = ""
    try:
        interaction_html = create_benchmark_interaction_html(
            image_b64=image_b64,
            clip_summary=summary,
            vllm_logprob=None,
            caption=caption,
            all_cross_modal_pairs=all_cross,
            segmap_b64=segmap_b64,
            overlay_b64=overlay_b64,
            segment_bboxes=segment_bboxes,
            label_map_b64=label_map_b64,
            title="MS-COCO β€” Click a region or word to explore interactions",
        )
    except Exception as exc:
        interaction_html = f"<p>Error building interaction view: {exc}</p>"

    note = (
        "**Note:** These results used the original UNK mask token "
        "(same as `<|endoftext|>`, CLIP token ID 49407). "
        "A first-token dominance artifact may be visible in the token Shapley chart. "
        "This will be corrected when scaling to 100 images with the dot-mask fix."
    )

    # Masked Image Browser
    region_choices = data.get("region_choices", [])
    masked_dd_update = gr.update(
        choices=region_choices,
        value=region_choices[0] if region_choices else None,
    )
    # Pre-load the first masked image (all_masked) so the viewer isn't blank
    first_masked_img = None
    if region_choices:
        try:
            first_masked_img = get_coco_masked_image_path(example_id, region_choices[0])
        except Exception:
            pass

    return (
        caption,           # 1
        original_img,      # 2
        overlay_labeled,   # 3
        interaction_html,  # 4
        token_plot,        # 5
        region_plot,       # 6
        cross_plot,        # 7
        cross_table,       # 8
        heatmap,           # 9
        note,              # 10
        first_masked_img,  # 11 β€” masked image viewer
        masked_dd_update,  # 12 β€” masked dropdown choices
    )


def _on_select_coco_masked(example_id, choice):
    """Return a masked image path for the COCO Masked Image Browser."""
    if not _COCO_AVAILABLE or not example_id or not choice:
        return None
    return get_coco_masked_image_path(example_id, choice)


def on_click_image_compute(
    image,
    caption,
    clip_model,
    seg_mode,
    grid_size,
    method,
    seed,
    progress=gr.Progress(track_tqdm=True),
):
    return _compute_image_attributions_clip(
        image=image,
        caption=caption,
        clip_model=clip_model,
        seg_mode=seg_mode,
        grid_size=grid_size,
        method=method,
        seed=seed,
        progress=progress,
    )


def on_click_mm_compute(
    image,
    caption,
    clip_model,
    seg_mode,
    grid_size,
    method,
    seed,
    progress=gr.Progress(track_tqdm=True),
):
    return _compute_mm_attributions_clip(
        image=image,
        caption=caption,
        clip_model=clip_model,
        seg_mode=seg_mode,
        grid_size=grid_size,
        method=method,
        seed=seed,
        progress=progress,
    )


# ---------------------------------------------------------------------------
# Demo helpers (used to quickly validate visualization components locally)
# ---------------------------------------------------------------------------

_DEMO_TEXT = "The quick brown fox jumps over the lazy dog in a sunny meadow."
_DEMO_FEATURES = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", "in", "a", "sunny", "meadow"]
_DEMO_SPANS = [
    (0, 3), (4, 9), (10, 15), (16, 19), (20, 25), (26, 30), (31, 34),
    (35, 39), (40, 43), (44, 46), (47, 48), (49, 54), (55, 61)
]
_DEMO_ATTRIBUTIONS: Dict[str, Dict[str, float]] = {
    "shapley": {
        "The": -0.04,
        "quick": 0.18,
        "brown": 0.12,
        "fox": 0.27,
        "jumps": 0.15,
        "over": 0.05,
        "the": -0.02,
        "lazy": -0.11,
        "dog": -0.07,
        "in": 0.03,
        "a": 0.02,
        "sunny": 0.09,
        "meadow": 0.21,
    }
}
_DEMO_ATTRIBUTIONS["banzhaf"] = {
    token: round(value * 0.8, 3)
    for token, value in _DEMO_ATTRIBUTIONS["shapley"].items()
}
_DEMO_ATTRIBUTIONS["influence"] = {
    token: round(abs(value), 3)
    for token, value in _DEMO_ATTRIBUTIONS["shapley"].items()
}

_DEMO_INTERACTIONS_2: List[Tuple[Tuple[str, ...], float]] = [
    (("quick", "fox"), 0.24),
    (("fox", "jumps"), 0.19),
    (("sunny", "meadow"), 0.22),
    (("lazy", "dog"), -0.17),
    (("the", "lazy"), -0.12),
]

_DEMO_INTERACTIONS_3: List[Tuple[Tuple[str, ...], float]] = [
    (("quick", "brown", "fox"), 0.28),
    (("fox", "jumps", "over"), 0.18),
    (("sunny", "meadow", "dog"), 0.11),
    (("the", "lazy", "dog"), -0.21),
]

_DEMO_INTERACTION_MATRIX: List[Tuple[Tuple[int, int], float]] = [
    ((1, 3), 0.23),
    ((3, 4), 0.17),
    ((7, 8), -0.18),
    ((11, 12), 0.2),
    ((2, 5), 0.09),
]

_DEMO_DATASETS = {
    "squad_demo": [
        [
            "The quick brown fox jumps over the lazy dog.",
            "Who jumps over the dog?",
            "The quick brown fox",
        ],
        [
            "AttrLLM explains attributions for large language models.",
            "What does AttrLLM explain?",
            "Attributions",
        ],
    ],
    "truthfulqa_demo": [
        [
            "Water boils at 100 degrees Celsius at sea level.",
            "At what temperature does water boil?",
            "100 degrees Celsius",
        ]
    ],
}


def _render_demo(method: str = "shapley"):
    method = (method or "shapley").lower()
    order = 2
    attributions = _DEMO_ATTRIBUTIONS.get(method, _DEMO_ATTRIBUTIONS["shapley"])
    interactions = _DEMO_INTERACTIONS_3 if order == 3 else _DEMO_INTERACTIONS_2

    interactions_fig = plot_top_interactions(interactions, order=order, method=method)
    demo_pairwise = _DEMO_INTERACTIONS_2 or _fallback_pairwise_from_values(
        _DEMO_FEATURES,
        [attributions[token] for token in _DEMO_FEATURES],
    )
    text_html = create_interactive_text_heatmap(
        _DEMO_TEXT,
        _DEMO_SPANS,
        [attributions[token] for token in _DEMO_FEATURES],
        method=method,
    )
    text_interaction_html = create_text_interaction_html(
        _DEMO_FEATURES,
        [attributions[token] for token in _DEMO_FEATURES],
        [
            {"indices": [i, j], "value": float(val)}
            for (i, j), val in _DEMO_INTERACTION_MATRIX
        ],
        method=method,
        top_k=20,
        threshold=0.0,
    )

    meta = {
        "method": method,
        "order": order,
        "feature_count": len(_DEMO_FEATURES),
        "scalarizer": "logprob",
    }

    return update(
        figs={
            "interactions": interactions_fig,
        },
        meta=meta,
        html=text_html,
        interaction_text_html=text_interaction_html,
        scoring_target_source="model_output",
        scoring_target_text="",
        reference_answer="",
        unmasked_answer="",
        debug_scores=None,
        scalarizer_used="logprob",
        score_full=None,
        score_empty=None,
        y_len_tokens=None,
    )


def _render_additional_plots(method: str = "shapley"):
    return plot_interaction_matrix(_DEMO_FEATURES, _DEMO_INTERACTION_MATRIX)


def _records_for_dataset(dataset_name: str) -> List[Dict[str, Any]]:
    if get_examples is not None:
        try:
            records = get_examples(dataset_name, n=10)
            if records:
                return records
        except KeyError:
            pass
        except Exception:
            pass

    fallback_csv = _fallback_load_dataset(dataset_name, max_rows=10)
    if fallback_csv:
        return fallback_csv

    fallback = []
    for idx, row in enumerate(_DEMO_DATASETS.get(dataset_name, []), start=1):
        context, prompt, answer = row
        fallback.append(
            {
                "id": f"{dataset_name}_demo_{idx}",
                "context": context,
                "prompt": prompt,
                "correct_answer": answer,
            }
        )
    return fallback


def _available_datasets() -> List[str]:
    if list_datasets is not None:
        try:
            datasets = list_datasets()
            if datasets:
                return datasets
        except Exception:
            pass
    fallback = [k for k, v in _FALLBACK_DATASET_FILES.items() if (_fallback_datasets_dir() / v).exists()]
    if fallback:
        return sorted(fallback)
    return list(_DEMO_DATASETS.keys())


def _format_examples(records: List[Dict[str, Any]]) -> List[List[str]]:
    formatted = []
    for rec in records:
        formatted.append([
            rec.get("context", ""),
            rec.get("prompt", ""),
            rec.get("correct_answer")
            or rec.get("answer")
            or rec.get("target")
            or "",
        ])
    return formatted


def _load_examples_for_demo(dataset_name: str):
    # Convert display name to internal key if needed
    if get_dataset_key_from_display_name is not None:
        dataset_key = get_dataset_key_from_display_name(dataset_name)
    else:
        dataset_key = dataset_name
    
    records = _records_for_dataset(dataset_key)
    formatted = _format_examples(records)
    samples = formatted if formatted else _DEMO_DATASETS.get(dataset_key, [])
    return gr.update(samples=samples or [])


def _resolve_example_fields(record: Dict[str, Any]) -> Tuple[str, str, str]:
    context = record.get("context", "")
    prompt = record.get("prompt", "")
    answer = (
        record.get("correct_answer")
        or record.get("answer")
        or record.get("target")
        or ""
    )
    return context, prompt, answer


def _resolve_dataset_key(dataset_name: str) -> str:
    if dataset_name in _available_datasets():
        return dataset_name
    for key, label in DATASET_DISPLAY_LABELS.items():
        if dataset_name == label:
            return key
    if get_dataset_key_from_display_name is not None:
        return get_dataset_key_from_display_name(dataset_name)
    return dataset_name


def _dataset_choice_labels(dataset_keys: List[str]) -> List[str]:
    labels: List[str] = []
    for key in dataset_keys:
        if get_dataset_display_name is not None:
            try:
                labels.append(get_dataset_display_name(key))
                continue
            except Exception:
                pass
        labels.append(DATASET_DISPLAY_LABELS.get(key, key.replace("_", " ").title()))
    return labels


def _resolve_example_index(example_number: Any, records: List[Dict[str, Any]]) -> int:
    if not records:
        return 0
    try:
        index = int(example_number) - 1
    except Exception:
        index = 0
    return max(0, min(index, len(records) - 1))


def _resolve_example_id(example_number: Any, records: List[Dict[str, Any]]) -> str:
    if _public_only_mode():
        return f"example_{int(example_number or 1)}"
    index = _resolve_example_index(example_number, records)
    record = records[index] if records else {}
    return str(record.get("id") or f"example_{index + 1}")


def _build_model_answer_panel(dataset_name: str, example_number: Any) -> str:
    """Render Model's Answer + Justification HTML for the 30 wrong-answer
    examples; return empty string for everything else so the gr.HTML slot
    stays visually empty."""
    try:
        from visualization.wrong_answer_examples import WRONG_ANSWER_EXAMPLES
    except Exception:
        return ""
    dataset_key = _resolve_dataset_key(dataset_name) if dataset_name else ""
    try:
        ex_id = f"example_{int(example_number or 1)}"
    except Exception:
        ex_id = "example_1"
    if (dataset_key, ex_id) not in WRONG_ANSWER_EXAMPLES:
        return ""
    path = (
        _get_results_dir() / "model_answers" / "small" / dataset_key / f"{ex_id}.json"
    )
    if not path.exists():
        return ""
    try:
        with path.open("r", encoding="utf-8") as f:
            data = json.load(f)
    except Exception:
        return ""

    from html import escape as _escape

    letter = (data.get("model_answer_parsed") or "").strip()
    raw = (data.get("model_answer_raw") or "").strip()
    gt_letter = (data.get("ground_truth_letter") or data.get("ground_truth") or "").strip()
    is_match = bool(data.get("is_match"))
    similarity = data.get("similarity")
    try:
        sim_str = f"{float(similarity):.3f}" if similarity is not None else "β€”"
    except Exception:
        sim_str = "β€”"

    if is_match:
        chip_bg, chip_fg, chip_text = "#e7f6ec", "#1f8d4a", "βœ“ MATCH"
    else:
        chip_bg, chip_fg, chip_text = "#fdecea", "#c0392b", "βœ— MISMATCH"

    # Split off the leading letter+rationale prefix for cleaner reading.
    justification = raw
    if raw.lower().startswith("justification:"):
        justification = raw.split(":", 1)[1].strip()
    elif "Justification:" in raw:
        justification = raw.split("Justification:", 1)[1].strip()

    return (
        '<div style="display:flex;flex-direction:column;gap:8px;'
        'background:#fdf7ff;border:1px solid #e2d6f3;border-radius:10px;'
        'padding:12px 14px;margin-top:6px;">'
        '<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">'
        '<strong style="color:#4a1c87;">Model\'s Answer</strong>'
        f'<span style="background:#fff;border:1px solid #d8c6f0;border-radius:6px;'
        f'padding:2px 8px;font-weight:600;color:#4a1c87;">{_escape(letter or "β€”")}</span>'
        f'<span style="color:#6f5a72;font-size:12px;">vs Ground Truth: '
        f'<strong>{_escape(gt_letter or "β€”")}</strong></span>'
        f'<span style="background:{chip_bg};color:{chip_fg};border-radius:999px;'
        f'padding:2px 10px;font-size:12px;font-weight:600;">{chip_text}</span>'
        f'<span style="color:#6f5a72;font-size:12px;">sim={sim_str}</span>'
        '</div>'
        '<div style="font-size:13px;color:#3a2b4a;line-height:1.55;'
        'background:#fff;border:1px solid #ece4f8;border-radius:8px;padding:10px 12px;">'
        f'<strong style="display:block;margin-bottom:4px;color:#4a1c87;">Justification</strong>'
        f'{_escape(justification) if justification else "<em>No justification captured.</em>"}'
        '</div>'
        '</div>'
    )


def _load_examples_for_slider(dataset_name: str):
    dataset_key = _resolve_dataset_key(dataset_name)
    records = _records_for_dataset(dataset_key)
    slider_max = max(1, min(10, len(records) or 10))
    context = prompt = answer = ""
    if records:
        context, prompt, answer = _resolve_example_fields(records[0])
    slider_update = gr.update(minimum=1, maximum=slider_max, step=1, value=1)
    return slider_update, records, context, prompt, answer


def _update_example_preview(example_number: Any, records):
    if not records:
        return "", "", ""
    index = _resolve_example_index(example_number, records)
    return _resolve_example_fields(records[index])


def _results_output_list(results: Dict[str, Any]) -> List[Any]:
    return [
        results["interactions"],
        results["interactions_tokens_html"],
        results["interactions_text_html"],
        results["text_html"],
        results["meta"],
        results["scoring_target_source"],
        results["scoring_target_text"],
        results["reference_answer"],
        results["unmasked_answer"],
        results["debug_scores"],
        results["scalarizer_used"],
        results["score_full"],
        results["score_empty"],
        results["y_len_tokens"],
    ]


def build_demo_app() -> gr.Blocks:
    datasets = _available_datasets()
    default_dataset = datasets[0] if datasets else "demo"

    # Apply the same colorful CSS theme
    custom_css = """
    .gradio-container {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif !important;
        background: linear-gradient(135deg, #fef5f0 0%, #f0e8ff 50%, #e8f5ff 100%) !important;
        padding: 24px !important;
    }
    
    .gradio-container h1, .gradio-container h2 {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 30%, #c44569 60%, #6c5ce7 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        font-weight: 900;
        font-size: 42px !important;
        margin: 20px 0 16px 0;
        letter-spacing: -0.03em;
    }
    
    label, .gr-label {
        font-weight: 700 !important;
        font-size: 16px !important;
        color: #2d1f4a !important;
    }
    
    .gr-button {
        border-radius: 16px !important;
        font-weight: 700 !important;
        font-size: 17px !important;
        padding: 16px 32px !important;
        background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%) !important;
        color: white !important;
        border: none !important;
    }
    
    .gr-box, .gr-input, .gr-dropdown, .gr-textbox {
        border-radius: 14px !important;
        border: 3px solid #e8dff5 !important;
        font-size: 17px !important;
    }
    
    .gr-markdown p {
        font-size: 17px !important;
        font-weight: 500 !important;
    }
    """

    _demo_kwargs = {"title": "AttrLLM Visualization Demo"}
    if _supports_kwarg(gr.Blocks, "css"):
        _demo_kwargs["css"] = custom_css
    with gr.Blocks(**_demo_kwargs) as demo:
        gr.Markdown(
            "# 🎨 AttrLLM Visualization Demo\n\n"
            "**Preview the attribution widgets** before wiring real backends. "
            "Use the controls below to explore the interface."
        )

        with gr.Row():
            with gr.Column(scale=1):
                # Prepare initial choices and value before creating component
                initial_choices = _dataset_choice_labels(datasets)
                initial_value = initial_choices[0] if initial_choices else None
                
                dataset_selector = gr.Dropdown(
                    choices=initial_choices,
                    value=initial_value,
                    label="Dataset",
                    interactive=True,
                    allow_custom_value=False,
                    elem_id="dataset-selector-demo",
                    elem_classes=["bubble-select"],
                )
                example_browser = create_example_browser()
                with gr.Column(scale=1):
                    model_selector = create_model_selector()
                    scalarizer_selector = gr.Dropdown(
                        choices=SCALARIZER_CHOICES,
                        value="logprob",
                        label="Scalarizer",
                        interactive=True,
                    )
                    embedding_model_box = gr.Textbox(
                        label="Embedding Model (for scalarizer=embedding)",
                        value="Qwen/Qwen3-Embedding-0.6B",
                        lines=1,
                    )
                    feature_level_selector = create_feature_level_selector()
                    method_toggle = create_attribution_method_toggle()

        dataset_selector.change(
            fn=_load_examples_for_demo,
            inputs=dataset_selector,
            outputs=example_browser,
        )
        demo.load(
            fn=_load_examples_for_demo,
            inputs=[dataset_selector],
            outputs=[example_browser],
        )

        render_button = gr.Button("Render Demo Visuals", variant="primary")

        outputs = create_results_display()
        extra_matrix = gr.Plot(label="Interaction Matrix (demo)")

        render_button.click(
            fn=_render_demo,
            inputs=[method_toggle],
            outputs=_results_output_list(outputs),
        )

        render_button.click(
            fn=_render_additional_plots,
            inputs=[method_toggle],
            outputs=[extra_matrix],
        )

    return demo


def _patch_gradio_schema_generation() -> None:
    """Prevent Gradio 5.x /info crash caused by additionalProperties: true in schemas."""
    try:
        from gradio_client import utils as client_utils
    except Exception:
        return
    if getattr(client_utils, "_attrllm_schema_patch", False):
        return
    original_inner = getattr(client_utils, "_json_schema_to_python_type", None)
    original_outer = getattr(client_utils, "json_schema_to_python_type", None)
    if not callable(original_inner) or not callable(original_outer):
        return

    def _normalize_schema(schema):
        if isinstance(schema, bool):
            return {} if schema else {"type": "null"}
        if isinstance(schema, list):
            return [_normalize_schema(item) for item in schema]
        if not isinstance(schema, dict):
            return schema
        normalized = dict(schema)
        if isinstance(normalized.get("additionalProperties"), bool):
            normalized["additionalProperties"] = _normalize_schema(normalized["additionalProperties"])
        for key in ("properties", "$defs", "definitions", "patternProperties"):
            value = normalized.get(key)
            if isinstance(value, dict):
                normalized[key] = {k: _normalize_schema(v) for k, v in value.items()}
        for key in ("items", "contains", "not", "if", "then", "else"):
            if key in normalized:
                normalized[key] = _normalize_schema(normalized[key])
        for key in ("anyOf", "allOf", "oneOf", "prefixItems"):
            value = normalized.get(key)
            if isinstance(value, list):
                normalized[key] = [_normalize_schema(item) for item in value]
        return normalized

    client_utils._json_schema_to_python_type = lambda s, d=None: original_inner(_normalize_schema(s), d)
    client_utils.json_schema_to_python_type = lambda s: original_outer(_normalize_schema(s))
    client_utils._attrllm_schema_patch = True


_patch_gradio_schema_generation()


def build_app() -> gr.Blocks:
    datasets = _available_datasets()
    default_dataset = datasets[0] if datasets else ""
    public_only = _public_only_mode()
    mm_only = _mm_only_mode()

    # Custom CSS for prettier UI - Inspired by modern, colorful design
    custom_css = """
    /* Main container styling - Warm gradient background */
    .gradio-container {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif !important;
        background: linear-gradient(135deg, #fef5f0 0%, #f0e8ff 50%, #e8f5ff 100%) !important;
        padding: 24px !important;
    }
    
    /* Header styling - Large, bold, colorful */
    .gradio-container h1 {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 30%, #c44569 60%, #6c5ce7 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        font-weight: 900;
        font-size: 48px !important;
        margin: 20px 0 16px 0;
        letter-spacing: -0.03em;
        text-align: left;
    }
    
    .gradio-container h2 {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 30%, #c44569 60%, #6c5ce7 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        font-weight: 900;
        font-size: 42px !important;
        margin: 20px 0 16px 0;
        letter-spacing: -0.03em;
    }
    
    .gradio-container h3 {
        color: #2d1f4a;
        font-weight: 800;
        font-size: 24px !important;
        margin: 24px 0 16px 0;
    }
    
    /* Tab styling - Bold and colorful */
    .tab-nav {
        border: none !important;
        background: transparent !important;
        gap: 8px !important;
        padding: 8px 0 !important;
    }
    
    .tab-nav button {
        font-size: 18px !important;
        font-weight: 700 !important;
        padding: 16px 32px !important;
        border-radius: 16px !important;
        transition: all 0.3s ease !important;
        border: 3px solid #e0d0f0 !important;
        background: white !important;
        color: #6c5ce7 !important;
        margin-right: 8px !important;
    }
    
    .tab-nav button:hover {
        background: #f8f4ff !important;
        border-color: #b8a8db !important;
        transform: translateY(-2px) !important;
    }
    
    .tab-nav button.selected {
        background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%) !important;
        color: white !important;
        border: 3px solid #6c5ce7 !important;
        box-shadow: 0 6px 20px rgba(108, 92, 231, 0.3) !important;
    }
    
    /* Button styling - Vibrant and interactive */
    .gr-button {
        border-radius: 16px !important;
        font-weight: 700 !important;
        font-size: 17px !important;
        padding: 16px 32px !important;
        transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) !important;
        box-shadow: 0 6px 20px rgba(108, 92, 231, 0.2) !important;
        border: none !important;
    }
    
    .gr-button-primary {
        background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%) !important;
        color: white !important;
    }
    
    .gr-button-secondary {
        background: linear-gradient(135deg, #fd79a8 0%, #ff7675 100%) !important;
        color: white !important;
    }
    
    .gr-button:hover {
        transform: translateY(-3px) scale(1.02) !important;
        box-shadow: 0 10px 30px rgba(108, 92, 231, 0.35) !important;
    }
    
    .gr-button-primary:hover {
        background: linear-gradient(135deg, #5e4ec7 0%, #9089e8 100%) !important;
    }
    
    /* Input/Dropdown styling - Clear and modern */
    .gr-box, .gr-input, .gr-dropdown {
        border-radius: 14px !important;
        border: 3px solid #e8dff5 !important;
        background: white !important;
        font-size: 17px !important;
        padding: 12px 16px !important;
        transition: all 0.3s ease !important;
        font-weight: 500 !important;
    }
    
    .gr-box:focus, .gr-input:focus, .gr-dropdown:focus {
        border-color: #6c5ce7 !important;
        box-shadow: 0 0 0 4px rgba(108, 92, 231, 0.15) !important;
        transform: translateY(-1px) !important;
    }
    
    /* Textbox styling - Larger text */
    .gr-textbox {
        border-radius: 16px !important;
        border: 3px solid #e8dff5 !important;
        font-size: 17px !important;
        line-height: 1.6 !important;
    }
    
    .gr-textbox textarea {
        font-size: 17px !important;
        line-height: 1.6 !important;
        padding: 14px !important;
    }
    
    .gr-textbox:focus-within {
        border-color: #6c5ce7 !important;
        box-shadow: 0 6px 24px rgba(108, 92, 231, 0.2) !important;
    }
    
    /* Radio button styling - Colorful pills */
    .gr-radio {
        gap: 12px !important;
    }
    
    .gr-radio label {
        font-size: 17px !important;
        font-weight: 600 !important;
        padding: 14px 28px !important;
        border-radius: 14px !important;
        border: 3px solid #e8dff5 !important;
        transition: all 0.3s ease !important;
        background: white !important;
        cursor: pointer !important;
    }
    
    .gr-radio label:hover {
        border-color: #b8a8db !important;
        background: #faf8ff !important;
        transform: translateY(-2px) !important;
        box-shadow: 0 4px 12px rgba(108, 92, 231, 0.15) !important;
    }
    
    .gr-radio input:checked + label {
        background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%) !important;
        color: white !important;
        border-color: #6c5ce7 !important;
        font-weight: 800 !important;
        box-shadow: 0 6px 20px rgba(108, 92, 231, 0.3) !important;
    }
    
    /* Panel/Accordion styling - Clean cards */
    .gr-panel {
        border-radius: 20px !important;
        border: 3px solid #e8dff5 !important;
        padding: 24px !important;
        background: white !important;
        box-shadow: 0 6px 24px rgba(108, 92, 231, 0.1) !important;
        margin: 16px 0 !important;
    }
    
    .gr-accordion {
        border-radius: 18px !important;
        border: 3px solid #e8dff5 !important;
        background: white !important;
    }
    
    /* Label styling - Bold and readable */
    label, .gr-label {
        font-weight: 700 !important;
        font-size: 16px !important;
        color: #2d1f4a !important;
        margin-bottom: 10px !important;
        letter-spacing: -0.01em !important;
    }
    
    /* Dropdown options */
    .gr-dropdown-menu {
        border-radius: 14px !important;
        border: 3px solid #e8dff5 !important;
        box-shadow: 0 8px 32px rgba(108, 92, 231, 0.15) !important;
        font-size: 17px !important;
    }
    
    .gr-dropdown-menu .item {
        font-size: 17px !important;
        padding: 12px 16px !important;
        font-weight: 500 !important;
    }
    
    .gr-dropdown-menu .item:hover {
        background: linear-gradient(135deg, #f3f0ff 0%, #e8f5ff 100%) !important;
    }
    
    /* Plot container - Prominent */
    .gr-plot {
        border-radius: 20px !important;
        border: 3px solid #e8dff5 !important;
        overflow: hidden !important;
        box-shadow: 0 8px 30px rgba(108, 92, 231, 0.12) !important;
        background: white !important;
        width: 100% !important;
    }

    /* Force the inner Plotly canvas + svg to fill its container so the Bar
       View doesn't render in a half-width column when the Text Interaction
       view above it is wide. */
    .gr-plot .js-plotly-plot,
    .gr-plot .plot-container,
    .gr-plot .svg-container,
    .gr-plot .main-svg {
        width: 100% !important;
        max-width: 100% !important;
    }
    .interaction-stack > .gradio-plot,
    .interaction-stack > .block.gradio-plot,
    .interaction-stack .gr-plot {
        width: 100% !important;
        max-width: 100% !important;
        flex: 1 1 100% !important;
    }
    
    /* JSON viewer */
    .gr-json {
        border-radius: 16px !important;
        border: 3px solid #e8dff5 !important;
        background: #faf8ff !important;
        padding: 20px !important;
        font-family: 'Monaco', 'Menlo', 'Consolas', monospace !important;
        font-size: 15px !important;
    }
    
    /* Column styling */
    .gr-column {
        padding: 20px !important;
    }
    
    /* Row styling */
    .gr-row {
        gap: 24px !important;
        margin: 12px 0 !important;
    }
    
    /* Markdown content - Larger, more readable */
    .gr-markdown {
        line-height: 1.8 !important;
        color: #2d1f4a !important;
    }
    
    .gr-markdown p {
        font-size: 17px !important;
        margin: 12px 0 !important;
        font-weight: 500 !important;
    }
    
    .gr-markdown strong {
        font-weight: 800 !important;
        color: #6c5ce7 !important;
    }
    
    /* Status/info messages - Colorful notifications */
    .gr-info {
        border-radius: 16px !important;
        border-left: 5px solid #6c5ce7 !important;
        background: linear-gradient(135deg, #f8f6ff 0%, #f0f4ff 100%) !important;
        padding: 18px 24px !important;
        font-size: 16px !important;
        font-weight: 600 !important;
        color: #2d1f4a !important;
        box-shadow: 0 4px 16px rgba(108, 92, 231, 0.1) !important;
    }
    
    /* Error messages */
    .gr-error {
        border-radius: 16px !important;
        border-left: 5px solid #ff6b6b !important;
        background: linear-gradient(135deg, #fff5f5 0%, #ffe8e8 100%) !important;
        padding: 18px 24px !important;
        font-size: 16px !important;
        font-weight: 600 !important;
        color: #c44569 !important;
    }
    
    /* Loading spinner */
    .loading {
        border: 4px solid #f3f0ff !important;
        border-top: 4px solid #6c5ce7 !important;
    }
    
    /* Scrollbar styling */
    ::-webkit-scrollbar {
        width: 12px !important;
        height: 12px !important;
    }
    
    ::-webkit-scrollbar-track {
        background: #f8f6ff !important;
        border-radius: 10px !important;
    }
    
    ::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%) !important;
        border-radius: 10px !important;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(135deg, #5e4ec7 0%, #9089e8 100%) !important;
    }

    .results-shell {
        margin-top: 16px !important;
        background: transparent !important;
        border: none !important;
        border-radius: 0 !important;
        padding: 0 !important;
        box-shadow: none !important;
    }

    .results-shell,
    .results-shell > div,
    .results-shell .gr-group,
    .results-shell .gr-box,
    .results-shell .gr-panel,
    .results-shell .block {
        background: transparent !important;
        border: none !important;
        box-shadow: none !important;
    }

    .interaction-stack {
        gap: 20px !important;
        padding: 0 8px 6px !important;
    }

    .interaction-stack h3 {
        margin-left: 24px !important;
        margin-bottom: 12px !important;
    }

    .public-controls {
        align-items: stretch !important;
        gap: 20px !important;
        margin-top: 8px !important;
    }

    .control-card {
        background: linear-gradient(180deg, rgba(255, 255, 255, 0.82) 0%, rgba(250, 246, 255, 0.96) 100%) !important;
        border: 2px solid rgba(224, 208, 240, 0.78) !important;
        border-radius: 26px !important;
        padding: 18px 20px 14px !important;
        box-shadow: 0 14px 30px rgba(108, 92, 231, 0.07) !important;
    }

    .control-card-primary {
        background: linear-gradient(180deg, rgba(255, 255, 255, 0.86) 0%, rgba(244, 248, 255, 0.96) 100%) !important;
    }

    .control-card-secondary {
        background: linear-gradient(180deg, rgba(255, 255, 255, 0.86) 0%, rgba(250, 244, 255, 0.96) 100%) !important;
    }

    .control-card .gradio-container,
    .control-card .gr-group {
        background: transparent !important;
    }

    .control-card > div,
    .control-card .block,
    .control-card .wrap,
    .control-card .gr-form,
    .control-card .form {
        background: transparent !important;
        border: none !important;
        box-shadow: none !important;
    }

    .control-card .gr-box,
    .control-card .gr-panel {
        background: transparent !important;
        box-shadow: none !important;
    }

    .bubble-select {
        border: 3px solid #8f5cff !important;
        border-radius: 18px !important;
        box-shadow: 0 8px 20px rgba(143, 92, 255, 0.10) !important;
        transition: box-shadow 0.2s ease, border-color 0.2s ease !important;
    }

    .bubble-select:focus-within {
        border-color: #7a3dff !important;
        box-shadow: 0 0 0 4px rgba(143, 92, 255, 0.14), 0 10px 24px rgba(143, 92, 255, 0.16) !important;
    }

    .example-id-slider {
        margin-top: 8px !important;
        padding: 10px 2px 2px !important;
    }

    .example-id-slider input[type="range"] {
        accent-color: #4f7cff !important;
    }

    .example-id-slider .number-input,
    .example-id-slider input[type="number"] {
        border-radius: 16px !important;
        border: 2px solid #d8dcee !important;
        background: linear-gradient(180deg, #ffffff 0%, #f7f9ff 100%) !important;
        font-weight: 700 !important;
        min-width: 72px !important;
    }

    .example-id-slider .wrap {
        gap: 14px !important;
    }

    @media (prefers-color-scheme: dark) {
        .gradio-container {
            background: radial-gradient(circle at top, #1e2a44 0%, #0d1422 52%, #090f19 100%) !important;
        }

        .gradio-container h3,
        label, .gr-label,
        .gr-markdown,
        .gr-markdown p {
            color: #e8eefc !important;
        }

        .gr-markdown strong {
            color: #cbd7ff !important;
        }

        .tab-nav button,
        .gr-box, .gr-input, .gr-dropdown, .gr-textbox,
        .gr-panel, .gr-accordion,
        .gr-plot, .gr-json {
            background: rgba(16, 24, 39, 0.88) !important;
            border-color: rgba(148, 163, 184, 0.24) !important;
            color: #e8eefc !important;
        }

        .tab-nav button {
            color: #d7e1ff !important;
        }

        .tab-nav button:hover {
            background: rgba(37, 52, 79, 0.96) !important;
            border-color: rgba(199, 210, 254, 0.36) !important;
        }

        .gr-radio label {
            background: rgba(16, 24, 39, 0.9) !important;
            border-color: rgba(148, 163, 184, 0.26) !important;
            color: #e8eefc !important;
        }

        .gr-radio label:hover {
            background: rgba(37, 52, 79, 0.96) !important;
        }

        .gr-textbox textarea,
        .gr-input input {
            background: transparent !important;
            color: #e8eefc !important;
        }

        .gr-dropdown-menu {
            background: #101827 !important;
            border-color: rgba(148, 163, 184, 0.24) !important;
        }

        .gr-dropdown-menu .item {
            color: #e8eefc !important;
        }

        .gr-dropdown-menu .item:hover {
            background: rgba(37, 52, 79, 0.96) !important;
        }

        .gr-plot .main-svg,
        .gr-plot .svg-container,
        .gr-plot .plot-container,
        .gr-plot .user-select-none {
            background: transparent !important;
        }

        .gr-plot .xtick text,
        .gr-plot .ytick text,
        .gr-plot .gtitle text,
        .gr-plot .xtitle text,
        .gr-plot .ytitle text,
        .gr-plot .annotation-text,
        .gr-plot .legend text {
            fill: #e8eefc !important;
            color: #e8eefc !important;
        }

        .gr-plot .gridlayer path,
        .gr-plot .zerolinelayer path,
        .gr-plot .xlines-above path,
        .gr-plot .ylines-above path {
            stroke: rgba(148, 163, 184, 0.22) !important;
        }

        .gr-info {
            background: linear-gradient(135deg, rgba(30, 41, 59, 0.95) 0%, rgba(17, 24, 39, 0.95) 100%) !important;
            color: #dbe7ff !important;
            border-left-color: #9db4ff !important;
        }

        .control-card {
            background: linear-gradient(180deg, rgba(16, 24, 39, 0.9) 0%, rgba(18, 28, 45, 0.96) 100%) !important;
            border-color: rgba(148, 163, 184, 0.2) !important;
            box-shadow: 0 18px 36px rgba(0, 0, 0, 0.24) !important;
        }

        .results-shell,
        .results-shell > div,
        .results-shell .gr-group,
        .results-shell .gr-box,
        .results-shell .gr-panel,
        .results-shell .block {
            background: transparent !important;
            border: none !important;
            box-shadow: none !important;
        }

        .bubble-select {
            border-color: #a06cff !important;
            box-shadow: 0 10px 24px rgba(143, 92, 255, 0.18) !important;
        }

        .bubble-select:focus-within {
            border-color: #c29cff !important;
            box-shadow: 0 0 0 4px rgba(143, 92, 255, 0.16), 0 12px 26px rgba(143, 92, 255, 0.22) !important;
        }

        .example-id-slider .number-input,
        .example-id-slider input[type="number"] {
            background: linear-gradient(180deg, #162031 0%, #111827 100%) !important;
            border-color: rgba(148, 163, 184, 0.24) !important;
            color: #e8eefc !important;
        }

        .gr-error {
            background: linear-gradient(135deg, rgba(68, 18, 32, 0.95) 0%, rgba(39, 12, 20, 0.95) 100%) !important;
            color: #ffd5dc !important;
        }

        ::-webkit-scrollbar-track {
            background: #111827 !important;
        }
    }
    """

    _app_kwargs = {"title": "LLM Reasoning Explorer Studio"}
    if _supports_kwarg(gr.Blocks, "css"):
        _app_kwargs["css"] = custom_css
    with gr.Blocks(**_app_kwargs) as app:
        gr.Markdown(
            "# LLM Reasoning Explorer Studio\n\n"
            "**Explore attribution results and feature interactions** with our interactive visualization tools. "
            "Browse pre-computed examples or analyze your own text in real-time with powerful AI insights."
        )
        gr.Markdown(f"**Build:** {BUILD_ID} ({BUILD_TS})")

        example_state = gr.State([])

        with (gr.Column(visible=not mm_only) if (public_only or mm_only) else gr.Tab("Public Mode")):
            with gr.Accordion("How to Use", open=False):
                gr.Markdown(
                    "1. **Select a dataset** from 10 available datasets (100 total examples, 10 per dataset)\n"
                    "2. **Choose a model** to compare: Qwen3-4B, Qwen3-30B, or Mistral-7B\n"
                    "3. **Pick a scoring method:** Perplexity or Semantic Similarity\n"
                    "4. **Set the feature level:** Word, Sentence, or Paragraph\n"
                    "5. **Choose an attribution method:** Shapley, Banzhaf, or Influence\n"
                    "6. **View results** in the Text Interaction View (inline highlights) and Bar View (ranked interactions)"
                )
            with gr.Row(elem_classes=["public-controls"]):
                with gr.Column(scale=1, elem_classes=["control-card", "control-card-primary"]):
                    # Prepare initial choices and value before creating component
                    initial_choices = _dataset_choice_labels(datasets)
                    # In mm_only mode the text attribution tab is hidden β€” no default value
                    # prevents the .change() callback from firing on page load.
                    _preferred_default = "BBQ Disambiguation"
                    if mm_only:
                        initial_value = None
                    elif _preferred_default in initial_choices:
                        initial_value = _preferred_default
                    else:
                        initial_value = initial_choices[0] if initial_choices else None

                    dataset_selector = gr.Dropdown(
                        choices=initial_choices,
                        value=initial_value,
                        label="Dataset",
                        interactive=True,
                        allow_custom_value=False,
                        elem_id="dataset-selector",
                        elem_classes=["bubble-select"],
                    )

                    example_selector = gr.Slider(
                        label="Example ID",
                        minimum=1,
                        maximum=10,
                        step=1,
                        value=1,
                        interactive=True,
                        elem_classes=["example-id-slider"],
                    )
                with gr.Column(scale=1, elem_classes=["control-card", "control-card-secondary"]):
                    model_selector = create_model_selector()
                    scalarizer_selector = gr.Dropdown(
                        choices=PUBLIC_SCALARIZER_CHOICES,
                        value="geomean_jointprob",
                        label="Scalarizer",
                        interactive=True,
                        elem_classes=["bubble-select"],
                    )
                    public_feature_level_selector = create_feature_level_selector(value="word")
                    method_toggle = create_attribution_method_toggle()

            with gr.Accordion("Example Preview", open=True):
                with gr.Row():
                    with gr.Column(scale=3):
                        context_box = gr.Textbox(
                            label="Context",
                            lines=8,
                            interactive=False,
                        )
                    with gr.Column(scale=2):
                        prompt_box = gr.Textbox(
                            label="Prompt",
                            lines=4,
                            interactive=False,
                        )
                        answer_box = gr.Textbox(
                            label="Ground Truth Answer",
                            lines=3,
                            interactive=False,
                        )
                # Empty for examples outside the 30-pair allow-list; renders
                # the model's parsed letter + justification for the others.
                try:
                    model_answer_html = gr.HTML(value="", sanitize_html=False)
                except TypeError:
                    model_answer_html = gr.HTML(value="")

            public_results = create_results_display()

            def _public_mode_compute(
                dataset,
                example_number,
                records,
                model_size,
                scalarizer,
                feature_level,
                method,
                progress=gr.Progress(track_tqdm=True),
            ):
                if mm_only:
                    return tuple([None] * 14)
                if not dataset:
                    raise gr.Error("Please select a dataset.")
                if not example_number:
                    raise gr.Error("Please select an example.")

                dataset_key = _resolve_dataset_key(dataset)
                ex_id = _resolve_example_id(example_number, records)

                method = _normalize_method(method)
                level = _normalize_level(feature_level)
                model_size = _normalize_model_size(model_size)

                # Prefer precomputed results: use loader if available, else load from file (Space-friendly).
                get_res = get_result_by_id if get_result_by_id is not None else _public_get_result_from_file
                result = get_res(
                    model_size,
                    dataset_key,
                    ex_id,
                    scalarizer=scalarizer,
                    feature_level=level,
                ) or {}
                payload = result.get(method, {})

                if not payload:
                    alt_size = _find_available_model_size(dataset_key, ex_id, scalarizer, level)
                    if alt_size and alt_size != model_size:
                        result = get_res(
                            alt_size,
                            dataset_key,
                            ex_id,
                            scalarizer=scalarizer,
                            feature_level=level,
                        ) or {}
                        payload = result.get(method, {})
                        if payload:
                            model_size = alt_size

                # If still no payload, try any available (model_size, scalarizer, level) for this example
                if not payload:
                    alt_size, alt_scalarizer, alt_level, result = _find_any_available_result(
                        dataset_key, ex_id, get_res, method
                    )
                    if alt_size and alt_scalarizer and alt_level and result:
                        payload = result.get(method, {})
                        model_size, scalarizer, level = alt_size, alt_scalarizer, alt_level

                if payload and (payload.get("features") or payload.get("heatmap")):
                    _, _, _, *outputs = on_select_example(
                        dataset_key,
                        ex_id,
                        model_size,
                        2,
                        method,
                        scalarizer=scalarizer,
                        feature_level=level,
                    )
                    return outputs

                # Public-only mode: do not attempt live compute
                if _public_only_mode() or get_example_by_id is None:
                    expected_ref = _reference_results_file(model_size, dataset_key, ex_id, scalarizer, level)
                    raise gr.Error(
                        "No precomputed results found.\n\n"
                        f"Expected (reference_answer):\n{expected_ref}\n\n"
                        "On Hugging Face Space: make sure the 'results' folder is in your repo "
                        "(commit & push it). If you use Git LFS, enable 'LFS' in Space Settings β†’ "
                        "Repository and ensure files are pulled. You can also try another "
                        "scalarizer (e.g. Perplexity) or feature level (e.g. word)."
                    )

                # Fallback to live compute if no precomputed payload or non-word level
                get_ex = _ensure_backend("loader.data.get_example_by_id", get_example_by_id)
                record = get_ex(dataset_key, ex_id)
                context = record.get("context", "")
                prompt = record.get("prompt", "")
                answer = _extract_answer(record)

                return _compute_live_attributions(
                    context=context,
                    prompt=prompt,
                    correct_answer=answer,
                    model_size=model_size,
                    scalarizer=scalarizer,
                    embedding_model=None,
                    level=level,
                    method=method,
                    order=2,
                    progress=progress,
                )

            public_preview_outputs = [context_box, prompt_box, answer_box]
            public_compute_inputs = [
                dataset_selector,
                example_selector,
                example_state,
                model_selector,
                scalarizer_selector,
                public_feature_level_selector,
                method_toggle,
            ]
            public_compute_outputs = _results_output_list(public_results)

            dataset_change_event = dataset_selector.change(
                fn=_load_examples_for_slider,
                inputs=[dataset_selector],
                outputs=[
                    example_selector,
                    example_state,
                    context_box,
                    prompt_box,
                    answer_box,
                ],
                queue=False,
            ).then(
                fn=_build_model_answer_panel,
                inputs=[dataset_selector, example_selector],
                outputs=[model_answer_html],
                queue=False,
            )
            load_event = app.load(
                fn=_load_examples_for_slider,
                inputs=[dataset_selector],
                outputs=[
                    example_selector,
                    example_state,
                    context_box,
                    prompt_box,
                    answer_box,
                ],
            ).then(
                fn=_build_model_answer_panel,
                inputs=[dataset_selector, example_selector],
                outputs=[model_answer_html],
                queue=False,
            )

            dataset_change_event.then(
                fn=_public_mode_compute,
                inputs=public_compute_inputs,
                outputs=public_compute_outputs,
                show_progress="full",
            )
            load_event.then(
                fn=_public_mode_compute,
                inputs=public_compute_inputs,
                outputs=public_compute_outputs,
                show_progress="full",
            )

            example_selector.release(
                fn=_update_example_preview,
                inputs=[example_selector, example_state],
                outputs=public_preview_outputs,
                queue=False,
            ).then(
                fn=_build_model_answer_panel,
                inputs=[dataset_selector, example_selector],
                outputs=[model_answer_html],
                queue=False,
            ).then(
                fn=_public_mode_compute,
                inputs=public_compute_inputs,
                outputs=public_compute_outputs,
                show_progress="full",
            )

            for component in (
                model_selector,
                scalarizer_selector,
                public_feature_level_selector,
                method_toggle,
            ):
                component.change(
                    fn=_public_mode_compute,
                    inputs=public_compute_inputs,
                    outputs=public_compute_outputs,
                    show_progress="full",
                )

        # ── MULTIMODAL TAB ──────────────────────────────────────────
        with gr.Tab("Multimodal"):

                with gr.Accordion("How to Use", open=False):
                    gr.Markdown(
                        "1. **Choose a dataset** from the three sub-tabs:\n"
                        "   - **MIMIC-CXR (10 Samples)** β€” chest X-rays across 10 pathology categories\n"
                        "   - **Dermoscopy ISIC (10 Samples)** β€” skin-lesion dermoscopy across 8 diagnostic classes\n"
                        "   - **MS-COCO (5 Samples)** β€” natural-image cross-modal benchmark\n"
                        "2. **Pick an example** from the dropdown (each is an image + caption pair)\n"
                        "3. **Choose an attribution method:** Influence (default, non-negative β€” clearer for clinicians) or Shapley (signed)\n"
                        "4. **Read the four panels side-by-side:**\n"
                        "   - **Interactive Cross-Modal View** β€” click any image patch or caption word to see its strongest cross-modal partners\n"
                        "   - **BiomedCLIP Cross-Modal Attribution** β€” patch-level overlay + bar charts (cosine-similarity scoring)\n"
                        "   - **LLaVA-Med Attribution** β€” log-prob and generation Shapley charts from the medical 7B VLM\n"
                        "   - **Compare Two Methods Side-by-Side** β€” pick any two of the above to overlay their rankings\n"
                        "5. **Hover token chips and patches** for exact attribution values; hover SVG arcs for pairwise interaction strength"
                    )

                with gr.Tab("MIMIC-CXR (10 Samples)"):
                    gr.Markdown(
                        "**10-sample MIMIC-CXR chest X-ray attribution benchmark** "
                        "(10 pathology categories).  \n"
                        "Source: [MIMIC-CXR-JPG](https://huggingface.co/datasets/itsanmolgupta/mimic-cxr-dataset-cleaned) "
                        "β€” de-identified chest radiographs from Beth Israel Deaconess Medical Center.  \n"
                        "Each example has a radiology report (impression = caption, findings = detail)."
                    )

                    # Build (category_name, example_id) choices so picking a
                    # pathology directly loads its example (1:1 mapping).
                    _mimic_choices = (
                        [(v["category"], k) for k, v in MIMIC_EXAMPLES.items()]
                        if _MIMIC_AVAILABLE else []
                    )

                    mimic_selector = gr.Dropdown(
                        choices=_mimic_choices,
                        value=None,
                        label="Filter by Pathology",
                        interactive=True,
                    )

                    mimic_method_toggle = gr.Radio(
                        choices=["Influence", "Shapley"],
                        value="Influence",
                        label="Attribution method",
                        info=(
                            "Influence (default) is always positive β€” clearer for clinicians. "
                            "Shapley is signed (green = supports caption, red = detracts)."
                        ),
                        interactive=True,
                    )

                    mimic_caption = gr.Textbox(
                        label="Radiology Impression (Caption)",
                        interactive=False,
                        lines=2,
                    )
                    with gr.Accordion("Full Radiology Findings", open=False):
                        mimic_findings = gr.Textbox(
                            label="Detailed Findings",
                            interactive=False,
                            lines=5,
                        )

                    # ── Original Image ────────────────────────────────
                    mimic_original = gr.Image(label="Chest X-ray", type="filepath")

                    mimic_interpretation = gr.Markdown(
                        value="*Select an example above to see the attribution analysis.*",
                        label="Interpretation",
                    )

                    # ── Table of Contents ─────────────────────────────
                    _mimic_pill = (
                        'style="display:inline-block;padding:6px 14px;background:#e3f2fd;'
                        'border-radius:16px;text-decoration:none;color:#1565c0;font-size:0.9em;'
                        'border:1px solid #bbdefb;"'
                    )
                    _mimic_toc_html = (
                        '<div style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:8px;'
                        'padding:16px;margin:12px 0;">'
                        '<strong style="font-size:1.05em;">Jump to Section:</strong>'
                        '<div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:10px;">'
                        f'<a href="#mimic-method-biomedclip" {_mimic_pill}>BiomedCLIP Cross-Modal</a>'
                        f'<a href="#mimic-method-llavamed" {_mimic_pill}>LLaVA-Med (UnSAM)</a>'
                        f'<a href="#mimic-interactive" {_mimic_pill}>Interactive View</a>'
                        f'<a href="#mimic-compare" {_mimic_pill}>Compare Methods</a>'
                        '</div></div>'
                    )
                    gr.HTML(value=_mimic_toc_html)

                    mimic_results_state = gr.State({})

                    # ════════════════════════════════════════════════════
                    # ── Interactive Cross-Modal View ───────────────────
                    # ════════════════════════════════════════════════════
                    with gr.Column(elem_id="mimic-interactive"):
                        gr.Markdown("---\n### BiomedCLIP Cross-Modal Interaction View β€” click segments or words")
                        gr.Markdown(
                            "**How to use:** Click any **image region** to see which caption words "
                            "it connects to, or click a **word** to see which regions activate.  \n"
                            "**Green** arrows = positive interaction. **Red** arrows = negative."
                        )
                        mimic_biomedclip_interaction_html = _html_component(
                            "BiomedCLIP Cross-Modal Interaction View")

                    # ════════════════════════════════════════════════════
                    # ── BiomedCLIP Cross-Modal Attribution ─────────────
                    # ════════════════════════════════════════════════════
                    with gr.Column(elem_id="mimic-method-biomedclip"):
                        gr.Markdown("---\n### BiomedCLIP Cross-Modal Attribution")
                        gr.Markdown(
                            "**What it does:** Uses [BiomedCLIP](https://huggingface.co/microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224) "
                            "β€” a CLIP model trained on **15 million biomedical figure-caption pairs** β€” "
                            "to jointly score image regions (via UnSAM segmentation) and caption tokens.  \n"
                            "**How to read:** **Green** = positive Shapley value (contributes to alignment). "
                            "**Red** = negative (hurts alignment)."
                        )
                        mimic_biomedclip_overlay = gr.Image(
                            label="BiomedCLIP Overlay (labeled segments)", type="filepath")
                        mimic_biomedclip_token_plot = gr.Plot(
                            label="BiomedCLIP β€” Caption Word Shapley Values")
                        mimic_biomedclip_region_plot = gr.Plot(
                            label="BiomedCLIP β€” Image Region Shapley Values")

                    # ════════════════════════════════════════════════════
                    # ── LLaVA-Med Attribution (UnSAM Segments) ─────────
                    # ════════════════════════════════════════════════════
                    with gr.Column(elem_id="mimic-method-llavamed"):
                        gr.Markdown("---\n### LLaVA-Med Attribution (4Γ—4 Patch Grid, P1–P16)")
                        gr.Markdown(
                            "**What it does:** Uses [LLaVA-Med](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf) "
                            "β€” a **7B parameter** medical VLM β€” evaluated over a **uniform 4Γ—4 patch grid** "
                            "(16 cells labeled **P1–P16**, row-major).  \n"
                            "**Two scoring approaches:**  \n"
                            "- **Log-Prob:** How removing a region affects confidence in the correct caption  \n"
                            "- **Generation:** How removing a region changes what the model describes"
                        )
                        gr.Markdown(
                            "Each method colors segments by its own Shapley values β€” "
                            "**green** = positive, **red** = negative. Signs often differ "
                            "between Log-Prob and Generation, so each has its own overlay."
                        )
                        with gr.Row(equal_height=True):
                            mimic_llavamed_unsam_lp_overlay = gr.Image(
                                label="LLaVA-Med Log-Prob β€” Overlay",
                                type="filepath", height=600)
                            mimic_llavamed_unsam_gen_overlay = gr.Image(
                                label="LLaVA-Med Generation β€” Overlay",
                                type="filepath", height=600)
                        with gr.Row():
                            mimic_llavamed_unsam_lp_plot = gr.Plot(
                                label="LLaVA-Med Log-Prob β€” Segment Shapley Values")
                            mimic_llavamed_unsam_gen_plot = gr.Plot(
                                label="LLaVA-Med Generation β€” Segment Shapley Values")

                    # ════════════════════════════════════════════════════
                    # ── Compare Two Methods Side-by-Side ──────────────
                    # ════════════════════════════════════════════════════
                    with gr.Column(elem_id="mimic-compare"):
                        gr.Markdown("---\n### Compare Two Methods Side-by-Side")
                        gr.Markdown(
                            "Select two methods to compare their attribution overlays "
                            "and Shapley value distributions on the same image."
                        )
                        with gr.Row():
                            mimic_compare_method_a = gr.Dropdown(
                                choices=_MIMIC_METHOD_NAMES,
                                label="Method A",
                                interactive=True,
                            )
                            mimic_compare_method_b = gr.Dropdown(
                                choices=_MIMIC_METHOD_NAMES,
                                label="Method B",
                                interactive=True,
                            )
                        with gr.Row():
                            mimic_compare_img_a = gr.Image(label="Method A β€” Overlay", type="filepath")
                            mimic_compare_img_b = gr.Image(label="Method B β€” Overlay", type="filepath")
                        with gr.Row():
                            mimic_compare_plot_a = gr.Plot(label="Method A β€” Shapley Values")
                            mimic_compare_plot_b = gr.Plot(label="Method B β€” Shapley Values")

                    mimic_meta = gr.JSON(label="Example Info", visible=False)

                    _mimic_outputs = [
                        mimic_caption, mimic_original, mimic_findings, mimic_interpretation,
                        mimic_biomedclip_overlay, mimic_biomedclip_token_plot,
                        mimic_biomedclip_region_plot, mimic_llavamed_unsam_lp_overlay,
                        mimic_llavamed_unsam_lp_plot, mimic_llavamed_unsam_gen_overlay,
                        mimic_llavamed_unsam_gen_plot, mimic_biomedclip_interaction_html,
                        mimic_meta, mimic_results_state, mimic_compare_method_a,
                    ]
                    mimic_selector.change(
                        fn=_on_select_mimic_example,
                        inputs=[mimic_selector, mimic_method_toggle],
                        outputs=_mimic_outputs,
                    )
                    mimic_method_toggle.change(
                        fn=_on_select_mimic_example,
                        inputs=[mimic_selector, mimic_method_toggle],
                        outputs=_mimic_outputs,
                    )

                    # Wire: comparison dropdowns -> side-by-side display
                    for _mimic_cmp_dd in [mimic_compare_method_a, mimic_compare_method_b]:
                        _mimic_cmp_dd.change(
                            fn=_on_mimic_compare_methods,
                            inputs=[mimic_compare_method_a, mimic_compare_method_b,
                                    mimic_results_state],
                            outputs=[mimic_compare_img_a, mimic_compare_img_b,
                                     mimic_compare_plot_a, mimic_compare_plot_b],
                        )

                # ── ISIC Dermoscopy Tab ────────────────────────
                with gr.Tab("Dermoscopy ISIC (10 Samples)"):
                    gr.Markdown(
                        "**10-sample ISIC-2019 dermoscopy attribution benchmark** "
                        "(8 diagnostic classes: MEL Γ— 2, NV Γ— 2, BCC, AK, BKL, DF, VASC, SCC).  \n"
                        "Source: [ISIC_2019_224](https://huggingface.co/datasets/MKZuziak/ISIC_2019_224) "
                        "β€” dermoscopic skin-lesion images from the International Skin Imaging Collaboration.  \n"
                        "Captions are synthesized from class labels (clinical descriptions of each diagnosis)."
                    )

                    _isic_choices = (
                        [(v["category"], k) for k, v in ISIC_EXAMPLES.items()]
                        if _ISIC_AVAILABLE else []
                    )

                    isic_selector = gr.Dropdown(
                        choices=_isic_choices,
                        value=None,
                        label="Filter by Diagnosis",
                        interactive=True,
                    )

                    isic_method_toggle = gr.Radio(
                        choices=["Influence", "Shapley"],
                        value="Influence",
                        label="Attribution method",
                        info=(
                            "Influence (default) is always positive β€” clearer for clinicians. "
                            "Shapley is signed (green = supports caption, red = detracts)."
                        ),
                        interactive=True,
                    )

                    isic_caption = gr.Textbox(
                        label="Diagnostic Caption",
                        interactive=False,
                        lines=3,
                    )

                    isic_original = gr.Image(label="Dermoscopic Image", type="filepath")

                    isic_interpretation = gr.Markdown(
                        value="*Select an example above to see the attribution analysis.*",
                        label="Interpretation",
                    )

                    _isic_pill = (
                        'style="display:inline-block;padding:6px 14px;background:#e3f2fd;'
                        'border-radius:16px;text-decoration:none;color:#1565c0;font-size:0.9em;'
                        'border:1px solid #bbdefb;"'
                    )
                    _isic_toc_html = (
                        '<div style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:8px;'
                        'padding:16px;margin:12px 0;">'
                        '<strong style="font-size:1.05em;">Jump to Section:</strong>'
                        '<div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:10px;">'
                        f'<a href="#isic-method-biomedclip" {_isic_pill}>BiomedCLIP Cross-Modal</a>'
                        f'<a href="#isic-method-llavamed" {_isic_pill}>LLaVA-Med (UnSAM)</a>'
                        f'<a href="#isic-interactive" {_isic_pill}>Interactive View</a>'
                        f'<a href="#isic-compare" {_isic_pill}>Compare Methods</a>'
                        '</div></div>'
                    )
                    gr.HTML(value=_isic_toc_html)

                    isic_results_state = gr.State({})

                    with gr.Column(elem_id="isic-interactive"):
                        gr.Markdown("---\n### BiomedCLIP Cross-Modal Interaction View β€” click segments or words")
                        gr.Markdown(
                            "**How to use:** Click any **image region** to see which caption words "
                            "it connects to, or click a **word** to see which regions activate."
                        )
                        isic_biomedclip_interaction_html = _html_component(
                            "BiomedCLIP Cross-Modal Interaction View")

                    with gr.Column(elem_id="isic-method-biomedclip"):
                        gr.Markdown("---\n### BiomedCLIP Cross-Modal Attribution")
                        gr.Markdown(
                            "**What it does:** Uses [BiomedCLIP](https://huggingface.co/microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224) "
                            "to jointly score dermoscopic image regions (via UnSAM segmentation) "
                            "and caption tokens.  \n"
                            "**How to read:** **Influence** bars (default) show positive importance. "
                            "Switch to **Shapley** above for signed values (green/red)."
                        )
                        isic_biomedclip_overlay = gr.Image(
                            label="BiomedCLIP Overlay (labeled segments)", type="filepath")
                        isic_biomedclip_token_plot = gr.Plot(
                            label="BiomedCLIP β€” Caption Word Values")
                        isic_biomedclip_region_plot = gr.Plot(
                            label="BiomedCLIP β€” Image Region Values")

                    with gr.Column(elem_id="isic-method-llavamed"):
                        gr.Markdown("---\n### LLaVA-Med Attribution (4Γ—4 Patch Grid, P1–P16)")
                        gr.Markdown(
                            "**What it does:** Uses [LLaVA-Med](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf) "
                            "β€” a **7B parameter** medical VLM β€” evaluated over a **uniform 4Γ—4 patch grid** "
                            "(16 cells labeled **P1–P16**, row-major).  \n"
                            "**Two scoring approaches:**  \n"
                            "- **Log-Prob:** How removing a region affects confidence in the caption  \n"
                            "- **Generation:** How removing a region changes what the model describes"
                        )
                        with gr.Row(equal_height=True):
                            isic_llavamed_unsam_lp_overlay = gr.Image(
                                label="LLaVA-Med Log-Prob β€” Overlay",
                                type="filepath", height=600)
                            isic_llavamed_unsam_gen_overlay = gr.Image(
                                label="LLaVA-Med Generation β€” Overlay",
                                type="filepath", height=600)
                        with gr.Row():
                            isic_llavamed_unsam_lp_plot = gr.Plot(
                                label="LLaVA-Med Log-Prob β€” Segment Values")
                            isic_llavamed_unsam_gen_plot = gr.Plot(
                                label="LLaVA-Med Generation β€” Segment Values")

                    with gr.Column(elem_id="isic-compare"):
                        gr.Markdown("---\n### Compare Two Methods Side-by-Side")
                        gr.Markdown(
                            "Select two methods to compare their attribution overlays "
                            "and value distributions on the same image."
                        )
                        with gr.Row():
                            isic_compare_method_a = gr.Dropdown(
                                choices=_ISIC_METHOD_NAMES,
                                label="Method A",
                                interactive=True,
                            )
                            isic_compare_method_b = gr.Dropdown(
                                choices=_ISIC_METHOD_NAMES,
                                label="Method B",
                                interactive=True,
                            )
                        with gr.Row():
                            isic_compare_img_a = gr.Image(label="Method A β€” Overlay", type="filepath")
                            isic_compare_img_b = gr.Image(label="Method B β€” Overlay", type="filepath")
                        with gr.Row():
                            isic_compare_plot_a = gr.Plot(label="Method A β€” Values")
                            isic_compare_plot_b = gr.Plot(label="Method B β€” Values")

                    isic_meta = gr.JSON(label="Example Info", visible=False)

                    _isic_outputs = [
                        isic_caption, isic_original, isic_interpretation,
                        isic_biomedclip_overlay, isic_biomedclip_token_plot,
                        isic_biomedclip_region_plot, isic_llavamed_unsam_lp_overlay,
                        isic_llavamed_unsam_lp_plot, isic_llavamed_unsam_gen_overlay,
                        isic_llavamed_unsam_gen_plot, isic_biomedclip_interaction_html,
                        isic_meta, isic_results_state, isic_compare_method_a,
                    ]
                    isic_selector.change(
                        fn=_on_select_isic_example,
                        inputs=[isic_selector, isic_method_toggle],
                        outputs=_isic_outputs,
                    )
                    isic_method_toggle.change(
                        fn=_on_select_isic_example,
                        inputs=[isic_selector, isic_method_toggle],
                        outputs=_isic_outputs,
                    )

                    for _isic_cmp_dd in [isic_compare_method_a, isic_compare_method_b]:
                        _isic_cmp_dd.change(
                            fn=_on_isic_compare_methods,
                            inputs=[isic_compare_method_a, isic_compare_method_b,
                                    isic_results_state],
                            outputs=[isic_compare_img_a, isic_compare_img_b,
                                     isic_compare_plot_a, isic_compare_plot_b],
                        )

                # ── MS-COCO Tab ─────────────────────────────────
                with gr.Tab("MS-COCO (5 Samples)"):
                    gr.Markdown(
                        "**CLIP cross-modal attribution on MS-COCO natural images.**  \n"
                        "Click an **image region** or **caption word** below to explore "
                        "which parts of the image and text are most strongly linked via "
                        "CLIP's visual-language similarity score."
                    )

                    _coco_choices = (
                        [(v["title"], k) for k, v in COCO_EXAMPLES.items()]
                        if _COCO_AVAILABLE else []
                    )
                    _coco_default = _coco_choices[0][1] if _coco_choices else None
                    coco_selector = gr.Radio(
                        choices=_coco_choices,
                        value=_coco_default,
                        label="Select MS-COCO Example",
                        interactive=True,
                    )
                    coco_method_toggle = gr.Radio(
                        choices=["Influence", "Shapley"],
                        value="Influence",
                        label="Attribution method",
                        info="Influence (default) is always positive. Shapley is signed.",
                        interactive=True,
                    )
                    coco_caption = gr.Textbox(
                        label="Caption", interactive=False, lines=2,
                    )

                    gr.Markdown("---\n#### Interactive Cross-Modal View")
                    gr.Markdown(
                        "Click a colored **image region** (left) to highlight the caption "
                        "words it interacts with, or click a **word** (right) to highlight "
                        "linked regions. Green = positive, red = negative."
                    )
                    coco_interaction_html = _html_component(
                        "COCO Cross-Modal Interaction View")

                    gr.Markdown("---\n#### Attribution Details")
                    with gr.Row():
                        coco_original = gr.Image(
                            label="Original Image", type="filepath")
                        coco_overlay = gr.Image(
                            label="CLIP Overlay (labeled segments)", type="filepath")

                    with gr.Row():
                        coco_token_plot = gr.Plot(
                            label="Caption Word Shapley Values")
                        coco_region_plot = gr.Plot(
                            label="Image Region Shapley Values")

                    with gr.Row():
                        coco_cross_plot = gr.Plot(
                            label="Top Image x Word Interactions")
                        coco_cross_table = gr.Dataframe(
                            headers=["Image Region", "Caption Word", "Score"],
                            label="Cross-Modal Interaction Table",
                            interactive=False,
                        )

                    with gr.Accordion("Influence Heatmap (Regions x Words)",
                                      open=False):
                        coco_heatmap = gr.Plot(
                            label="Full Heatmap: Regions x Caption Words")

                    gr.Markdown("---\n#### Masked Image Browser")
                    gr.Markdown(
                        "Browse ablation images: **solo** shows only the selected region "
                        "(everything else inpainted away); **removed** shows the image with "
                        "that region inpainted out."
                    )
                    with gr.Row():
                        coco_masked_dd = gr.Dropdown(
                            choices=[],
                            label="Region / View",
                            interactive=True,
                        )
                        coco_masked_img = gr.Image(
                            label="Masked View", type="filepath")

                    coco_note = gr.Markdown(value="")

                    _coco_outputs = [
                        coco_caption,
                        coco_original,
                        coco_overlay,
                        coco_interaction_html,
                        coco_token_plot,
                        coco_region_plot,
                        coco_cross_plot,
                        coco_cross_table,
                        coco_heatmap,
                        coco_note,
                        coco_masked_img,
                        coco_masked_dd,
                    ]
                    coco_selector.change(
                        fn=_on_select_coco_example,
                        inputs=[coco_selector, coco_method_toggle],
                        outputs=_coco_outputs,
                    )
                    coco_method_toggle.change(
                        fn=_on_select_coco_example,
                        inputs=[coco_selector, coco_method_toggle],
                        outputs=_coco_outputs,
                    )
                    coco_masked_dd.change(
                        fn=_on_select_coco_masked,
                        inputs=[coco_selector, coco_masked_dd],
                        outputs=[coco_masked_img],
                    )

        # NOTE: auto-load removed β€” too much data on startup crashes the browser.
        # Users select an example via the Radio to trigger loading.

        gr.HTML(
            '<div style="margin-top:32px;padding:20px;border-top:1px solid #e5e7eb;text-align:center;">'
            '<p style="font-weight:600;margin-bottom:10px;">Contributors β€” University of California, Berkeley</p>'
            '<p style="display:flex;justify-content:center;gap:40px;flex-wrap:wrap;font-size:0.9em;">'
            '<span><strong>Stephen Tao</strong> Β· Loader Layer Β· '
            '<a href="mailto:stephen_tao@berkeley.edu" style="color:#6366f1;">stephen_tao@berkeley.edu</a></span>'
            '<span><strong>Yiting Gao</strong> Β· Attribution Layer Β· '
            '<a href="mailto:yg2025@berkeley.edu" style="color:#6366f1;">yg2025@berkeley.edu</a></span>'
            '<span><strong>Qingpeng Kong</strong> Β· Visualization Layer Β· '
            '<a href="mailto:qpkong@berkeley.edu" style="color:#6366f1;">qpkong@berkeley.edu</a></span>'
            '</p>'
            '<p style="display:flex;justify-content:center;gap:40px;flex-wrap:wrap;font-size:0.9em;margin-top:6px;">'
            '<span><strong>Advisor:</strong> Kannan Ramchandran Β· '
            '<a href="mailto:kannanr@berkeley.edu" style="color:#6366f1;">kannanr@berkeley.edu</a></span>'
            '<span><strong>Mentor:</strong> Landon Butler Β· '
            '<a href="mailto:landonb@berkeley.edu" style="color:#6366f1;">landonb@berkeley.edu</a></span>'
            '</p></div>'
        )

    # Stash CSS for Gradio 6.x launch() (Blocks(css=) is deprecated in 6.x)
    app._custom_css = custom_css
    return app


def _launch_kwargs(app_or_demo, **kwargs):
    """Build common launch kwargs, injecting CSS for Gradio 6.x."""
    lk = dict(
        server_name=kwargs.pop("server_name", os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")),
        server_port=int(kwargs.pop("server_port", os.getenv("GRADIO_SERVER_PORT", "7860"))),
        share=kwargs.pop("share", _env_flag("GRADIO_SHARE", False)),
        show_error=kwargs.pop("show_error", True),
    )
    css = getattr(app_or_demo, "_custom_css", None)
    if css and _supports_kwarg(app_or_demo.launch, "css"):
        lk["css"] = css
    lk.update(kwargs)
    return lk


def launch_demo(**kwargs):
    demo = build_demo_app()
    demo.launch(**_launch_kwargs(demo, **kwargs))


def launch_app(**kwargs):
    app = build_app()
    app.launch(**_launch_kwargs(app, **kwargs))


if __name__ == "__main__":
    launch_app()