File size: 164,435 Bytes
bc9f3e6 dab4ea2 bc9f3e6 dab4ea2 bc9f3e6 | 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 | """web_api.py β FastAPI backend for the custom (non-Gradio) LocalAiLab UI.
Serves the built Svelte SPA from ``ui/web/dist`` and exposes a small JSON +
WebSocket API. The chat WebSocket streams the SAME generator the Gradio UI
uses (``backend/chat.chat_general``), so every tested code path (agent build,
step formatting, final-answer chunking, docx export text) is reused unchanged β
the new UI is a different frontend over the same backend, not a reimplementation.
Run for development: python tools/_launch_web.py
Run inside pywebview: python run_webview.py --ui web
"""
import asyncio
import os
import re
import secrets
import shutil
import sys
import threading
import time
import traceback
from pathlib import Path
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
from backend import model_registry as mr
from backend import models
from backend import user_config
DIST = Path(__file__).resolve().parent.parent / "ui" / "web" / "dist"
APP_ICON = Path(__file__).resolve().parent.parent / "ui" / "image" / "logo_round.png"
# Xet (hf_xet) reports 0 bytes through its tqdm progress callback, which makes
# the model-download progress bar sit frozen at 0% (the "static progress" bug).
# Force the standard http_get download path β it reports real chunk sizes via
# tqdm.update(len(chunk)) so the live progress bar actually moves. http_get is
# the universally-compatible baseline, so this is also a robustness win.
os.environ["HF_HUB_DISABLE_XET"] = "1"
# (tab key, icon, i18n label key)
TABS = [
("general", "π¬", "tab_general"),
("rag", "π", "tab_rag"),
("deep_research", "π¬", "tab_deep_research"),
("stt", "ποΈ", "tab_stt"),
("data", "π", "tab_data"),
("kb", "π", "tab_kb"),
("vision", "πΌοΈ", "tab_vision"),
("about", "βΉοΈ", "tab_about"),
("feedback", "βοΈ", "tab_feedback"),
("settings", "βοΈ", "tab_settings"),
]
_PROVIDER_OPTIONS = mr.LLM_PROVIDER_OPTIONS
# VLM provider map β a separate, smaller set (no LiteLLM) used by the Vision
# tab's picker and by /api/mmproj's provider resolution.
_VLM_PROVIDER_OPTIONS = mr.VLM_PROVIDER_OPTIONS
# Client-facing tab keys (TABS above) β canonical backend keys used by
# model_registry._PROVIDER_KEYS / REPORT_DIRS ("gen", "rag", "dr", "vis",
# "stt", "data"). Without this mapping the provider would silently never
# persist and reports would land in the wrong folder.
_BACKEND_TAB = {
"general": "gen",
"rag": "rag",
"deep_research": "dr",
"vision": "vis",
"stt": "stt",
"data": "data",
"kb": "kb",
"about": "about",
"feedback": "feedback",
"settings": "settings",
}
def _backend_tab(tab: str) -> str:
return _BACKEND_TAB.get(tab) or "gen"
# Provider persistence keys (model_registry._PROVIDER_KEYS) β NOT the same as
# report-folder keys above: the Vision tab persists under "vlm" (provider_vlm),
# while its reports live in the "vis" folder. Calling set_saved_provider("vis")
# would silently no-op (no _PROVIDER_KEYS entry), so provider saves MUST go
# through this map.
_PROVIDER_TAB = {
"general": "gen",
"rag": "rag",
"deep_research": "dr",
"vision": "vlm",
"stt": "stt",
"data": "data",
# KB's provider/model persist under the embed slots (provider_embed /
# model_embed) β the tab maps to "embed" like the STT tab maps to "stt".
"kb": "embed",
}
def _provider_tab(tab: str) -> str:
return _PROVIDER_TAB.get(tab) or _backend_tab(tab)
# smolagents' LocalPythonExecutor `timeout_seconds` default β the AUTO value
# the General / RAG / Deep Research "Exec timeout" controls resolve to
# (build_smol_agent passes executor_kwargs only when the control holds an
# explicit number, so this is what actually runs when it is empty).
_SMOLAGENTS_EXEC_TIMEOUT_DEFAULT = 30
def _auto_defaults() -> dict:
"""The concrete values the chat tabs' "auto" controls resolve to, keyed
by CLIENT tab name (same keys as savedStepBudgets / savedExecutionTimeout).
Step budgets are the agents' *_DEFAULT_MAX_STEPS base constants (the
frontend scales them per the LIVE model picker label, mirroring
mr.get_max_steps_for_model β see ui/web/src/lib/autoDefaults.js); exec
timeouts are the CodeAgent-path executor defaults; runTimeout None means
auto = no explicit whole-run deadline. All constants live here (or in the
agent modules they reference), never duplicated in the web UI."""
from agents import (
data_analysis,
deep_research_agent,
general_agent,
rag_agent,
)
return {
"stepBudgets": {
"general": general_agent.GENERAL_AGENT_DEFAULT_MAX_STEPS,
"rag": rag_agent.RAG_AGENT_DEFAULT_MAX_STEPS,
"rag_searcher": rag_agent.SEARCHER_DEFAULT_MAX_STEPS,
"deep_research": deep_research_agent.MANAGER_DEFAULT_MAX_STEPS,
"deep_research_search": deep_research_agent.SEARCH_AGENT_DEFAULT_MAX_STEPS,
"data": mr.DATA_AGENT_MAX_STEPS,
"data_worker": data_analysis.DATA_WORKER_DEFAULT_MAX_STEPS,
},
"execTimeout": {
"general": _SMOLAGENTS_EXEC_TIMEOUT_DEFAULT,
"rag": _SMOLAGENTS_EXEC_TIMEOUT_DEFAULT,
"deep_research": _SMOLAGENTS_EXEC_TIMEOUT_DEFAULT,
"data": data_analysis.DATA_EXECUTION_TIMEOUT_DEFAULT,
},
"runTimeout": None,
}
# Per-tab context-window persistence keys β DERIVED from the backend's own
# _CONTEXT_WINDOW_KEYS (gen/rag/data/dr/vlm) through the same clientβbackend
# mapping as _PROVIDER_TAB (vision β vlm), so a context-window key added to
# model_registry is automatically exposed here instead of needing a second
# hand-maintained map to stay in sync. The five chat tabs that run an
# LLM/VLM each get their own n_ctx dropdown in Settings.
_CTX_WINDOW_TABS = {
client: backend
for client, backend in _PROVIDER_TAB.items()
if backend in mr._CONTEXT_WINDOW_KEYS
}
def _ctx_window_payload() -> dict:
"""The per-tab context-window dropdown contract β the dropdown options
are the CONTEXT_WINDOW_OPTIONS LABELS (the label IS the value the UI
posts back β the backend maps it to the token count), and savedCtxWindow
holds each chat tab's currently-saved label so its dropdown initializes
to whatever was last chosen. Shared by /api/meta (the chat panes' shared
startup payload) and the /api/settings-family endpoint β the helper IS
the contract, so the two endpoints can never drift."""
return {
"contextWindowOptions": list(mr.CONTEXT_WINDOW_OPTIONS.keys()),
"savedCtxWindow": {
client: mr.get_saved_context_window_label(backend)
for client, backend in _CTX_WINDOW_TABS.items()
},
}
def _i18n_dict():
from ui.i18n import LANGUAGES # dicts only β lightweight, no UI framework
return LANGUAGES
def _lang(lang_key: str) -> dict:
d = _i18n_dict()
return d.get(lang_key) or d.get("kh") or {}
def _tab_label(tab_key: str, lang_key: str) -> str:
i18n_key = next((k for (_t, _i, k) in TABS if _t == tab_key), None)
if i18n_key:
return _lang(lang_key).get(i18n_key, tab_key)
return tab_key
def _reset_agents_for(backend_tab: str):
"""Drop the cached agent for the affected tab so the next run rebuilds
with the newly chosen provider/model (mirrors the Gradio reload handlers)."""
try:
if backend_tab == "gen":
from agents import general_agent
general_agent.reset_agent()
elif backend_tab == "rag":
from agents import rag_agent
rag_agent.reset_agent()
elif backend_tab == "dr":
from agents import deep_research_agent
deep_research_agent.reset_agent()
elif backend_tab == "data":
# Data's agent is cached per model choice β a header provider/model
# switch must drop it so the next run rebuilds with the new pick
# (mirrors the Gradio do_reload_data handler).
from agents import data_analysis
data_analysis.reset_agent()
except Exception:
pass
_SESSION_TOKEN = os.environ.get("LOCALAILAB_SESSION_TOKEN") or secrets.token_urlsafe(32)
def get_session_token() -> str:
"""Return the active local session authentication token."""
return _SESSION_TOKEN
app = FastAPI(title="LocalAiLab Assistant", docs_url=None, redoc_url=None)
# Explicit CORS: restrict origins to local loopback and webview custom schemes
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"^(http://(127\.0\.0\.1|localhost)(:\d+)?|null|app://.*|pywebview://.*)$",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def verify_session_token(request: Request, call_next):
path = request.url.path
# Allow static assets, health check, favicon, and root SPA HTML without token
if (
path.startswith("/assets/")
or path in ("/favicon.png", "/api/health")
or not path.startswith("/api/")
):
return await call_next(request)
token = request.headers.get("X-Session-Token") or request.query_params.get("token")
if not token or token != _SESSION_TOKEN:
return JSONResponse(
{"ok": False, "message": "Unauthorized: invalid or missing session token"},
status_code=401,
)
return await call_next(request)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# JSON API
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/health")
def health():
from ui.branding import APP_NAME_EN, APP_NAME_KH, APP_VERSION
return {"ok": True, "app": APP_NAME_EN, "app_kh": APP_NAME_KH, "version": APP_VERSION}
@app.get("/api/meta")
def meta():
from backend import knowledge_base as kb
from ui.branding import APP_NAME_EN, APP_NAME_KH, APP_VERSION
lang_key = str(user_config.USER_CONFIG.get("lang", "kh")) or "kh"
app_name = APP_NAME_KH if lang_key == "kh" else APP_NAME_EN
kb_themes, kb_subthemes = kb.get_existing_themes_and_subthemes()
models = {
label: list(mr.get_model_options_for_provider(sentinel, "llm").keys())
for label, sentinel in _PROVIDER_OPTIONS.items()
}
# The Data tab's model lists β the LLM chat tabs' list with the
# verified-ladder exclusions applied (a GGUF whose Data harness leg
# failed is still fine for General / RAG / Deep Research but is NOT
# offered on the Data tab β see
# mr.is_data_tab_excluded_model / DATA_TAB_EXCLUDED_MODEL_MARKERS).
data_models = {
label: [
m for m in list(mr.get_model_options_for_provider(sentinel, "llm").keys())
if not mr.is_data_tab_excluded_model(m)
]
for label, sentinel in _PROVIDER_OPTIONS.items()
}
# Per-tab saved provider/model for the migrated chat tabs (client-facing
# keys) β the header pickers rebind per active tab, like Gradio's
# per-tab dropdowns.
saved_provider = {}
saved_model = {}
for client_key, backend_key, model_type, provider_map in (
("general", "gen", "llm", _PROVIDER_OPTIONS),
("rag", "rag", "llm", _PROVIDER_OPTIONS),
("deep_research", "dr", "llm", _PROVIDER_OPTIONS),
("vision", "vlm", "vlm", _VLM_PROVIDER_OPTIONS),
("data", "data", "llm", _PROVIDER_OPTIONS),
):
sentinel = mr.get_saved_provider(backend_key)
saved_provider[client_key] = mr.get_provider_label(provider_map, sentinel)
_choices, default_model = mr.get_model_dropdown_defaults(backend_key, model_type)
# The user's LAST model pick (persisted label) when it's still a
# valid choice for the tab's provider; otherwise the provider's
# default β a GGUF file removed / CSV edited between sessions must
# degrade to a valid model, never a stale label.
saved_label = mr.get_saved_model(backend_key)
saved_model[client_key] = saved_label if saved_label in _choices else default_model
vlm_models = {
label: list(mr.get_model_options_for_provider(sentinel, "vlm").keys())
for label, sentinel in _VLM_PROVIDER_OPTIONS.items()
}
# STT β provider dropdown (STT_PROVIDER_OPTIONS) + a flat STT model list
# (STT_OPTIONS labels, mirroring the Gradio stt_dd choices).
stt_providers = [
{"label": label, "value": sentinel}
for label, sentinel in mr.STT_PROVIDER_OPTIONS.items()
]
stt_models = {
label: list(mr.get_model_options_for_provider(sentinel, "stt").keys())
for label, sentinel in mr.STT_PROVIDER_OPTIONS.items()
}
_stt_choices, _stt_model_default = mr.get_model_dropdown_defaults("stt", "stt")
_stt_model_saved = mr.get_saved_model("stt")
if _stt_model_saved in _stt_choices:
_stt_model_default = _stt_model_saved
_stt_llm_choices, _stt_llm_default = mr.get_llm_dropdown_defaults("stt_report")
_stt_llm_saved = mr.get_saved_model("stt_report")
if _stt_llm_saved in _stt_llm_choices:
_stt_llm_default = _stt_llm_saved
# Embeddings β per-provider model lists (mirrors the KB tab's embed_dd).
embed_providers = [
{"label": label, "value": sentinel}
for label, sentinel in mr.EMBED_PROVIDER_OPTIONS.items()
]
embed_models = {
label: list(mr.get_model_options_for_provider(sentinel, "embed").keys())
for label, sentinel in mr.EMBED_PROVIDER_OPTIONS.items()
}
_embed_choices, _embed_default = mr.get_model_dropdown_defaults("embed", "embed")
_embed_saved = mr.get_saved_model("embed")
if _embed_saved in _embed_choices:
_embed_default = _embed_saved
return {
"app": {"name": app_name, "version": APP_VERSION, "lang": lang_key},
# True on the very first launch (the onboarding was never dismissed)
# β the SPA lands on the Settings tab and shows the setup popup.
"firstRun": user_config.is_first_run(),
"tabs": [
{"key": key, "icon": icon, "label": _tab_label(key, lang_key)}
for (key, icon, _k) in TABS
],
"providers": [
{"label": label, "value": sentinel}
for label, sentinel in _PROVIDER_OPTIONS.items()
],
"vlmProviders": [
{"label": label, "value": sentinel}
for label, sentinel in _VLM_PROVIDER_OPTIONS.items()
],
"vlmModels": vlm_models,
"savedProvider": saved_provider,
"models": models,
"dataModels": data_models,
"savedModel": saved_model,
# STT tab
"sttProviders": stt_providers,
"sttModels": stt_models,
"savedStt": {
"provider": mr.get_provider_label(mr.STT_PROVIDER_OPTIONS, mr.get_saved_provider("stt")),
"model": _stt_model_default,
"llmProvider": mr.get_provider_label(mr.LLM_PROVIDER_OPTIONS, mr.get_saved_provider("stt_report")),
"llmModel": _stt_llm_default,
},
# KB tab
"embedProviders": embed_providers,
"embedModels": embed_models,
"savedEmbed": {
"provider": mr.get_provider_label(mr.EMBED_PROVIDER_OPTIONS, mr.get_saved_provider("embed")),
"model": _embed_default,
},
"visualRetrievers": list(mr.VISUAL_RETRIEVER_OPTIONS.keys()),
"themes": kb_themes or [],
"subthemes": kb_subthemes or [],
# STT language picker (value β label) β DERIVED from the registry's
# STT_LANG_OPTIONS constant (the single source of truth, shared with
# the /api/settings/save stt_lang validator) so the option list and
# the persistence contract can never drift. 'auto' is the only value
# whose label isn't just the capitalized name.
"sttLanguages": [
{
"value": v,
"label": "Auto-detect" if v == "auto" else v.capitalize(),
}
for v in mr.STT_LANG_OPTIONS
],
# Data Analysis tab
"analysisTypes": ["exploratory", "sales", "customer", "financial", "payroll"],
"reportBaseDir": mr.REPORT_BASE_DIR,
# Per-tab agentic step budgets (Max Steps / Search steps) β the chat
# panes initialize their step controls from these on mount. A value
# is the user's explicit budget; None = AUTO (model-scaled default).
"savedStepBudgets": {
"general": mr.get_saved_agent_steps("gen"),
"rag": mr.get_saved_agent_steps("rag"),
"rag_searcher": mr.get_saved_sub_agent_steps("rag"),
"deep_research": mr.get_saved_agent_steps("dr"),
"deep_research_search": mr.get_saved_sub_agent_steps("dr"),
"deep_research_timeout": mr.get_saved_agent_run_timeout("dr"),
"data": mr.get_saved_agent_steps("data"),
"data_worker": mr.get_saved_sub_agent_steps("data"),
},
# Per-tab agentic execution timeout (each agentic tab's "Exec
# timeout" control β General / RAG / Deep Research / Data) β an int
# is the user's per-step code-executor timeout; null = AUTO (the
# agent factory's default). Same shape as savedStepBudgets so panes
# initialize their controls from meta.
"savedExecutionTimeout": {
"general": mr.get_saved_execution_timeout("gen"),
"rag": mr.get_saved_execution_timeout("rag"),
"deep_research": mr.get_saved_execution_timeout("dr"),
"data": mr.get_saved_execution_timeout("data"),
},
# Per-tab generation RUN timeout (each chat tab's Generation Settings
# "Timeout" control; Deep Research was the first to expose it) β an
# int is the user's whole-run wall-clock deadline in seconds; null =
# no explicit deadline. Keyed by CLIENT tab name (the panes read
# app.meta.savedRunTimeout[tab]); the backend keys are gen/rag/dr/vlm/data.
"savedRunTimeout": {
"general": mr.get_saved_agent_run_timeout("gen"),
"rag": mr.get_saved_agent_run_timeout("rag"),
"deep_research": mr.get_saved_agent_run_timeout("dr"),
"vision": mr.get_saved_agent_run_timeout("vlm"),
"data": mr.get_saved_agent_run_timeout("data"),
},
# Whether the RAG tab's resource-intensive visual path (the agentic
# `visual_retriever` page-image tool + the VLM grounding pass) is
# enabled β DEFAULT OFF (pure text-retrieval + text-LLM pipeline).
"savedVisualRetrieval": mr.get_rag_visual_retrieval(),
# The concrete values the chat tabs' "auto" controls resolve to β
# the web UI renders these IN the empty fields instead of the opaque
# word "auto", so the user sees the real default (e.g. "8" steps, a
# "no limit" run). stepBudgets are the agents' *_DEFAULT_MAX_STEPS
# BASE constants (Python-owned); the frontend applies the same
# model-size scaling as mr.get_max_steps_for_model against the LIVE
# picker label (ui/web/src/lib/autoDefaults.js) so the shown value
# stays accurate after a mid-session model switch. execTimeout is
# smolagents' LocalPythonExecutor default (30s β build_smol_agent
# passes nothing when the control is None) for the CodeAgent-path
# tabs, and Data's own DATA_EXECUTION_TIMEOUT_DEFAULT (120s).
# runTimeout None = auto means "no explicit deadline β the run
# finishes naturally" (the frontend renders it as "no limit").
"autoDefaults": _auto_defaults(),
# NOTE: the llama-server per-request timeout is NOT in /api/meta β it
# is a GLOBAL setting (one shared llama-server subprocess) edited
# ONLY from the Settings tab (its number input), persisted under the
# 'llama_server_timeout' user_config key and exposed via /api/settings.
# Per-tab context window (n_ctx) β RELOCATED into each relevant
# tab's settings (the four chat panes' collapsed Generation Settings
# section + the Data tab card), so it must ride the shared /api/meta
# payload the panes initialize from, not just /api/settings (the
# chat panes read app.meta β a restart would otherwise render the
# dropdowns with zero options).
**_ctx_window_payload(),
# App-wide Alt+Delete clear-confirmation threshold (messages) β the
# chat panes' confirm() closures read this live at keypress time, so
# a Settings-tab change takes effect without a restart.
"clearConfirmMin": mr.get_saved_clear_confirm_min() or mr.CLEAR_CONFIRM_MIN_DEFAULT,
# STT tab's π§ Reduce Noise strength preset β the picker initializes
# from this on mount, so the tab reopens on the user's last pick.
"denoiseStrength": mr.get_saved_denoise_strength(),
# STT tab's transcription language β the language dropdown
# initializes from this on mount, so the tab reopens on the user's
# last pick (auto / english / khmer / french / chinese / japanese).
"sttLanguage": mr.get_saved_stt_lang(),
"sttMicDevice": mr.get_saved_stt_mic(),
# Set by packaging later; when non-empty the placeholder tabs show a
# "Open Classic UI" button pointing here.
"classicUrl": "",
}
@app.get("/api/i18n")
def i18n(lang: str = "kh"):
d = _i18n_dict()
return d.get(lang) or d.get("kh") or {}
@app.post("/api/first-run/dismiss")
async def first_run_dismiss():
"""Mark the first-run onboarding as seen (the Settings-tab landing + popup
shown on the very first launch). Idempotent β called when the user
dismisses the popup, so it never shows again on later launches."""
user_config.mark_first_run_done()
return {"ok": True}
@app.get("/api/model-notice")
def model_notice(provider: str = "", model: str = "", type: str = "llm", lang: str = "kh"):
"""The 'already downloaded?' notice for the header model picker β the web
port of report_tools.get_model_download_notice, the single source of
truth. Returns {ok, notice}; the notice is empty when no model is
selected or the lookup fails."""
if not model:
return {"ok": True, "notice": ""}
from backend.report_tools import get_model_download_notice # Gradio-free
try:
notice = get_model_download_notice(
provider or "", model, option_type=type or "llm", lang_key=lang or "kh"
)
except Exception:
notice = ""
return {"ok": True, "notice": notice}
# ββ Model pre-download endpoint βββββββββββββββββββββββββββββββββββββββββ
# Triggers a background download of a HuggingFace model (transformers or
# GGUF preset) so the "Download Now" button can kick off the download
# without waiting for the first chat message. Uses its OWN shared state
# (separate from the component _DL_STATE) so component and model downloads
# never block each other.
_MODEL_DL_STATE: dict = {
"running": False,
"model_id": "",
"model_label": "",
"progress": None,
"dl_mb": "",
"total_mb": "",
"speed_mb": "",
"label": "",
"status_line": "",
"done": False,
"error": "",
"cancelled": False,
}
_MODEL_DL_LOCK = threading.Lock()
# Cancellation signal for an in-flight model download. Set by
# POST /api/model-download-cancel; checked inside _ModelDownloadProgress so the
# blocking hf_hub_download call is aborted mid-stream.
_MODEL_DL_CANCEL = threading.Event()
class _ModelDownloadCancelled(Exception):
"""Raised from the tqdm callback to abort an in-flight download."""
pass
# Module-level cumulative tracking for snapshot_download's multi-tqdm pattern.
# huggingface_hub.snapshot_download (>= 1.25) does NOT pass the user's
# tqdm_class to individual file downloads. Instead it:
#
# 1. Creates two tqdm instances with the user's tqdm_class:
# - transfer_progress total=0 (Xet transfer bytes)
# - reconstruct_progress total=0 (byte reconstruction)
# 2. Wraps each hf_hub_download in an _AggregatedTqdm that:
# a) Adds each file's size to reconstruct_progress.total (total grows)
# b) Forwards update(n) bytes to reconstruct_progress.update(n)
# 3. Creates a thread-map tqdm for hf_thread_map with total=N (file count)
#
# For hf_hub_download (GGUF path), each file gets its own tqdm with
# total=file_size β standard per-instance accumulation.
#
# The tricky part: reconstruct_progress starts with total=0, so a cached
# "is_real_file" flag computed at __init__ stays False forever, ignoring
# all update() calls. We solve this with LAZY registration: _is_registered
# starts False and _ensure_registered() promotes it when total first becomes
# positive (or grows further via _AggregatedTqdm).
_DL_ACCUM_BYTES = 0 # cumulative bytes downloaded across real files
_DL_ACCUM_TOTAL = 0 # sum of sizes of real files we have registered
_DL_ACCUM_START = 0.0 # time.time() when the first real tqdm was created
_DL_ACCUM_LAST_UPDATE = 0.0 # throttle for state writes
def _dl_accum_reset():
global _DL_ACCUM_BYTES, _DL_ACCUM_TOTAL, _DL_ACCUM_START, _DL_ACCUM_LAST_UPDATE
_DL_ACCUM_BYTES = 0
_DL_ACCUM_TOTAL = 0
_DL_ACCUM_START = 0.0
_DL_ACCUM_LAST_UPDATE = 0.0
def _dl_accum_push_state(desc: str = ""):
"""Write the cumulative progress into _MODEL_DL_STATE (throttled)."""
global _DL_ACCUM_LAST_UPDATE
now = time.time()
if now - _DL_ACCUM_LAST_UPDATE < 0.25 and _DL_ACCUM_BYTES < _DL_ACCUM_TOTAL:
return # throttle
_DL_ACCUM_LAST_UPDATE = now
total = _DL_ACCUM_TOTAL
done = _DL_ACCUM_BYTES
pct = int(min(100, max(0, (done / total * 100)))) if total > 0 else 0
elapsed = now - _DL_ACCUM_START if _DL_ACCUM_START else 0.0
speed = (done / elapsed / (1024 * 1024)) if elapsed > 0.1 else 0.0
total_mb = (total / (1024 * 1024)) if total else 0.0
dl_mb = (done / (1024 * 1024))
d = desc or "model files"
if d.startswith("Downloading "):
d = d[12:]
line = f"Downloading {d} ({pct}%)"
if total_mb > 0:
line += f" Β· {dl_mb:.1f} / {total_mb:.1f} MB"
if speed > 0:
line += f" ({speed:.1f} MB/s)"
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["progress"] = pct
_MODEL_DL_STATE["dl_mb"] = f"{dl_mb:.1f}" if total_mb > 0 else ""
_MODEL_DL_STATE["total_mb"] = f"{total_mb:.1f}" if total_mb > 0 else ""
_MODEL_DL_STATE["speed_mb"] = f"{speed:.1f}" if speed > 0 else ""
_MODEL_DL_STATE["label"] = d
_MODEL_DL_STATE["status_line"] = line
# Minimum total bytes to register a tqdm as a "real file download".
# Filters out metadata phases (total=0) and file-count progress bars (total=N)
# that huggingface_hub creates before the actual per-file downloads start.
_DL_MIN_FILE_BYTES = 1024
class _ModelDownloadProgress:
"""tqdm-compatible progress tracker that updates _MODEL_DL_STATE in real-time.
Two usage patterns:
1. **hf_hub_download (GGUF path)**: each file gets its own instance with
total=file_size. Registered immediately in __init__.
2. **snapshot_download (HF model path)**: the user's tqdm_class is used for
``reconstruct_progress`` which starts with total=0. ``_AggregatedTqdm``
(huggingface_hub internal) later sets ``self.total`` to the cumulative
file sizes and calls ``self.update(n)`` with cumulative bytes. We detect
the total transition via _ensure_registered() and start tracking.
"""
def __init__(self, *args, **kwargs):
global _DL_ACCUM_BYTES, _DL_ACCUM_TOTAL, _DL_ACCUM_START
self.total = kwargs.get("total") or 0
self.n = kwargs.get("initial") or 0
self.desc = kwargs.get("desc") or ""
self.start_time = time.time()
self.last_time = self.start_time
self._instance_n_at_start = 0 # snapshot of cumulative bytes at creation
self._is_registered = False # whether registered in _DL_ACCUM_TOTAL
self._registered_total = 0 # total at time of registration (for delta)
# Immediate registration for hf_hub_download path (total known at init)
if self.total >= _DL_MIN_FILE_BYTES:
if _DL_ACCUM_START == 0.0:
_DL_ACCUM_START = self.start_time
self._instance_n_at_start = _DL_ACCUM_BYTES
_DL_ACCUM_TOTAL += self.total
self._registered_total = self.total
self._is_registered = True
def _ensure_registered(self):
"""Lazily register when total first becomes positive.
snapshot_download creates tqdm(total=0) then _AggregatedTqdm later
sets self.total to the cumulative file sizes. We detect this and
register lazily. Also handles total growing further as more files
are added to _AggregatedTqdm.
"""
global _DL_ACCUM_BYTES, _DL_ACCUM_TOTAL, _DL_ACCUM_START
if self._is_registered:
# Total may have grown β update the delta in _DL_ACCUM_TOTAL.
if self.total > self._registered_total:
_DL_ACCUM_TOTAL += (self.total - self._registered_total)
self._registered_total = self.total
return
if self.total >= _DL_MIN_FILE_BYTES:
if _DL_ACCUM_START == 0.0:
_DL_ACCUM_START = self.start_time
self._instance_n_at_start = _DL_ACCUM_BYTES
_DL_ACCUM_TOTAL += self.total
self._registered_total = self.total
self._is_registered = True
# ββ tqdm interface ββββββββββββββββββββββββββββββββββββββββββ
def update(self, n=1):
if _MODEL_DL_CANCEL.is_set():
raise _ModelDownloadCancelled()
global _DL_ACCUM_BYTES
self.n += n
self._ensure_registered()
if self._is_registered:
_DL_ACCUM_BYTES = self._instance_n_at_start + self.n
now = time.time()
if now - self.last_time >= 0.25 or (self.total and self.n >= self.total):
_dl_accum_push_state(self.desc)
self.last_time = now
def refresh(self):
"""Called by huggingface_hub after update(); push current state."""
self._ensure_registered()
if self._is_registered:
global _DL_ACCUM_BYTES
_DL_ACCUM_BYTES = self._instance_n_at_start + self.n
_dl_accum_push_state(self.desc)
self.last_time = time.time()
def set_description(self, desc, refresh=True):
"""huggingface_hub sets a new description mid-download."""
self.desc = desc or self.desc
if self._is_registered:
_dl_accum_push_state(self.desc)
def set_postfix(self, *args, **kwargs):
"""huggingface_hub may set postfix info β accept silently."""
pass
def set_postfix_str(self, s, refresh=True):
"""huggingface_hub's Xet progress reporting calls this."""
pass
@property
def format_dict(self):
"""Some huggingface_hub code reads bar.format_dict for rate info."""
return {"rate": 0}
def close(self):
self._ensure_registered()
if self._is_registered:
global _DL_ACCUM_BYTES
_DL_ACCUM_BYTES = self._instance_n_at_start + self.n
if self.total and self.n >= self.total:
global _DL_ACCUM_LAST_UPDATE
_DL_ACCUM_LAST_UPDATE = 0 # reset throttle
_dl_accum_push_state(self.desc)
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def _model_download_worker(model_id: str):
"""Background worker that pre-downloads a HuggingFace or GGUF model."""
_dl_accum_reset() # clear cumulative counters from any prior download
_MODEL_DL_CANCEL.clear() # allow a fresh cancel signal for this run
# Make sure xet is off for this download (see module-level note). The env var
# is read by huggingface_hub at import time, but hf may have been imported
# earlier in this process, so force the live flag on the already-loaded module.
os.environ["HF_HUB_DISABLE_XET"] = "1"
try:
import huggingface_hub
huggingface_hub.constants.HF_HUB_DISABLE_XET = True
except Exception:
pass
try:
from backend import model_registry as mr, models as mdl
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["status_line"] = "Starting downloadβ¦"
_MODEL_DL_STATE["label"] = model_id
_MODEL_DL_STATE["progress"] = 0
# If it's a quant-pinned GGUF or GGUF repo
if (
"#" in model_id
or str(model_id).lower().endswith(".gguf")
or model_id in mr.PRESET_GGUF_MODELS.values()
or model_id in mr.PRESET_GGUF_VLM_MODELS.values()
or model_id in mr.PRESET_GGUF_EMBED_MODELS.values()
):
from backend import llama_backend
from backend.paths import user_data_dir
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["status_line"] = "Downloading GGUF model filesβ¦"
llama_backend.resolve_or_download_gguf_model(model_id, tqdm_class=_ModelDownloadProgress)
default_dir = str(user_data_dir() / "gguf_models")
current_dir = llama_backend.LLAMA_CPP_MODEL_DIR or default_dir
if not llama_backend.LLAMA_CPP_MODEL_DIR:
llama_backend.set_model_dir(current_dir)
try:
from backend import whisper_cpp_backend
whisper_cpp_backend.set_whisper_model_dir(current_dir)
except Exception:
pass
try:
mr.rescan_gguf_models(current_dir)
except Exception:
pass
else:
import huggingface_hub as hf
hf.snapshot_download(
repo_id=model_id,
tqdm_class=_ModelDownloadProgress,
)
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["progress"] = 100
_MODEL_DL_STATE["status_line"] = "Download complete"
_MODEL_DL_STATE["done"] = True
except _ModelDownloadCancelled:
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["cancelled"] = True
_MODEL_DL_STATE["running"] = False
_MODEL_DL_STATE["done"] = False
_MODEL_DL_STATE["error"] = ""
_MODEL_DL_STATE["status_line"] = "Download cancelled"
except Exception as e:
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["error"] = str(e)
_MODEL_DL_STATE["status_line"] = f"β Error: {e}"
finally:
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["running"] = False
@app.post("/api/model-download")
async def start_model_download(payload: dict):
"""POST /api/model-download β trigger a background download of a
HuggingFace or GGUF model. The model_id is the HF repo id or quant pin (e.g.
'google/gemma-4-E2B-it-qat-q4_0-gguf'). Returns {ok, running}."""
model_id = (payload.get("model_id") or "").strip()
model_label = (payload.get("model_label") or model_id).strip()
if not model_id:
return JSONResponse({"ok": False, "message": "model_id is required"}, status_code=400)
with _MODEL_DL_LOCK:
if _MODEL_DL_STATE["running"]:
return JSONResponse({"ok": False, "message": "a model download is already running"}, status_code=409)
_MODEL_DL_STATE["running"] = True
_MODEL_DL_STATE["model_id"] = model_id
_MODEL_DL_STATE["model_label"] = model_label
_MODEL_DL_STATE["progress"] = 0
_MODEL_DL_STATE["dl_mb"] = ""
_MODEL_DL_STATE["total_mb"] = ""
_MODEL_DL_STATE["speed_mb"] = ""
_MODEL_DL_STATE["label"] = model_label
_MODEL_DL_STATE["status_line"] = "Starting downloadβ¦"
_MODEL_DL_STATE["done"] = False
_MODEL_DL_STATE["error"] = ""
_MODEL_DL_STATE["cancelled"] = False
_MODEL_DL_CANCEL.clear()
threading.Thread(target=_model_download_worker, args=(model_id,), daemon=True).start()
return {"ok": True, "running": True}
@app.post("/api/model-download-cancel")
async def cancel_model_download():
"""POST /api/model-download-cancel β signal an in-flight model download
to abort. The blocking hf_hub_download call raises inside its tqdm
callback, and the worker marks the state cancelled."""
_MODEL_DL_CANCEL.set()
with _MODEL_DL_LOCK:
_MODEL_DL_STATE["running"] = False
_MODEL_DL_STATE["cancelled"] = True
_MODEL_DL_STATE["status_line"] = "Download cancelled"
return {"ok": True}
@app.get("/api/model-download")
async def model_download_status():
"""GET /api/model-download β poll the model download progress."""
from backend import models as mdl
with _MODEL_DL_LOCK:
mid = _MODEL_DL_STATE["model_id"]
return {
"ok": True,
"running": _MODEL_DL_STATE["running"],
"model_id": mid,
"model_label": _MODEL_DL_STATE["model_label"],
"progress": _MODEL_DL_STATE["progress"],
"dl_mb": _MODEL_DL_STATE["dl_mb"],
"total_mb": _MODEL_DL_STATE["total_mb"],
"speed_mb": _MODEL_DL_STATE["speed_mb"],
"label": _MODEL_DL_STATE["label"],
"status_line": _MODEL_DL_STATE["status_line"],
"done": _MODEL_DL_STATE["done"],
"error": _MODEL_DL_STATE["error"],
"cancelled": _MODEL_DL_STATE.get("cancelled", False),
"cached": mdl.is_model_cached(mid) if mid else False,
}
@app.get("/api/model-check")
async def model_check(provider: str = "", model: str = "", type: str = "llm", lang: str = "kh"):
"""GET /api/model-check β returns whether the given model is cached, its resolved model_id,
and estimated download size."""
if not model:
return {"ok": True, "cached": True, "needs_download": False, "size_gb": 0, "model_id": "", "label": ""}
from backend import model_registry as mr, models as mdl
if type == "vlm":
provider_map = mr.VLM_PROVIDER_OPTIONS
elif type == "stt":
provider_map = mr.STT_PROVIDER_OPTIONS
elif type == "embed":
provider_map = mr.EMBED_PROVIDER_OPTIONS
else:
provider_map = mr.LLM_PROVIDER_OPTIONS
provider_id = provider_map.get(provider, provider)
if provider_id in (mr.PROVIDER_HF_API, mr.PROVIDER_LITELLM):
return {
"ok": True,
"cached": True,
"needs_download": False,
"size_gb": 0,
"model_id": model,
"label": model,
}
opts = mr.get_model_options_for_provider(provider_id, type or "llm")
model_id = opts.get(model, model)
if model_id == model and model in mr.PRESET_GGUF_MODELS:
model_id = mr.PRESET_GGUF_MODELS[model]
elif model_id == model and model in mr.PRESET_GGUF_VLM_MODELS:
model_id = mr.PRESET_GGUF_VLM_MODELS[model]
elif model_id == model and model in mr.PRESET_GGUF_EMBED_MODELS:
model_id = mr.PRESET_GGUF_EMBED_MODELS[model]
elif model_id == model and model in mr.PRESET_GGUF_STT_MODELS:
model_id = mr.PRESET_GGUF_STT_MODELS[model]
if provider_id == mr.PROVIDER_SERVER and os.path.isfile(model_id):
return {
"ok": True,
"cached": True,
"needs_download": False,
"size_gb": 0,
"model_id": model_id,
"label": model,
}
cached = mdl.is_model_cached(model_id)
size_gb = mdl.get_download_size_gb(model_id)
needs_download = not cached and bool(model_id and ("/" in model_id or str(model_id).lower().endswith(".gguf")))
return {
"ok": True,
"cached": cached,
"needs_download": needs_download,
"size_gb": size_gb,
"model_id": model_id,
"label": model,
}
@app.get("/api/disk-space")
def disk_space():
"""GET /api/disk-space β available disk space on the drive where user_data
lives. Returns {available_gb, total_gb, path} so the UI can warn when a
model download won't fit."""
from backend.paths import user_data_dir
try:
usage = shutil.disk_usage(str(user_data_dir()))
return {
"ok": True,
"available_gb": round(usage.free / (1024 ** 3), 1),
"total_gb": round(usage.total / (1024 ** 3), 1),
"path": str(user_data_dir()),
}
except Exception:
return {"ok": False, "available_gb": None, "total_gb": None, "path": ""}
@app.post("/api/model-delete")
async def delete_model(payload: dict):
"""POST /api/model-delete β delete downloaded model files from disk."""
model_id = (payload.get("model_id") or "").strip()
if not model_id:
return JSONResponse({"ok": False, "message": "model_id is required"}, status_code=400)
deleted_files = []
# 1. Direct file on disk
if os.path.isfile(model_id):
try:
os.remove(model_id)
deleted_files.append(model_id)
except Exception as e:
return JSONResponse({"ok": False, "message": f"Failed to delete file: {e}"}, status_code=500)
# 2. GGUF pinned file / repo
from backend import llama_backend
if "#" in model_id:
parts = model_id.split("#")
for part in parts[1:]:
if part.lower().endswith(".gguf"):
found = llama_backend.find_downloaded_model_file(part)
if found and os.path.isfile(found):
try:
os.remove(found)
deleted_files.append(found)
except Exception:
pass
repo_id = parts[0]
else:
repo_id = model_id
if repo_id in llama_backend.KNOWN_GGUF_REPOS:
info = llama_backend.KNOWN_GGUF_REPOS[repo_id]
for key in ("main", "mmproj"):
fn = info.get(key)
if fn:
found = llama_backend.find_downloaded_model_file(fn)
if found and os.path.isfile(found):
try:
os.remove(found)
deleted_files.append(found)
except Exception:
pass
# 3. Check user_data/gguf_models/repo--name
from backend.paths import user_data_dir
default_dir = user_data_dir() / "gguf_models" / repo_id.replace("/", "--")
if default_dir.exists() and default_dir.is_dir():
try:
shutil.rmtree(str(default_dir))
deleted_files.append(str(default_dir))
except Exception:
pass
# 4. Hugging Face cache
try:
import huggingface_hub as hf
cache_info = hf.scan_cache_dir()
for repo in cache_info.repos:
if repo.repo_id == repo_id or repo.repo_id == model_id:
hashes = [r.commit_hash for r in repo.revisions]
if hashes:
del_strategy = cache_info.delete_revisions(*hashes)
del_strategy.execute()
deleted_files.append(f"HF cache: {repo.repo_id}")
except Exception:
pass
return {"ok": True, "deleted": deleted_files, "model_id": model_id}
@app.post("/api/settings")
async def save_settings(payload: dict):
tab = _provider_tab(payload.get("tab", "general"))
provider_label = payload.get("provider_label")
model_label = payload.get("model_label")
try:
if provider_label:
if tab == "embed":
sentinel = mr.EMBED_PROVIDER_OPTIONS.get(provider_label)
elif tab == "stt":
sentinel = mr.STT_PROVIDER_OPTIONS.get(provider_label)
elif tab == "vlm":
sentinel = mr.VLM_PROVIDER_OPTIONS.get(provider_label)
else:
sentinel = _PROVIDER_OPTIONS.get(provider_label)
if sentinel:
mr.set_saved_provider(tab, sentinel)
if tab == "embed":
models.unload_embed_model_fn()
_reset_agents_for(tab)
if model_label:
# Persist the model label too β the header picker's reload
# contract (savedProvider + savedModel in /api/meta). The label
# is validated against live choices at read time; a stale label
# falls back to the provider's default model.
mr.set_saved_model(tab, model_label)
# For the KB (embed) tab, also write the "embed_model" key
# that get_default_embed_model() reads at indexing time β the
# header picker saves to model_embed via set_saved_model(),
# but the actual model load uses embed_model.
if tab == "embed":
mr.set_embed_model(model_label)
models.unload_embed_model_fn()
_reset_agents_for(tab)
return {"ok": True}
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
@app.post("/api/agent/reset")
async def reset_agent(payload: dict):
"""Drop the cached agent for a tab (mirrors Gradio's clear handlers, which
reset the agent so a "cleared" conversation starts with empty memory)."""
tab = _backend_tab(payload.get("tab", "general"))
_reset_agents_for(tab)
return {"ok": True}
@app.post("/api/upload")
async def upload_image(request: Request):
"""Accept a raw image body (the Vision tab's file picker POSTs the File
bytes directly), validate it really is an image, and stash it in a temp
file. Returns {path}; the WS chat handler feeds that path to
chat.chat_vision() (which accepts a path) and deletes it after the run."""
body = await request.body()
if not body:
return JSONResponse({"ok": False, "message": "empty upload"}, status_code=400)
if len(body) > 25 * 1024 * 1024:
return JSONResponse({"ok": False, "message": "image too large (25 MB max)"}, status_code=400)
import io
import tempfile
import uuid
from PIL import Image
try:
with Image.open(io.BytesIO(body)) as probe:
w, h = probe.size
fmt = (probe.format or "PNG").lower()
# verify() only validates structure β the size check stops
# decompression-bomb uploads before chat_vision decodes them.
probe.verify()
except Exception:
return JSONResponse({"ok": False, "message": "not a valid image"}, status_code=400)
if w * h > 50_000_000: # ~50 MP β far beyond any real photo
return JSONResponse({"ok": False, "message": "image dimensions too large"}, status_code=400)
fmt = "jpg" if fmt == "jpeg" else fmt
up_dir = Path(tempfile.gettempdir()) / "localailab_uploads"
up_dir.mkdir(parents=True, exist_ok=True)
path = up_dir / f"vis-{uuid.uuid4().hex}.{fmt}"
path.write_bytes(body)
return {"ok": True, "path": str(path)}
@app.get("/api/mmproj")
def mmproj(vlm: str = "", provider: str = ""):
"""Choices for the Vision tab's mmproj dropdown β mirrors the Gradio
vlm_dd.change handler: only GGUF VLMs under a llama.cpp provider expose
mmproj candidates, and the auto candidate (GGUF_VLM_MMPROJ_MAP) is
returned as the default selection. The payload's mmproj_label is resolved
back to a path inside chat.chat_vision()."""
sentinel = _VLM_PROVIDER_OPTIONS.get(provider) or mr.get_saved_provider("vlm")
mid = mr.resolve_model_id(vlm, provider=sentinel, model_type="vlm")
choices = []
saved = None
if "llama.cpp" in provider and str(mid).lower().endswith(".gguf"):
candidates = mr.get_mmproj_choices_for_vlm(mid)
choices = list(candidates.keys())
auto = mr.GGUF_VLM_MMPROJ_MAP.get(mid)
for lbl, path in candidates.items():
if path == auto:
saved = lbl
break
return {"visible": bool(choices), "choices": choices, "saved": saved}
def _copy_report_images(markdown: str, out_dir: Path) -> None:
"""Copy every chart image the report markdown references into `out_dir`
(the report's attached folder), as well as all generated PNG charts in
the active report folder and mr.DATA_OUTPUT_DIR. Best-effort: a missing/
invalid reference, a URL, or a data: URI is skipped β never raises."""
import shutil
refs = re.findall(r"!\[[^\]]*\]\(\s*([^)\s]+)\s*\)", markdown or "")
refs += re.findall(r"<img[^>]+src=[\"']([^\"']+)[\"']", markdown or "")
charts = Path(mr.DATA_OUTPUT_DIR)
for ref in refs:
try:
ref = (ref or "").strip().strip('"').strip("'")
if not ref or ref.startswith(("http://", "https://", "data:")):
continue
src = Path(ref)
if not src.is_absolute():
src = charts / src.name
if src.is_file():
dst = out_dir / src.name
if not dst.exists():
shutil.copy2(src, dst)
except OSError:
pass
# Ensure all generated PNG graphs from DATA_OUTPUT_DIR are in out_dir
try:
if charts.is_dir():
for png in charts.glob("*.png"):
try:
dst = out_dir / png.name
if not dst.exists():
shutil.copy2(png, dst)
except OSError:
pass
except OSError:
pass
# Also copy all charts from the active report directory if different
try:
from agents import data_analysis as da
active = da.get_active_report_dir()
if active and active.is_dir() and active.resolve() != out_dir.resolve():
for png in active.glob("*.png"):
try:
dst = out_dir / png.name
if not dst.exists():
shutil.copy2(png, dst)
except OSError:
pass
except Exception:
pass
@app.post("/api/reports")
async def save_report(payload: dict):
"""Save an answer as .docx into user_data/reports/<tab>/ (never auto β
the user clicks πΎ Save Report, same contract as the Gradio UI).
The DATA tab saves into a per-report ATTACHED FOLDER
(user_data/reports/data_analysis/<stem>/) containing the .docx AND the
chart images the report references β so the images live with the report
instead of only in the shared charts output dir. Every other tab keeps
the flat per-tab folder layout."""
tab = _backend_tab(payload.get("tab", "general"))
markdown = payload.get("markdown") or ""
filename = payload.get("filename") or ""
if not markdown.strip():
return {"ok": False, "message": "empty answer"}
import datetime
from backend.docx_export import markdown_text_to_docx
from backend.paths import user_data_dir
from backend.report_tools import _sanitize_report_filename # Gradio-free
folder = Path(mr.REPORT_DIRS.get(tab)) if mr.REPORT_DIRS.get(tab) else (
user_data_dir() / "reports" / tab
)
folder.mkdir(parents=True, exist_ok=True)
stem = _sanitize_report_filename(filename, ".docx") if filename else ""
if not stem:
stem = datetime.datetime.now().strftime("report-%Y-%m-%d-%H%M%S")
if tab == "data":
# Per-report attached folder: <tab_folder>/<stem>/ holding the .docx
# and the charts it references.
from agents import data_analysis as da
active_dir = da.get_active_report_dir()
# If no custom filename was provided and an active report folder exists
if not filename and active_dir and active_dir.is_dir() and active_dir.parent.resolve() == folder.resolve():
out_dir = active_dir
stem = out_dir.name
else:
out_dir = folder / stem
if not ((out_dir / f"{stem}.docx").exists()) and active_dir and active_dir.is_dir() and active_dir.name == stem and active_dir.parent.resolve() == folder.resolve():
out_dir = active_dir
else:
n = 2
while out_dir.exists() and (out_dir / f"{stem}.docx").exists():
out_dir = folder / f"{stem}-{n}"
n += 1
out_dir.mkdir(parents=True, exist_ok=True)
_copy_report_images(markdown, out_dir)
path = out_dir / f"{stem}.docx"
ok = bool(markdown_text_to_docx(
markdown, str(path),
image_search_dirs=[str(out_dir), mr.DATA_OUTPUT_DIR],
))
return {"ok": ok, "path": str(path), "folder": str(out_dir)}
else:
path = folder / f"{stem}.docx"
n = 2
while path.exists():
path = folder / f"{stem}-{n}.docx"
n += 1
ok = bool(markdown_text_to_docx(markdown, str(path)))
return {"ok": ok, "path": str(path), "folder": str(folder)}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Migrated tabs: STT / Data Analysis / Knowledge Base / Settings / About
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _save_uploads(files, prefix: str, with_names: bool = False) -> list:
"""Persist uploaded File objects to a per-purpose temp dir and return
their paths (string paths β knowledge_base.get_file_path handles str).
The temp file itself gets a UUID prefix so same-named uploads never
collide, but the ORIGINAL filename travels with it: with
``with_names=True`` each returned item is
``{"path": str, "name": original_filename}`` so the Knowledge Base can
index chunks under the user's real file name instead of the long
``<uuid>-<name>`` temp name."""
import tempfile
import uuid
up_dir = Path(tempfile.gettempdir()) / f"localailab_{prefix}"
up_dir.mkdir(parents=True, exist_ok=True)
paths = []
for f in files:
data = f.file.read()
if not data:
continue
name = Path(f.filename or "upload.bin").name
path = up_dir / f"{uuid.uuid4().hex}-{name}"
path.write_bytes(data)
item = str(path)
if with_names:
item = {"path": str(path), "name": name}
paths.append(item)
return paths
def _device_label() -> str:
try:
from backend import hardware
return (hardware.HardwareManager.get_system_status().get("current_device") or "cpu").upper()
except Exception:
return "CPU"
# ββ About βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _about_content(lang_key: str) -> str:
from ui import branding
try:
if lang_key == "kh":
base = branding.about_content_kh(_device_label(), _about_version())
else:
base = branding.about_content_en(_device_label(), _about_version())
except Exception:
base = ""
# Append the same venv/packages diagnostic as the Settings card so users
# can check package recognition without opening Settings. Single source
# of truth is `_env_status_text` β never a second copy of the check.
try:
env = _env_status_text(lang_key)
except Exception:
env = ""
if env:
heading = (
"### π§ͺ ααα·ααΆααΆααααααα·ααΈ & αααα
αα (Env & Packages)"
if lang_key == "kh"
else "### π§ͺ App Environment & Packages"
)
base = f"{base}\n\n---\n\n{heading}\n\n```text\n{env}\n```"
return base
def _about_version() -> str:
try:
from ui.branding import APP_VERSION
return APP_VERSION
except Exception:
return ""
@app.get("/api/about")
def about(lang: str = "kh"):
return {"ok": True, "content": _about_content(lang or "kh"), "version": _about_version()}
# ββ Feedback ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/feedback/diagnostics")
def feedback_diagnostics(lang: str = "kh"):
"""Return sanitized system diagnostics and recent log context for
feedback and error reporting."""
import platform
import sys
from backend import paths
from ui.branding import APP_VERSION
diag_lines = [
f"App: LocalAiLab v{APP_VERSION}",
f"OS: {platform.system()} {platform.release()} ({platform.machine()})",
f"Python: {sys.version.split()[0]}",
]
# Hardware / GPU detection
try:
from backend.hardware import detect_hardware, detect_cuda
hw = detect_hardware()
cuda = detect_cuda()
if hw:
summary = hw.get("summary") or hw.get("cpu") or ""
if summary:
diag_lines.append(f"Hardware: {summary}")
if hw.get("vram_gb"):
diag_lines.append(f"VRAM: {hw.get('vram_gb')} GB")
if cuda:
cuda_sum = cuda.get("summary") or cuda.get("driver") or ""
if cuda_sum:
diag_lines.append(f"CUDA: {cuda_sum}")
except Exception:
pass
# Active provider / models
try:
diag_lines.append(f"Saved Provider (General): {mr.get_saved_provider('general') or 'default'}")
diag_lines.append(f"Saved Model (General): {mr.get_saved_model('general') or 'default'}")
except Exception:
pass
# Recent log tail if available
recent_logs = ""
try:
log_file = paths.user_data_dir() / "logs" / "app.log"
if log_file.is_file():
content = log_file.read_text(encoding="utf-8", errors="ignore").strip().splitlines()
recent_logs = "\n".join(content[-30:])
except Exception:
pass
return {
"ok": True,
"diagnostics": "\n".join(diag_lines),
"recent_logs": recent_logs,
"email_target": "aidgcreator@gmail.com",
}
@app.post("/api/feedback")
async def submit_feedback(payload: dict):
"""Process feedback or error report, save a local copy to user_data/feedback/,
and return pre-built mailto and Gmail web URLs for 1-click emailing to
aidgcreator@gmail.com."""
import datetime
import urllib.parse
from backend.paths import user_data_dir
fb_type = str(payload.get("type") or "feedback").strip()
subject = str(payload.get("subject") or "").strip()
message = str(payload.get("message") or "").strip()
user_email = str(payload.get("email") or "").strip()
include_diag = bool(payload.get("include_diag", True))
diag_text = str(payload.get("diagnostics") or "").strip()
logs_text = str(payload.get("logs") or "").strip()
if not subject:
subject_title = f"LocalAiLab {fb_type.capitalize()} Report"
else:
subject_title = f"[LocalAiLab] [{fb_type.upper()}] {subject}"
body_parts = [
f"Feedback Type: {fb_type.upper()}",
f"Sender Email: {user_email or 'Not provided'}",
f"Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"",
"--- Description ---",
message or "(No message provided)",
]
if include_diag and (diag_text or logs_text):
body_parts.append("\n--- System Diagnostics ---")
if diag_text:
body_parts.append(diag_text)
if logs_text:
body_parts.append("\n--- Recent Logs ---")
body_parts.append(logs_text)
full_body = "\n".join(body_parts)
# Save local copy in user_data/feedback/
saved_path = ""
try:
fb_dir = user_data_dir() / "feedback"
fb_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
fb_file = fb_dir / f"feedback-{ts}.txt"
fb_file.write_text(full_body, encoding="utf-8-sig")
saved_path = str(fb_file)
except Exception:
pass
target_email = "aidgcreator@gmail.com"
mailto_url = f"mailto:{target_email}?subject={urllib.parse.quote(subject_title)}&body={urllib.parse.quote(full_body)}"
gmail_url = f"https://mail.google.com/mail/?view=cm&fs=1&to={target_email}&su={urllib.parse.quote(subject_title)}&body={urllib.parse.quote(full_body)}"
return {
"ok": True,
"target_email": target_email,
"subject": subject_title,
"body": full_body,
"mailto_url": mailto_url,
"gmail_url": gmail_url,
"saved_path": saved_path,
}
# ββ STT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/api/stt/transcribe")
async def stt_transcribe(request: Request):
"""Upload an audio file + STT model label + language β transcript text
(the whisper generator's emoji status lines are dropped; the LAST
non-status yield is the complete transcript β status lines like
"π΅ Loadingβ¦" / "ποΈ Transcribingβ¦" must never leak into the text, and
the old per-chunk cumulative yields must never duplicate it)."""
form = await request.form()
files = form.getlist("audio")
stt_label = str(form.get("stt_label") or "").strip()
language = str(form.get("language") or "auto").strip()
paths = _save_uploads(files, "stt")
if not paths:
return JSONResponse({"ok": False, "message": "no audio uploaded"}, status_code=400)
try:
from backend import models
mid = mr.resolve_stt_model_id(stt_label) or mr.DEFAULT_STT_MODEL or None
transcript = ""
for chunk in models.transcribe_audio_stream(paths[0], language=language or None, model_id=mid):
text = str(chunk or "").strip()
if text and not text.startswith(("β³", "π", "π‘", "π΅", "ποΈ")):
transcript = text
return {"ok": True, "transcript": transcript}
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
finally:
for p in paths:
try:
Path(p).unlink(missing_ok=True)
except OSError:
pass
@app.post("/api/stt/analyse")
async def stt_analyse(payload: dict):
"""Raw transcript β structured Markdown report via the STT-tab LLM
(chat.analyse_transcript_to_report β empty transcript is refused
without any LLM call)."""
import backend.chat as chat
transcript = payload.get("transcript") or ""
model_label = payload.get("model_label") or ""
lang_key = payload.get("lang", "kh")
if not (transcript or "").strip():
l = _lang(lang_key)
return {"ok": False, "message": l.get("err_stt_no_transcript", "no transcript"), "report": ""}
try:
status, report = "", ""
for s, r in chat.analyse_transcript_to_report(transcript, model_label, lang_key=lang_key):
if r:
report = r
if s and not report:
status = s
return {"ok": True, "report": report or status, "status": status}
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
@app.post("/api/stt/save-txt")
async def stt_save_txt(payload: dict):
"""Save the raw transcript as a UTF-8-BOM .txt under user_data/reports/stt/."""
from backend.report_tools import _transcript_txt_path # Gradio-free
path = _transcript_txt_path(payload.get("transcript") or "", payload.get("filename") or "")
return {"ok": bool(path), "path": path or ""}
@app.post("/api/stt/save-audio")
async def stt_save_audio(request: Request):
"""Save the current audio (recorded / uploaded / trimmed) into
user_data/outputs/ β the STT tab's "πΎ Save Audio" button. The optional
`filename` field becomes the stem when typed; otherwise the upload's OWN
filename is used (sanitized) β e.g. uploading `my voice.wav` saves as
`my voice.wav` instead of an anonymous timestamp. The extension is
preserved from the upload (the record/trim paths send WAV, the one
format every consumer reads). Sanitized + deduped exactly like report
saves; an unusable name falls back to the timestamped name. Never
auto-saved β only ever called on the button click."""
import datetime
form = await request.form()
files = form.getlist("audio")
filename = str(form.get("filename") or "").strip()
if not files or not files[0].filename:
return JSONResponse({"ok": False, "message": "no audio to save"}, status_code=400)
data = files[0].file.read()
if not data:
return JSONResponse({"ok": False, "message": "empty audio"}, status_code=400)
# 100 MB cap β generous for any voice recording, stops an unbounded
# body from being written straight to user_data/outputs (the image
# upload endpoint carries the same guard at 25 MB).
if len(data) > 100 * 1024 * 1024:
return JSONResponse({"ok": False, "message": "audio too large (100 MB max)"}, status_code=413)
try:
from backend.paths import user_data_dir
from backend.report_tools import _dedupe_report_path, _sanitize_report_filename # Gradio-free
upload_name = Path(files[0].filename or "").name
ext = Path(upload_name).suffix.lower()
if not ext or len(ext) > 5 or not ext[1:].isalnum():
ext = ".wav"
stem = _sanitize_report_filename(filename or upload_name, ext)
if not stem:
# datetime (not time.strftime): %f microseconds isn't supported
# by time.strftime on Windows and would raise.
ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
stem = f"audio-{ts}"
out_dir = user_data_dir() / "outputs"
out_dir.mkdir(parents=True, exist_ok=True)
out_path = _dedupe_report_path(out_dir, stem, ext)
out_path.write_bytes(data)
return {"ok": True, "path": str(out_path)}
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
@app.post("/api/stt/denoise")
async def stt_denoise(request: Request):
"""Reduce background noise in the uploaded audio and return the cleaned
WAV bytes β the STT tab's "π§ Reduce Noise" button swaps the denoised
file in as the current audio, so transcribe / save / trim all use it.
Returns binary audio/wav on success; a JSON error otherwise (the client
inspects Content-Type to tell them apart)."""
import tempfile
import uuid
form = await request.form()
files = form.getlist("audio")
if not files or not files[0].filename:
return JSONResponse({"ok": False, "message": "no audio to denoise"}, status_code=400)
data = files[0].file.read()
if not data:
return JSONResponse({"ok": False, "message": "empty audio"}, status_code=400)
# Same cap as the save-audio endpoint β a sane recording size, never an
# unbounded body read into memory.
if len(data) > 100 * 1024 * 1024:
return JSONResponse({"ok": False, "message": "audio too large (100 MB max)"}, status_code=413)
try:
from backend.audio_denoise import denoise_audio, resolve_strength
# The STT tab's preset picker sends 'gentle' / 'medium' / 'aggressive'
# (or a raw 0β1 number); resolve_strength never raises, so a garbage
# pick degrades to the default instead of a 500.
strength = resolve_strength(form.get("strength") or "")
tmp_in = Path(tempfile.gettempdir()) / f"lal_denoise_{uuid.uuid4().hex}.wav"
tmp_out = Path(tempfile.gettempdir()) / f"lal_denoise_{uuid.uuid4().hex}_clean.wav"
tmp_in.write_bytes(data)
try:
denoise_audio(str(tmp_in), str(tmp_out), strength=strength)
cleaned = tmp_out.read_bytes()
finally:
# Both temp files are cleaned up on every exit path β a denoiser
# failure mid-write must not leak lal_denoise_* in the temp dir.
tmp_in.unlink(missing_ok=True)
tmp_out.unlink(missing_ok=True)
if not cleaned:
return JSONResponse({"ok": False, "message": "denoise produced no audio"}, status_code=500)
return Response(content=cleaned, media_type="audio/wav")
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
@app.post("/api/stt/open-outputs")
async def stt_open_outputs():
"""Open user_data/outputs/ (where Save Audio lands) in the OS file
explorer β created on first use so Explorer never opens a missing path."""
from backend.paths import user_data_dir
from backend.report_tools import _open_folder_in_explorer # Gradio-free
out_dir = user_data_dir() / "outputs"
ok, message = _open_folder_in_explorer(str(out_dir))
return {"ok": ok, "message": message, "path": str(out_dir)}
@app.post("/api/stt/load")
async def stt_load(payload: dict):
from backend import models
mid = mr.resolve_stt_model_id(payload.get("model_label") or "") or mr.DEFAULT_STT_MODEL or ""
try:
models.force_reload_stt(mid)
l = _lang(payload.get("lang", "kh"))
return {"ok": True, "message": l["msg_loaded"].format(model=mid)}
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
@app.post("/api/stt/unload")
async def stt_unload(payload: dict):
from backend import models
return {"ok": True, "message": models.unload_stt_fn(payload.get("lang", "kh"))}
# ββ Data Analysis βββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/data/chart/{name}")
def data_chart(name: str):
"""Serve a chart PNG produced by data-analysis runs. Checks the active report
folder, DATA_OUTPUT_DIR, and data_analysis report subdirectories. Only
basenames are served (no traversal)."""
safe = Path(name or "").name
if not safe:
return JSONResponse({"ok": False, "message": "chart not found"}, status_code=404)
# 1. Check active report directory from current/latest data analysis run
try:
from agents import data_analysis as da
active_dir = da.get_active_report_dir()
if active_dir and (Path(active_dir) / safe).is_file():
return FileResponse(str(Path(active_dir) / safe), media_type="image/png")
except Exception:
pass
# 2. Check DATA_OUTPUT_DIR
path = Path(mr.DATA_OUTPUT_DIR) / safe
if path.is_file():
return FileResponse(str(path), media_type="image/png")
# 3. Check reports/data_analysis subdirectories (newest first)
try:
data_reports = Path(mr.REPORT_DIRS.get("data", ""))
if data_reports.is_dir():
for sub in sorted(data_reports.iterdir(), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True):
if sub.is_dir() and (sub / safe).is_file():
return FileResponse(str(sub / safe), media_type="image/png")
except Exception:
pass
return JSONResponse({"ok": False, "message": "chart not found"}, status_code=404)
@app.get("/api/data/output-dir")
def data_output_dir():
"""The FULL path of the folder where the Data Analysis agent saves its
charts (mr.DATA_OUTPUT_DIR) β so the UI can display it. Read-only, no
side effects (the folder may not exist until the first run)."""
return {
"ok": True,
"path": str(Path(mr.DATA_OUTPUT_DIR)),
"exists": Path(mr.DATA_OUTPUT_DIR).is_dir(),
}
@app.post("/api/data/open-outputs")
async def data_open_outputs():
"""Create (on first use) + open the Data Analysis charts folder in the
OS file explorer β mirrors the STT open-outputs endpoint."""
from backend.report_tools import _open_folder_in_explorer # Gradio-free
out_dir = Path(mr.DATA_OUTPUT_DIR)
out_dir.mkdir(parents=True, exist_ok=True)
ok, message = _open_folder_in_explorer(str(out_dir))
return {"ok": ok, "message": message, "path": str(out_dir)}
def _run_data_analysis(paths, question, model_label, history, use_memory, lang_key, max_steps, worker_max_steps, execution_timeout):
"""Run the EDA agent generator in a thread; return the FINAL yield's
values (history, real chart list, report β the report slot is always
None: the agent returns the report as its final answer, never a saved
file). Intermediate yields carry placeholder values β only yields
whose gallery is a real list are kept."""
from agents import data_analysis
final = (history, [], "")
try:
for h, gallery, report_file in data_analysis.run_data_analysis(
paths,
question,
model_label,
history or [],
use_memory=use_memory,
lang_key=lang_key,
max_steps=max_steps or None,
worker_max_steps=worker_max_steps or None,
execution_timeout=execution_timeout or None,
):
if isinstance(gallery, list):
final = (h, gallery, report_file)
except Exception as e: # pragma: no cover β defensive
final = (history, [], f"β {e}")
return final
@app.post("/api/data/upload")
async def data_upload(request: Request):
"""Accept CSV/XLSX files (the Data tab's upload chip) and stash them in
temp files. Returns {paths}; the WS chat handler feeds those paths to
chat.chat_data() and deletes them after the run β the same lifecycle as
the Vision tab's /api/upload image."""
form = await request.form()
files = form.getlist("files")
paths = _save_uploads(files, "data")
if not paths:
return JSONResponse({"ok": False, "message": "no data file uploaded"}, status_code=400)
return {"ok": True, "paths": paths}
@app.post("/api/data/analyze")
async def data_analyze(request: Request):
"""Upload CSV/XLSX files + question + analysis options β the EDA agent
runs (in a worker thread) and the final history, chart list and report
markdown are returned."""
import asyncio
form = await request.form()
files = form.getlist("files")
question = str(form.get("question") or "").strip()
model_label = str(form.get("model_label") or "").strip()
use_memory = str(form.get("use_memory") or "true").lower() not in ("0", "false", "no")
lang_key = str(form.get("lang") or "kh")
try:
max_steps = int(form.get("max_steps") or 0) or None
except ValueError:
max_steps = None
try:
worker_max_steps = int(form.get("worker_max_steps") or 0) or None
except ValueError:
worker_max_steps = None
try:
execution_timeout = int(form.get("execution_timeout") or 0) or None
except ValueError:
execution_timeout = None
paths = _save_uploads(files, "data")
if not paths:
return JSONResponse({"ok": False, "message": "no data file uploaded"}, status_code=400)
try:
history, gallery, report_file = await asyncio.to_thread(
_run_data_analysis, paths, question, model_label, [], use_memory, lang_key, max_steps, worker_max_steps, execution_timeout
)
finally:
# save_data_files() copied the uploads into the data-output dir during
# the run β the temp copies are now redundant (STT/KB clean up too).
for p in paths:
try:
Path(p).unlink(missing_ok=True)
except OSError:
pass
report_text = ""
if isinstance(report_file, str) and report_file and Path(report_file).is_file():
try:
report_text = Path(report_file).read_text(encoding="utf-8", errors="replace")
except Exception:
report_text = ""
charts = [Path(p).name for p in (gallery or []) if Path(str(p)).suffix.lower() == ".png"]
return {
"ok": True,
"history": history or [],
"charts": charts,
"report": report_text,
}
@app.post("/api/data/reset")
async def data_reset():
from agents import data_analysis
data_analysis.reset_agent()
data_analysis._last_data_context["key"] = None
return {"ok": True}
# ββ Knowledge Base ββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/api/kb/index")
async def kb_index(request: Request):
"""Upload files (+ theme/subtheme/visual retriever) and index them into
the ChromaDB knowledge base.
Streams live progress as Server-Sent Events (``text/event-stream``): each
``log`` event carries one of the app's OWN terminal status prints
(``[RAG]`` embedding load, ``[transformers]`` model-load warnings, β¦) so
the KB tab can render AND copy them as they happen, and the final ``done``
event carries the result message. Mirrors the chat WS log-streaming
pattern (ThreadStdoutTee) so the KB tab's "Copy All" can capture exactly
what the terminal showed β including the ColPali weight-report warnings that
previously only appeared in the console."""
import json as _json
from backend import knowledge_base as kb
from backend.stdio_hardening import ThreadStdoutTee
form = await request.form()
files = form.getlist("files")
# theme/subtheme may be a single value OR repeated form fields (the
# multi-select tag dropdowns) β collect them all.
theme = [str(v).strip() for v in form.getlist("theme") if str(v).strip()]
subtheme = [str(v).strip() for v in form.getlist("subtheme") if str(v).strip()]
lang_key = str(form.get("lang") or "kh").strip() or "kh"
visual_retriever = str(form.get("visual_retriever") or "").strip()
if not visual_retriever and mr.VISUAL_RETRIEVER_OPTIONS:
visual_retriever = next(iter(mr.VISUAL_RETRIEVER_OPTIONS))
embed_model_label = str(form.get("embed_model") or "").strip()
embed_provider_label = str(form.get("embed_provider") or "").strip()
if embed_provider_label:
sentinel = mr.EMBED_PROVIDER_OPTIONS.get(embed_provider_label)
if sentinel:
mr.set_saved_provider("embed", sentinel)
if embed_model_label:
mr.set_saved_model("embed", embed_model_label)
mr.set_embed_model(embed_model_label)
saved = _save_uploads(files, "kb", with_names=True)
paths = [it["path"] for it in saved]
source_names = {it["path"]: it["name"] for it in saved}
if not paths:
return JSONResponse({"ok": False, "message": "no files uploaded"}, status_code=400)
loop = asyncio.get_running_loop()
# Surfaced even when untagged: the ColPali UNEXPECTED/MISSING weight report
# and any other model-load warnings/errors the terminal prints.
_warn_re = re.compile(r"(UNEXPECTED|MISSING|Load Report|WARNING|ERROR|β|β οΈ)", re.IGNORECASE)
def _warn_predicate(line):
return bool(_warn_re.search(line))
q: "asyncio.Queue" = asyncio.Queue()
# The tee is created on the event-loop thread but must CAPTURE on the
# worker thread (where the blocking index actually prints) β attach() is
# therefore called inside _run, not here.
tee = ThreadStdoutTee(sys.stdout, warn_predicate=_warn_predicate)
sys.stdout = tee
def _run():
try:
tee.attach()
try:
message = kb.index_uploaded_files(
paths, visual_retriever, theme, subtheme,
lang_key=lang_key, source_names=source_names,
)
loop.call_soon_threadsafe(q.put_nowait, ("done", message or "Nothing indexed.", None))
except Exception as e: # surface the failure as a done event too
loop.call_soon_threadsafe(q.put_nowait, ("done", f"β {e}", str(e)))
finally:
for p in paths:
try:
Path(p).unlink(missing_ok=True)
except OSError:
pass
tee.detach()
except Exception:
loop.call_soon_threadsafe(q.put_nowait, ("done", "β Indexing crashed.", None))
async def event_gen():
worker = threading.Thread(target=_run, daemon=True)
worker.start()
try:
while worker.is_alive():
lines = tee.drain()
for ln in lines:
yield f"data: {_json.dumps({'type': 'log', 'line': ln}, ensure_ascii=False)}\n\n"
await asyncio.sleep(0.3)
# Flush any trailing (unfinished) line so the final warning isn't lost.
for ln in tee.drain(flush_partial=True):
yield f"data: {_json.dumps({'type': 'log', 'line': ln}, ensure_ascii=False)}\n\n"
finally:
tee.restore()
# Emit the terminal result line carried by the done event.
kind, msg, err = await q.get()
yield f"data: {_json.dumps({'type': 'done', 'message': msg, 'error': err}, ensure_ascii=False)}\n\n"
return StreamingResponse(
event_gen(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
@app.get("/api/kb/docs")
async def kb_docs(refresh: int = 0):
from backend import knowledge_base as kb
rows = await asyncio.to_thread(kb.get_doc_table, bool(refresh))
return {"ok": True, "rows": rows or []}
@app.post("/api/kb/delete")
async def kb_delete(payload: dict):
import asyncio
from backend import knowledge_base as kb
table, message = await asyncio.to_thread(
kb.delete_selected_sources,
payload.get("selected") or [], payload.get("rows") or [],
payload.get("lang", "kh"),
)
return {"ok": True, "message": message, "rows": table or []}
@app.post("/api/kb/clear")
async def kb_clear(payload: dict = None):
import asyncio
from backend import knowledge_base as kb
lang_key = (payload or {}).get("lang", "kh")
table, message = await asyncio.to_thread(kb.clear_index, lang_key)
return {"ok": True, "message": message, "rows": table or []}
@app.get("/api/kb/visual-thumb")
def kb_visual_thumb(doc_id: int = 0, page: int = 1):
"""A stored page image from the visual index as a PNG β read from the
persisted collection (base64 per embed id), NO retriever model load.
Served via <img> in the KB tab's Visual Index table, so the session
token must ride the `?token=` query param (an <img> can't send headers)."""
from backend import knowledge_base as kb
data = kb.get_visual_thumb_bytes(doc_id, page)
if not data:
return JSONResponse({"ok": False, "message": "visual page not found"}, status_code=404)
return Response(content=data, media_type="image/png")
@app.get("/api/kb/themes")
async def kb_themes(theme: str = ""):
import asyncio
from backend import knowledge_base as kb
themes, subthemes = await asyncio.to_thread(kb.get_existing_themes_and_subthemes, theme)
return {"ok": True, "themes": themes or [], "subthemes": subthemes or []}
@app.get("/api/kb/visual-docs")
async def kb_visual_docs():
"""List the visual index documents (source file, doc id, page/image
count) WITHOUT loading the retriever model β pure file read."""
import asyncio
from backend import knowledge_base as kb
rows = await asyncio.to_thread(kb.get_visual_index_table)
return {"ok": True, "rows": rows or []}
@app.post("/api/kb/visual-delete")
async def kb_visual_delete(payload: dict):
"""Delete selected rows from the visual index (file surgery β no model
reload needed). Returns the refreshed visual table + message."""
import asyncio
from backend import knowledge_base as kb
table, message = await asyncio.to_thread(
kb.delete_visual_docs,
payload.get("selected") or [], payload.get("rows") or [],
payload.get("lang", "kh"),
)
return {"ok": True, "message": message, "rows": table or []}
@app.post("/api/kb/visual-clear")
async def kb_visual_clear(payload: dict = None):
"""Delete the ENTIRE visual index."""
import asyncio
from backend import knowledge_base as kb
lang_key = (payload or {}).get("lang", "kh")
table, message = await asyncio.to_thread(kb.clear_visual_index, lang_key)
return {"ok": True, "message": message, "rows": table or []}
# ββ Settings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _llama_cpp_status_text(lang_key: str) -> str:
from backend import llama_backend
kh = lang_key == "kh"
if not llama_backend.LLAMA_CPP_AVAILABLE:
if getattr(llama_backend, "LLAMA_CPP_IMPORT_ERROR", ""):
return ("β Installed but Broken β GGUF won't load (ααα‘αΎααα½α
ααα»ααααααΌα
β GGUF ααΉααα·αααααΎαααΆα)" if kh
else "β Installed but Broken β GGUF won't load")
return "β Not Installed (αα·αααΆααααΆαααα‘αΎα)" if kh else "β Not Installed"
if llama_backend.LLAMA_CPP_GPU_AVAILABLE:
return "β
Installed (GPU CUDA Accelerated β ααΆαααα‘αΎαααΎ GPU)" if kh else "β
Installed (GPU CUDA Accelerated)"
return "β
Installed (CPU Mode β ααΆαααα‘αΎαααΎ CPU)" if kh else "β
Installed (CPU Mode)"
def _hw_status_text(lang_key: str) -> str:
"""HARDWARE detection block for the Settings tab β the physical machine
story only: device, GPU brand, driver CUDA version, the GPU list with
VRAM, and compute capability. No software-detection info here β the
llama.cpp engine state / runtime DLL / torch / index story lives in the
software block below."""
from backend import hardware
from backend.llama_health import _gpu_compute_capability
kh = lang_key == "kh"
info = hardware.HardwareManager.get_system_status()
device = (info.get("current_device") or "cpu").upper()
brand = (info.get("gpu_brand") or "none").upper()
cuda_ver = info.get("cuda_version") or "β"
cc = _gpu_compute_capability() or "β"
gpu_parts = []
for g in info.get("gpus") or []:
name = g.get("name") or "?"
try:
ram_gb = hardware.HardwareManager._adapter_ram_gb(g)
ram_text = f" Β· {ram_gb:.1f} GB" if ram_gb is not None else ""
except Exception:
ram_text = ""
gpu_parts.append(f"{name}{ram_text}")
gpu_line = " | ".join(gpu_parts) or ("ααααΆα" if kh else "none")
if kh:
return (
f"α§ααααα: {device} | GPU: {brand} | CUDA: {cuda_ver}\n"
f"GPU: {gpu_line}\n"
f"Compute Capability: {cc}"
)
return (
f"Device: {device} | GPU: {brand} | CUDA: {cuda_ver}\n"
f"GPU: {gpu_line}\n"
f"Compute Capability: {cc}"
)
def _llama_server_path_status_text(lang_key: str) -> str:
"""The llama-server binary PATH health line β 'the path has been set to
...' / 'not set yet', shown in the Software Detection block so the user
sees at a glance whether the llama-server backend is configured (and to
which exact path)."""
from backend import llama_backend
kh = lang_key == "kh"
path = (getattr(llama_backend, "LLAMA_SERVER_EXE_PATH", "") or "").strip()
if not path:
return (
"llama-server: β " + (
"αα·αααΆαααααααααααΌααα β ααααααααα»α Settings (βοΈ)"
if kh else "path not set β set it in Settings (βοΈ)"
)
)
if os.path.exists(path):
return (
"llama-server: β
" + (
f"ααααΌαααααΌαααΆαααααααα
: {path}"
if kh else f"path has been set to: {path}"
)
)
return (
"llama-server: β οΈ " + (
f"ααααΌαααΆαααααα ααα»ααααααα―αααΆααα·αααΎα: {path}"
if kh else f"path set but file not found: {path}"
)
)
def _cuda_status_text(lang_key: str) -> str:
"""SOFTWARE detection block for the Settings tab β the installed-runtime
story the hardware console above does NOT carry: the llama.cpp python
engine state, the llama-server binary path health, the installed CUDA
runtime DLL family, and the live torch CUDA state. The RECOMMENDATIONS
are dynamic β each appears ONLY while it is not already done: the
PyTorch index is hidden once CUDA torch works, the llama.cpp build
recommendation hides once the engine is installed as recommended, and
the install hint shows only when at least one recommendation is still
pending. Hardware facts (device / GPU brand / VRAM / compute capability)
live in the hardware console β never duplicated here."""
from backend import hardware
from backend import llama_backend
kh = lang_key == "kh"
info = hardware.HardwareManager.get_system_status()
runtime_major = hardware.HardwareManager.detect_installed_cuda_runtime_major()
runtime_dll = f"cublas64_{runtime_major}.dll" if runtime_major else "β"
torch_ok = bool(info.get("torch_cuda_available"))
index = info.get("recommended_index") or ""
recs = info.get("recommendations") or {}
ll = (recs.get("llama_cpp") or {}).get("choice", "cpu").upper()
lines = [
f"llama-cpp-python: {_llama_cpp_status_text(lang_key)}",
_llama_server_path_status_text(lang_key),
("CUDA Runtime DLL" if kh else "Installed CUDA Runtime DLL") + f": {runtime_dll}",
"PyTorch CUDA: " + ("β
ααΆα" if kh and torch_ok else "β
Yes" if torch_ok else "β αα" if kh else "β No"),
]
# Dynamic recommendations β each shows ONLY while it is not done yet.
recommends = []
# PyTorch GPU: recommended only when CUDA torch is NOT working.
if not torch_ok:
recommends.append(
("PyTorch Index αααααΆαααααΆα" if kh else "Recommended PyTorch Index") + f": {index}"
)
# llama.cpp build: recommended only while the engine is NOT installed in
# the recommended mode (CPU-only builds still recommend the GPU build on
# a CUDA machine; an absent engine always recommends).
llama_cpp_done = bool(
getattr(llama_backend, "LLAMA_CPP_AVAILABLE", False)
and (ll == "CPU" or getattr(llama_backend, "LLAMA_CPP_GPU_AVAILABLE", False))
)
if not llama_cpp_done:
recommends.append(
("ααΆαααααΆα llama.cpp" if kh else "Recommended llama.cpp") + f": {ll}"
)
# The install hint appears only while something is still pending.
if recommends:
lines.append("")
lines.extend(recommends)
lines.append("")
lines.append(
"ααα‘αΎα GPU ααααααααΈαααα»α Settings αααααΆααααΈααΎααααααα·ααΈα"
if kh else "Install GPU packages from Settings after launch."
)
return "\n".join(lines)
def _env_status_text(lang_key: str) -> str:
"""Python-environment block for the Settings tab β the 'does the app
recognize its packages?' diagnostic. Reports the runtime MODE (frozen
standalone bundle vs a .venv vs system Python), the interpreter path,
and a LIVE import check of every core package with its version.
A frozen (MSIX / PyInstaller standalone) build bundles the packages
INSIDE the app β no .venv exists or is needed; a venv-based install
(SETUP.ps1) shows the venv path instead. On a machine that 'does not
recognize any packages', this block shows exactly which imports fail.
"""
import importlib.metadata as _md
import importlib.util as _iu
import sys as _sys
kh = lang_key == "kh"
frozen = bool(getattr(_sys, "frozen", False))
venv = bool(getattr(_sys, "base_prefix", None) and _sys.base_prefix != _sys.prefix)
lines = []
if frozen:
lines.append(
"π¦ " + (
"αααααα·ααΈ Standalone (ααΆαααα
αα) β αααα
ααααΆααα’αααααα·ααααα»ααααααα·ααΈ αα·αααααΌαααΆα .venv αα"
if kh else
"Standalone (frozen bundle) β all packages are bundled inside the app; no .venv needed"
)
)
elif venv:
lines.append(
"π " + ("ααα·ααΆααΆααα·αααα·α (.venv)" if kh else "Virtual environment (.venv)")
)
else:
lines.append(
"π " + ("Python αααααααα (System)" if kh else "System Python")
)
lines.append(f"Python: {_sys.version.split()[0]} | {_sys.executable}")
# Core packages the app needs at runtime β each with a live import
# check + version, so a machine that 'does not recognize any packages'
# shows exactly which imports fail (and which are just on-demand).
core = [
("torch", "torch"),
("torchaudio", "torchaudio"),
("torchvision", "torchvision"),
("transformers", "transformers"),
("accelerate", "accelerate"),
("sentence_transformers", "sentence-transformers"),
("chromadb", "chromadb"),
("docx", "python-docx"),
("pandas", "pandas"),
("numpy", "numpy"),
("matplotlib", "matplotlib"),
("PIL", "Pillow"),
("soundfile", "soundfile"),
("librosa", "librosa"),
("smolagents", "smolagents"),
("requests", "requests"),
]
failed = []
for mod, dist in core:
try:
spec = _iu.find_spec(mod)
except Exception:
spec = None
if spec is None:
lines.append(f"β {mod}")
failed.append(mod)
continue
# Metadata (dist-info) is NOT shipped for every bundled package β
# PyInstaller only collects it for packages that query it at runtime
# (e.g. torch, chromadb). A missing version must NEVER flip a
# present-and-importable package to β: try the canonical dist name
# plus the PEP-503-normalized variants, and fall back to a blank
# version (still β
β the import check is what matters).
ver = ""
for name in {dist, dist.replace("-", "_"), dist.replace("_", "-")}:
try:
got = _md.version(name)
if got:
ver = got
break
except Exception:
continue
lines.append(f"β
{mod} {ver}".rstrip())
# llama-cpp-python is OPTIONAL β installed on demand from Settings, so
# 'missing' here is expected until the user installs it (never a red β).
try:
if _iu.find_spec("llama_cpp") is not None:
lines.append(f"β
llama_cpp {_md.version('llama-cpp-python') or ''}".rstrip())
else:
lines.append(
"βΉοΈ llama_cpp β " + (
"ααα‘αΎαααΆααααααΌαααΆαααΈ Settings (αααααΎα)"
if kh else "optional β install from Settings"
)
)
except Exception:
lines.append("βΉοΈ llama_cpp β " + ("αα·αα’αΆα
αα·αα·αααααΆα" if kh else "unavailable"))
# One-line summary when ANY core package import fails β the at-a-glance
# takeaway for a machine that 'does not recognize any packages', with a
# hint pointing at the reinstall path (the Settings download buttons /
# GPU PyTorch install, or the MSIX/venv reinstall). Kept in BOTH
# languages, following the inline-bilingual pattern of this block.
if failed:
names = ", ".join(failed)
if kh:
lines.append(
f"β οΈ αααα
ααααααα·αα’αΆα
αααα»αααΆα ({len(failed)}): {names} β "
"ααΌαααα‘αΎαα‘αΎααα·αααΆα Settings (βοΈ)"
)
else:
lines.append(
f"β οΈ {len(failed)} package(s) failed to import: {names} β "
"reinstall via Settings (βοΈ)"
)
return "\n".join(lines)
def _llama_timeout_seconds() -> int:
"""The saved llama-server timeout as SECONDS (the Settings number input
contract) β maps the persisted label back through LLAMA_SERVER_TIMEOUT_OPTIONS."""
try:
return mr.LLAMA_SERVER_TIMEOUT_OPTIONS.get(mr.get_saved_llm_server_timeout_label())\
or mr.DEFAULT_LLAMA_SERVER_TIMEOUT
except Exception: # pragma: no cover β defensive
return 300
@app.get("/api/settings")
async def settings_status(lang: str = "kh"):
from backend import component_downloader, llama_backend, whisper_cpp_backend
from backend.report_tools import _list_report_files # Gradio-free
lang_key = lang or "kh"
l = _lang(lang_key)
comp = component_downloader.get_component_statuses()
def _status(ready: bool) -> str:
return l["web_comp_ready"] if ready else l["web_comp_missing"]
comp_text = (
f"llama-server.exe: {_status(comp['llama_server'])}"
f" | whisper-server.exe: {_status(comp['whisper_server'])}"
f" | Poppler: {_status(comp['poppler'])}"
f" | Playwright Chromium: {_status(comp['playwright'])}"
)
return {
"ok": True,
"hw": _hw_status_text(lang_key),
# The venv/packages diagnostic β shown right under the hardware
# card: runtime mode (frozen standalone vs .venv), interpreter, and
# a live import check of every core package.
"env": _env_status_text(lang_key),
"components": comp_text,
"componentStatuses": comp,
"device": _device_label(),
"cuda": _cuda_status_text(lang_key),
"reportBaseDir": mr.REPORT_BASE_DIR,
"reportFiles": _list_report_files(),
"fields": {
"hf_token": mr.get_saved_hf_token(),
# NOTE: no "hf_model_id" field β the HF API model is chosen
# ONLY in each tab's header model picker (the curated
# hf_api_models.csv list); there is no Settings-level model id.
"hf_provider": mr.get_saved_hf_provider(),
"litellm_model_id": mr.get_saved_litellm_model_id(),
"litellm_api_key": mr.get_saved_litellm_api_key(),
"litellm_api_base": mr.get_saved_litellm_api_base(),
"llama_server_path": llama_backend.LLAMA_SERVER_EXE_PATH or "",
"llama_server_args": llama_backend.LLAMA_SERVER_EXTRA_ARGS or "",
# SECONDS, not the display label β the Settings tab renders this in
# a number input and POSTs it straight back to set_llm_server_timeout.
"llama_server_timeout": _llama_timeout_seconds(),
"whisper_server_path": whisper_cpp_backend.WHISPER_CPP_SERVER_EXE_PATH or "",
"whisper_server_args": whisper_cpp_backend.WHISPER_CPP_SERVER_EXTRA_ARGS or "",
"gguf_dir": llama_backend.LLAMA_CPP_MODEL_DIR or "",
"flash_attn_pytorch": mr.get_saved_flash_attn_pytorch(),
"flash_attn_llama": mr.get_saved_flash_attn_llama(),
"torch_compile": mr.get_saved_torch_compile(),
"torch_compile_mode": mr.get_saved_torch_compile_mode(),
"torch_bf16": mr.get_saved_torch_bf16(),
"llama_kv_cache_quant": mr.get_saved_llama_kv_cache_quant(),
"llama_mlock": mr.get_saved_llama_mlock(),
"llama_mmap": mr.get_saved_llama_mmap(),
"llama_threads": mr.get_saved_llama_threads(),
"llama_tensor_split": mr.get_saved_llama_tensor_split(),
"llama_draft_model": mr.get_saved_llama_draft_model(),
"llama_draft_max": mr.get_saved_llama_draft_max(),
"visual_retrieval": mr.get_rag_visual_retrieval(),
"clear_confirm_min": mr.get_saved_clear_confirm_min() or mr.CLEAR_CONFIRM_MIN_DEFAULT,
"denoise_strength": mr.get_saved_denoise_strength(),
"stt_lang": mr.get_saved_stt_lang(),
"stt_mic_device": mr.get_saved_stt_mic(),
},
# The llama-server per-request timeout presets (label + seconds) β
# the Settings tab's timeout dropdown (this GLOBAL setting lives
# only here; see test_llama_server_timeout_lives_in_settings_not_meta).
"llama_server_timeout_options": [
{"label": label, "seconds": seconds}
for label, seconds in mr.LLAMA_SERVER_TIMEOUT_OPTIONS.items()
],
# Per-tab context window (n_ctx) β same shared contract as /api/meta
# (see _ctx_window_payload).
**_ctx_window_payload(),
}
@app.post("/api/settings/save")
async def settings_save(payload: dict):
"""Persist one Settings field ({key, value}) β mirrors the Gradio save
handlers (set_* in model_registry / llama_backend / whisper_cpp_backend)."""
key = payload.get("key") or ""
value = payload.get("value")
try:
if key == "lang":
user_config.set_saved_lang(str(value or ""))
elif key == "hf_token":
mr.set_hf_token(str(value or ""))
# NOTE: no "hf_model_id" save branch β the HF API model is chosen
# per-tab in the header pickers; a stale save request is ignored so
# a custom Settings-level model id can never silently reappear.
elif key == "hf_provider":
mr.set_hf_provider(str(value or ""))
elif key == "litellm_model_id":
mr.set_litellm_model_id(str(value or ""))
elif key == "litellm_api_key":
mr.set_litellm_api_key(str(value or ""))
elif key == "litellm_api_base":
mr.set_litellm_api_base(str(value or ""))
elif key == "llama_server_path":
from backend import llama_backend
llama_backend.set_llama_server_exe_path(str(value or ""))
elif key == "llama_server_args":
from backend import llama_backend
llama_backend.set_llama_server_extra_args(str(value or ""))
elif key == "llama_server_timeout":
seconds = int(value or 0)
if seconds > 0:
mr.set_llm_server_timeout(seconds)
try:
import backend.models as models
if getattr(models, "_llm", None) is not None and hasattr(models._llm, "timeout"):
models._llm.timeout = seconds
except Exception:
pass
elif key == "whisper_server_path":
from backend import whisper_cpp_backend
whisper_cpp_backend.set_whisper_server_exe_path(str(value or ""))
elif key == "whisper_server_args":
from backend import whisper_cpp_backend
whisper_cpp_backend.set_whisper_server_extra_args(str(value or ""))
elif key == "gguf_dir":
from backend import llama_backend
llama_backend.set_model_dir(str(value or ""))
elif key == "flash_attn_pytorch":
mr.set_flash_attn_pytorch(bool(value))
elif key == "flash_attn_llama":
mr.set_flash_attn_llama(bool(value))
elif key == "torch_compile":
mr.set_torch_compile(bool(value))
elif key == "torch_compile_mode":
mr.set_torch_compile_mode(str(value or ""))
elif key == "torch_bf16":
mr.set_torch_bf16(bool(value))
elif key == "llama_kv_cache_quant":
mr.set_llama_kv_cache_quant(str(value or ""))
elif key == "llama_mlock":
mr.set_llama_mlock(bool(value))
elif key == "llama_mmap":
mr.set_llama_mmap(bool(value))
elif key == "llama_threads":
mr.set_llama_threads(value)
elif key == "llama_tensor_split":
mr.set_llama_tensor_split(str(value or ""))
elif key == "llama_draft_model":
mr.set_llama_draft_model(str(value or ""))
elif key == "llama_draft_max":
mr.set_llama_draft_max(value)
elif key == "stt_provider":
sentinel = mr.STT_PROVIDER_OPTIONS.get(str(value or ""))
if sentinel:
mr.set_saved_provider("stt", sentinel)
elif key == "stt_report_provider":
# The STT tab's transcriptβreport analysis LLM provider β its
# own slot (stt_report), separate from the transcription
# provider above. chat.py reads this to build the analyser.
sentinel = mr.LLM_PROVIDER_OPTIONS.get(str(value or ""))
if sentinel:
mr.set_saved_provider("stt_report", sentinel)
elif key == "stt_report_model":
mr.set_saved_model("stt_report", str(value or ""))
elif key == "embed_provider":
sentinel = mr.EMBED_PROVIDER_OPTIONS.get(str(value or ""))
if sentinel:
mr.set_saved_provider("embed", sentinel)
models.unload_embed_model_fn()
elif key == "ctx_window":
# Per-tab context window β the UI posts the dropdown LABEL (the
# label IS the value); map it back to the token count. Defensive:
# a raw int is accepted too, so a future UI posting numbers keeps
# working. Unknown labels/tabs are refused, never silently saved.
tab = _CTX_WINDOW_TABS.get(payload.get("tab") or "general")
# type() is int rather than isinstance() so a JSON `true` (bool) can
# never slip through as n_ctx=1.
n_ctx = value if type(value) is int else mr.CONTEXT_WINDOW_OPTIONS.get(str(value or ""))
if tab not in _CTX_WINDOW_TABS.values() or type(n_ctx) is not int or n_ctx <= 0:
return JSONResponse(
{"ok": False, "message": f"unknown context window: {value}"},
status_code=400,
)
mr.set_context_window(n_ctx, tab)
elif key in ("agent_max_steps", "searcher_max_steps"):
# Per-tab step budgets β the UI's "Max Steps" / "Search steps"
# controls. value: a positive int, or null to clear back to
# AUTO (model-scaled default). type() is int (not isinstance)
# so a JSON `true` (bool) can never persist as a budget of 1.
tab = _provider_tab(payload.get("tab") or "general")
slots = mr._AGENT_STEPS_KEYS if key == "agent_max_steps" else mr._SUB_AGENT_STEPS_KEYS
if tab not in slots:
return JSONResponse(
{"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
status_code=400,
)
if value is not None and type(value) is not int:
return JSONResponse(
{"ok": False, "message": f"invalid step budget: {value}"},
status_code=400,
)
if key == "agent_max_steps":
mr.set_agent_steps(tab, value)
else:
mr.set_sub_agent_steps(tab, value)
elif key == "execution_timeout":
# Per-tab agentic execution timeout (General's "Exec timeout"
# control). value: a positive int (seconds), or null to clear
# back to AUTO (factory default). Same guards as the step
# budgets β type() is int so a JSON `true` can never persist
# as a 1-second timeout.
tab = _provider_tab(payload.get("tab") or "general")
if tab not in mr._AGENT_EXEC_TIMEOUT_KEYS:
return JSONResponse(
{"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
status_code=400,
)
if value is not None and type(value) is not int:
return JSONResponse(
{"ok": False, "message": f"invalid execution timeout: {value}"},
status_code=400,
)
mr.set_execution_timeout(tab, value)
elif key == "run_timeout":
# Per-tab generation RUN timeout (the Generation Settings
# "Timeout" control β General / RAG / Vision, plus Deep
# Research's legacy `deep_research_timeout` key which lands in
# the same slot). value: a positive int (seconds), or null to
# clear back to no explicit deadline. Same guards as the step
# budgets β type() is int so a JSON `true` can never persist
# as a 1-second timeout.
tab = _provider_tab(payload.get("tab") or "general")
if tab not in mr._AGENT_RUN_TIMEOUT_KEYS:
return JSONResponse(
{"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
status_code=400,
)
if value is not None and type(value) is not int:
return JSONResponse(
{"ok": False, "message": f"invalid run timeout: {value}"},
status_code=400,
)
mr.set_agent_run_timeout(tab, value)
elif key == "visual_retrieval":
# The RAG tab's resource-intensive visual path toggle (the
# agentic `visual_retriever` page-image tool + the VLM grounding
# pass). Only the RAG tab exposes it; DEFAULT OFF (pure
# text-retrieval + text-LLM pipeline).
tab = _provider_tab(payload.get("tab") or "general")
if tab != "rag":
return JSONResponse(
{"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
status_code=400,
)
mr.set_rag_visual_retrieval(bool(value))
elif key == "clear_confirm_min":
# App-wide Alt+Delete clear-confirmation threshold (messages) β
# the Settings tab's "Confirm-clear threshold" field. value: a
# positive int, or null/'' to reset to the default (8). Same
# guards as the budgets β type() is int so a JSON `true` can
# never persist as a 1-message threshold.
if value is not None and type(value) is not int:
return JSONResponse(
{"ok": False, "message": f"invalid clear threshold: {value}"},
status_code=400,
)
if value is not None and value < 1:
return JSONResponse(
{"ok": False, "message": f"invalid clear threshold: {value}"},
status_code=400,
)
mr.set_clear_confirm_min(value)
elif key == "denoise_strength":
# STT tab's π§ Reduce Noise strength preset (gentle / medium /
# aggressive). value: the preset name, or null/'' to reset to the
# default ('' normalized to None like the other handlers).
# Unknown names are refused with a 400 β never silently persisted.
if value is not None and value != "":
from backend.audio_denoise import DENOISE_STRENGTH_PRESETS
if not isinstance(value, str) or value.strip().lower() not in DENOISE_STRENGTH_PRESETS:
return JSONResponse(
{"ok": False, "message": f"invalid denoise strength: {value}"},
status_code=400,
)
mr.set_denoise_strength(value if value != "" else None)
elif key == "stt_lang":
# STT tab's transcription language (auto / english / khmer /
# french / chinese / japanese). value: the language value, or
# null/'' to reset to the default ('auto'). Unknown values are
# refused with a 400 β never silently persisted.
if value is not None and value != "":
if not isinstance(value, str) or value.strip().lower() not in mr.STT_LANG_OPTIONS:
return JSONResponse(
{"ok": False, "message": f"invalid stt language: {value}"},
status_code=400,
)
mr.set_stt_lang(value if value != "" else None)
elif key == "stt_mic_device":
# STT tab's microphone device id β an opaque browser-assigned
# string (or '' for system default). No validation needed;
# the frontend silently clears stale ids on its own.
mr.set_stt_mic(value if isinstance(value, str) else "")
elif key == "deep_research_timeout":
# Deep Research's whole-run timeout (DrControls "Timeout"
# field). value: a positive int (seconds), or null to clear
# back to the agent's default. Same guards as the step budgets
# β type() is int so a JSON `true` can never persist as a
# 1-second run timeout.
tab = _provider_tab(payload.get("tab") or "general")
if tab not in mr._AGENT_RUN_TIMEOUT_KEYS:
return JSONResponse(
{"ok": False, "message": f"unknown tab: {payload.get('tab')}"},
status_code=400,
)
if value is not None and type(value) is not int:
return JSONResponse(
{"ok": False, "message": f"invalid deep research timeout: {value}"},
status_code=400,
)
mr.set_agent_run_timeout(tab, value)
else:
return JSONResponse({"ok": False, "message": f"unknown setting: {key}"}, status_code=400)
return {"ok": True}
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
@app.get("/api/settings/memory")
def settings_memory():
"""Live CPU + RAM + VRAM usage β polled by the Settings tab and the
sidebar Free-VRAM chip so users see how much of the machine is in use
next to the buttons (and how much freeing VRAM actually recovered)."""
from backend import hardware
try:
usage = hardware.HardwareManager.get_memory_usage()
except Exception: # pragma: no cover β defensive
usage = {"cpu": {}, "ram": {}, "vram": {}}
return {"ok": True, "usage": usage}
def _reset_app_state(lang_key: str = "kh") -> list:
"""Shared full-reset teardown used by Free-All-VRAM AND the header
Restart button: reset cached agents, unload every model, stop the
managed llama-server/whisper-server subprocesses, then run a full
multi-generation garbage collection + GPU cache reclaim.
Returns the list of bilingual status lines (unload summaries + server-
stop claims) the caller renders. Safe to call when nothing is loaded
(every step is idempotent/cheap).
The managed servers are stopped UNCONDITIONALLY, not only when a model
wrapper happens to be cached: a GGUF model can be resident in VRAM
inside llama-server.exe while every Python wrapper is already None (e.g.
an earlier Free All VRAM dropped the wrapper, then a late/stale chat
turn restarted the server; or a start succeeded but crashed before the
wrapper was cached; or an old build that released EmbeddingServerModel's
wrapper without stopping the shared server). The per-model unload fns
early-return "nothing loaded" in that state, so the server would survive
and keep the GPU occupied β exactly the "VRAM still ~50% after Free All
VRAM" report. Stopping is idempotent and cheap when nothing runs.
"""
from agents import data_analysis, deep_research_agent, general_agent, rag_agent
from backend import knowledge_base as kb
from backend import llama_backend, models, whisper_cpp_backend
from ui.i18n import LANGUAGES # dicts only β lightweight, no UI framework
msgs = []
# 1. Reset all cached agents FIRST so they release any references to
# the shared _llm, tools, and sub-agents.
for mod in (general_agent, rag_agent, data_analysis, deep_research_agent):
try:
mod.reset_agent()
except Exception:
pass
# 2. Unload all models and visual retrievers
msgs.append(models.unload_llm_fn(lang_key))
msgs.append(models.unload_vlm_fn(lang_key))
msgs.append(models.unload_stt_fn(lang_key))
msgs.append(models.unload_embed_model_fn(lang_key))
msgs.append(kb.unload_visual_retriever_fn(lang_key))
# 3. Unconditional server stop β see the docstring. stop_*_server() also
# reaps ORPHANED servers a previous app instance left behind (same exe /
# model-dir signature β see local_server.kill_stray_app_servers) and
# reports how many processes they actually stopped, so the summary only
# claims a stop when one really happened.
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
stopped = llama_backend.stop_llama_server()
if stopped:
msgs.append(l["msg_server_stopped"].format(server="llama-server"))
# The dedicated EMBEDDING llama-server is a separate slot β stopped
# here too (idempotent when idle), never by stop_llama_server().
stopped = llama_backend.stop_embed_server()
if stopped:
msgs.append(l["msg_server_stopped"].format(server="llama-server-embed"))
stopped = whisper_cpp_backend.stop_whisper_server()
if stopped:
msgs.append(l["msg_server_stopped"].format(server="whisper-server"))
# 4. Reset agents again defensively
for mod in (general_agent, rag_agent, data_analysis, deep_research_agent):
try:
mod.reset_agent()
except Exception:
pass
# 5. Full multi-generation garbage collection & GPU cache reclaim
import gc
gc.collect()
gc.collect()
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
elif hasattr(torch, "xpu") and torch.xpu.is_available():
torch.xpu.empty_cache()
torch.xpu.synchronize()
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
torch.mps.empty_cache()
except Exception:
pass
return msgs
@app.post("/api/settings/free-vram")
async def settings_free_vram(payload: dict):
"""Unload every loaded model + drop cached agents β the web port of the
Gradio do_free_vram handler."""
try:
msgs = _reset_app_state(str(payload.get("lang", "kh")))
except Exception as e: # pragma: no cover β defensive
return JSONResponse({"ok": False, "message": str(e)}, status_code=500)
return {"ok": True, "notice": "\n".join(str(m) for m in msgs if m)}
@app.post("/api/restart")
async def api_restart(payload: dict):
"""Full in-process app restart β the header β» Restart button (after π
Refresh). Unlike the refresh button (which only re-boots the SPA and
re-fetches /api/meta), this ALSO fully resets the backend state: cached
agents, every loaded model (VRAM), and the managed llama-server /
whisper-server subprocesses β then rebuilds the model registry from disk
(re-scanning the saved GGUF folder) so newly installed / downloaded
components and models are picked up, exactly like a cold app start.
The FastAPI server runs IN the same process as the launcher (dev
`_launch_web.py`, webview `run_webview.py`, frozen MSIX exe), so a hard
process kill + relaunch would risk a dead app if the respawn failed.
`_reset_app_state()` gives the same observable outcome β the SPA re-boot
re-fetches everything fresh β with zero death risk."""
lang_key = str(payload.get("lang", "kh"))
l = _lang(lang_key)
try:
msgs = _reset_app_state(lang_key)
# Rebuild the model registry from disk (GGUF folder + registered
# presets) so newly-installed components / models are discovered.
from backend import llama_backend
from backend import model_registry as mr
mr.rescan_gguf_models(llama_backend.LLAMA_CPP_MODEL_DIR or "", lang_key)
except Exception as e: # pragma: no cover β defensive
return JSONResponse(
{"ok": False, "message": l["err_restart_app"].format(error=str(e))},
status_code=500,
)
return {
"ok": True,
"message": l["msg_restart_app"],
"notice": "\n".join(str(m) for m in msgs if m),
}
@app.post("/api/settings/clear-reports")
async def settings_clear_reports(payload: dict):
from backend.report_tools import _clear_old_reports # Gradio-free
deleted, days = _clear_old_reports(payload.get("days"))
return {"ok": True, "deleted": deleted, "days": days}
@app.post("/api/settings/open-reports")
async def settings_open_reports(payload: dict):
from backend.report_tools import open_reports_folder_for # Gradio-free
# A per-tab "Open Reports Folder" button sends its tab key (stt / gen /
# rag / dr / vis / data) and opens THAT tab's own folder; or passes an
# exact folder path if a report was recently saved. No/unknown
# tab falls back to the reports base dir (Settings / About / KB).
tab = str(payload.get("tab") or "").strip() or None
target_path = str(payload.get("path") or "").strip() or None
ok, message, path = open_reports_folder_for(tab_key=tab, specific_path=target_path)
return {"ok": ok, "message": message, "path": path}
@app.post("/api/settings/refresh-reports")
async def settings_refresh_reports():
from backend.report_tools import _list_report_files # Gradio-free
return {"ok": True, "files": _list_report_files()}
@app.post("/api/settings/delete-report")
async def settings_delete_report(payload: dict):
from backend.report_tools import _delete_report_file, _list_report_files # Gradio-free
ok, message = _delete_report_file(payload.get("rel") or "")
return {"ok": ok, "message": message, "files": _list_report_files()}
# Background component downloads / installs β one job at a time; the frontend
# polls GET /api/settings/download for the streaming log tail. The lock makes
# the check-and-start atomic so two near-simultaneous POSTs can't spawn two
# workers (the TOCTOU the bare flag allowed).
_DL_STATE = {"running": False, "component": "", "lines": [], "progress": None, "label": ""}
_DL_LOCK = threading.Lock()
# Regex to extract "(42%)" from download progress lines.
_RE_DL_PCT = re.compile(r"\((\d{1,3})%\)")
_RE_DL_MB = re.compile(r"([\d.]+)\s*/\s*([\d.]+)\s*MB")
_RE_DL_LABEL = re.compile(r"Downloading\s+(.+?)\.\.\.")
def _track_dl_progress(line: str) -> None:
"""Parse a download progress line and update _DL_STATE progress/label."""
m_pct = _RE_DL_PCT.search(line)
if m_pct:
_DL_STATE["progress"] = int(m_pct.group(1))
m_label = _RE_DL_LABEL.search(line)
if m_label:
_DL_STATE["label"] = m_label.group(1).strip()
# Track downloaded/total MB for the progress bar subtitle.
m_mb = _RE_DL_MB.search(line)
if m_mb:
_DL_STATE["dl_mb"] = m_mb.group(1)
_DL_STATE["total_mb"] = m_mb.group(2)
def _download_worker(component: str, choice: str | None = None):
try:
if component in ("llama_cpp", "llm_cpp_install"):
from backend import hardware
gen = hardware.HardwareManager.install_llama_cpp_python_gen(choice=choice)
for line in gen:
sline = str(line)
_DL_STATE["lines"].append(sline)
_track_dl_progress(sline)
if len(_DL_STATE["lines"]) > 800:
_DL_STATE["lines"] = _DL_STATE["lines"][-800:]
elif component == "fix_env":
from backend import hardware
for msg, dev, log in hardware.HardwareManager.fix_environment_gen(choice=choice):
sline = str(log or msg)
_DL_STATE["lines"].append(sline)
_track_dl_progress(sline)
if len(_DL_STATE["lines"]) > 800:
_DL_STATE["lines"] = _DL_STATE["lines"][-800:]
else:
from backend import component_downloader
for line in component_downloader.download_component_gen(component, choice=choice):
sline = str(line)
_DL_STATE["lines"].append(sline)
_track_dl_progress(sline)
if len(_DL_STATE["lines"]) > 800:
_DL_STATE["lines"] = _DL_STATE["lines"][-800:]
except Exception as e: # pragma: no cover β defensive
_DL_STATE["lines"].append(f"β {e}")
finally:
_DL_STATE["running"] = False
@app.post("/api/settings/download")
async def settings_download(payload: dict):
component = payload.get("component") or ""
if component not in ("llama_server", "whisper_server", "poppler", "playwright", "llama_cpp", "fix_env"):
return JSONResponse({"ok": False, "message": f"unknown component: {component}"}, status_code=400)
with _DL_LOCK:
if _DL_STATE["running"]:
return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
_DL_STATE["running"] = True
_DL_STATE["component"] = component
_DL_STATE["lines"] = []
_DL_STATE["progress"] = None
_DL_STATE["label"] = ""
_DL_STATE.pop("dl_mb", None)
_DL_STATE.pop("total_mb", None)
threading.Thread(target=_download_worker, args=(component,), daemon=True).start()
return {"ok": True, "running": True}
@app.get("/api/settings/download")
async def settings_download_status():
from backend import component_downloader
return {
"ok": True,
"running": _DL_STATE["running"],
"component": _DL_STATE["component"],
"log": "\n".join(_DL_STATE["lines"][-200:]),
"progress": _DL_STATE.get("progress"),
"label": _DL_STATE.get("label", ""),
"dl_mb": _DL_STATE.get("dl_mb"),
"total_mb": _DL_STATE.get("total_mb"),
"statuses": component_downloader.get_component_statuses(),
}
@app.get("/api/settings/llm-cpp-info")
async def settings_llm_cpp_info():
from backend import hardware
return {"ok": True, **hardware.HardwareManager.get_llama_cpp_install_plan()}
@app.post("/api/settings/llm-cpp-install")
async def settings_llm_cpp_install(payload: dict):
choice = (payload.get("choice") or "auto").lower()
if choice not in ("auto", "cpu", "cuda", "vulkan"):
return JSONResponse(
{"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
)
with _DL_LOCK:
if _DL_STATE["running"]:
return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
_DL_STATE["running"] = True
_DL_STATE["component"] = "llm_cpp_install"
_DL_STATE["lines"] = []
_DL_STATE["progress"] = None
_DL_STATE["label"] = ""
_DL_STATE.pop("dl_mb", None)
_DL_STATE.pop("total_mb", None)
threading.Thread(target=_download_worker, args=("llm_cpp_install", choice), daemon=True).start()
return {"ok": True, "running": True}
@app.get("/api/settings/llama-server-info")
async def settings_llama_server_info():
"""GET /api/settings/llama-server-info β the llama-server download
popup's data source. Mirrors the llama-cpp-python detection report: the
detected hardware facts plus every build that CAN run on this PC
(auto / cpu / cuda12 / cuda13), each with a bilingual reason key."""
from backend import component_downloader
return {"ok": True, **component_downloader.get_llama_server_download_plan()}
@app.post("/api/settings/llama-server-install")
async def settings_llama_server_install(payload: dict):
"""POST /api/settings/llama-server-install {choice} β download the
user-chosen llama-server build (auto / cpu / cuda12 / cuda13) in the
SAME shared download thread as /api/settings/download. A garbage choice
is refused (400) before any worker spawns."""
choice = (payload.get("choice") or "auto").lower()
if choice not in ("auto", "cpu", "cuda12", "cuda13"):
return JSONResponse(
{"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
)
with _DL_LOCK:
if _DL_STATE["running"]:
return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
_DL_STATE["running"] = True
_DL_STATE["component"] = "llama_server_install"
_DL_STATE["lines"] = []
_DL_STATE["progress"] = None
_DL_STATE["label"] = ""
_DL_STATE.pop("dl_mb", None)
_DL_STATE.pop("total_mb", None)
threading.Thread(target=_download_worker, args=("llama_server", choice), daemon=True).start()
return {"ok": True, "running": True}
@app.get("/api/settings/whisper-server-info")
async def settings_whisper_server_info():
"""GET /api/settings/whisper-server-info β the whisper-server download
popup's data source. Mirrors the llama-server / llama-cpp-python
detection reports: the detected hardware facts plus every build that CAN
run on this PC (auto / cpu / cuda11 / cuda12), each with a bilingual
reason key."""
from backend import component_downloader
return {"ok": True, **component_downloader.get_whisper_server_download_plan()}
@app.post("/api/settings/whisper-server-install")
async def settings_whisper_server_install(payload: dict):
"""POST /api/settings/whisper-server-install {choice} β download the
user-chosen whisper-server build (auto / cpu / cuda11 / cuda12) in the
SAME shared download thread as /api/settings/download. A garbage choice
is refused (400) before any worker spawns."""
choice = (payload.get("choice") or "auto").lower()
if choice not in ("auto", "cpu", "cuda11", "cuda12"):
return JSONResponse(
{"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
)
with _DL_LOCK:
if _DL_STATE["running"]:
return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
_DL_STATE["running"] = True
_DL_STATE["component"] = "whisper_server_install"
_DL_STATE["lines"] = []
_DL_STATE["progress"] = None
_DL_STATE["label"] = ""
_DL_STATE.pop("dl_mb", None)
_DL_STATE.pop("total_mb", None)
threading.Thread(target=_download_worker, args=("whisper_server", choice), daemon=True).start()
return {"ok": True, "running": True}
@app.get("/api/settings/pytorch-info")
async def settings_pytorch_info():
"""GET /api/settings/pytorch-info β the PyTorch install popup's data
source. Mirrors the llama-server / whisper-server / llama-cpp-python
detection reports: the detected hardware facts plus every build that CAN
run on this PC (auto / cpu / cuda / xpu / rocm), each with a bilingual
reason key."""
from backend import hardware
return {"ok": True, **hardware.HardwareManager.get_pytorch_install_plan()}
@app.post("/api/settings/pytorch-install")
async def settings_pytorch_install(payload: dict):
"""POST /api/settings/pytorch-install {choice} β install the user-chosen
PyTorch build (auto / cpu / cuda / xpu / rocm) in the SAME shared
download thread as /api/settings/download. A garbage choice is refused
(400) before any worker spawns."""
choice = (payload.get("choice") or "auto").lower()
if choice not in ("auto", "cpu", "cuda", "xpu", "rocm"):
return JSONResponse(
{"ok": False, "message": f"unknown choice: {choice}"}, status_code=400
)
with _DL_LOCK:
if _DL_STATE["running"]:
return JSONResponse({"ok": False, "message": "a download is already running"}, status_code=409)
_DL_STATE["running"] = True
_DL_STATE["component"] = "fix_env"
_DL_STATE["lines"] = []
_DL_STATE["progress"] = None
_DL_STATE["label"] = ""
_DL_STATE.pop("dl_mb", None)
_DL_STATE.pop("total_mb", None)
threading.Thread(target=_download_worker, args=("fix_env", choice), daemon=True).start()
return {"ok": True, "running": True}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Chat WebSocket
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _clean_unicode_surrogates(obj):
"""Recursively sanitize invalid Unicode surrogate code points (U+D800 - U+DFFF)
from strings, dicts, lists, and tuples so that JSON serialization and WebSocket
UTF-8 transmission can never raise UnicodeEncodeError."""
if isinstance(obj, str):
try:
return obj.encode("utf-8", errors="replace").decode("utf-8")
except Exception:
return "".join(c for c in obj if not (0xD800 <= ord(c) <= 0xDFFF))
elif isinstance(obj, dict):
return {_clean_unicode_surrogates(k): _clean_unicode_surrogates(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [_clean_unicode_surrogates(x) for x in obj]
elif isinstance(obj, tuple):
return tuple(_clean_unicode_surrogates(x) for x in obj)
return obj
async def _send_ws_json(ws: WebSocket, payload: dict) -> None:
"""Send a JSON payload over WebSocket with guaranteed surrogate-safe UTF-8
encoding. Starlette's ws.send_json leaves lone surrogates in the text string,
causing uvicorn's .encode('utf-8') to fail with UnicodeEncodeError.
This helper cleans all surrogates and uses ws.send_text."""
import json
clean_payload = _clean_unicode_surrogates(payload)
try:
text = json.dumps(clean_payload, ensure_ascii=False)
safe_text = text.encode("utf-8", errors="replace").decode("utf-8")
await ws.send_text(safe_text)
except Exception:
safe_ascii = json.dumps(clean_payload, ensure_ascii=True)
await ws.send_text(safe_ascii)
@app.websocket("/ws/chat")
async def chat_ws(ws: WebSocket):
token = ws.query_params.get("token") or ws.headers.get("x-session-token")
if not token or token != _SESSION_TOKEN:
await ws.close(code=1008)
return
await ws.accept()
try:
payload = await ws.receive_json()
except Exception:
await ws.close()
return
if payload.get("type") != "chat":
await ws.close()
return
tab = payload.get("tab", "general")
message = payload.get("message", "")
history = payload.get("history") or []
model_label = payload.get("model_label") or ""
lang_key = payload.get("lang", "kh")
try:
if tab == "general":
await _stream_general(ws, payload, message, history, model_label, lang_key)
elif tab == "rag":
await _stream_rag(ws, payload, message, history, model_label, lang_key)
elif tab == "deep_research":
await _stream_deep_research(ws, payload, message, history, model_label, lang_key)
elif tab == "vision":
await _stream_vision(ws, payload, message, history, model_label, lang_key)
elif tab == "data":
await _stream_data(ws, payload, message, history, model_label, lang_key)
else:
await _send_ws_json(
ws, {"type": "error", "message": f"no chat stream for tab '{tab}'"}
)
except WebSocketDisconnect:
pass
except Exception:
try:
await _send_ws_json(ws, {"type": "error", "message": traceback.format_exc()})
except Exception:
pass
finally:
try:
await ws.close()
except Exception:
pass
async def _run_stream(ws, build_gen, timeout=None, lang_key: str = "kh"):
"""Run a chat generator in a daemon thread and stream its (history, export)
yields to the client as JSON events (update β final, or error). Shared by
the general, RAG, Deep Research and Vision WS handlers.
The generator thread's stdout is teed (ThreadStdoutTee): the app's own
`[Tag]`-prefixed status prints β llama-server launch/ready, model load,
agent build, β¦ β are drained between yields and streamed to the client
as `log` events BEFORE the corresponding update/final event, so the chat
answer shows what the terminal shows. All output still reaches the real
stdout too.
While a run is active the live-streaming bus is also owned by this
stream: the model wrappers push the incremental text they generate there
(see live_stream.py), and the SAME 0.5s live timer forwards it to the
client as `live` events ({"type": "live", "reset": bool, "text": str})
so the answer bubble grows from the model's ACTUAL output in real time.
`timeout` (optional seconds): the per-tab generation RUN timeout β a
whole-run wall-clock deadline. When a run exceeds it, the client gets a
"timeout" event instead (the generator is abandoned mid-run; the daemon
thread then exits and any finally-blocks β e.g. the Vision image
deletion β still run through the generator's close()). None = no
deadline, the run finishes naturally."""
import copy
queue: asyncio.Queue = asyncio.Queue()
loop = asyncio.get_running_loop()
deadline = (time.monotonic() + timeout) if (timeout and timeout > 0) else None
from backend.stdio_hardening import ThreadStdoutTee
def run():
# Capture the app's own `[Tag]`-prefixed status prints (llama-server
# launch, model load, agent build, β¦) from THIS thread and stream
# them to the UI as `log` events β the terminal output shown inside
# the chat answer. All output still reaches the real stdout too.
from backend.live_stream import get_bus
bus = get_bus()
bus.begin_run() # enable the model wrappers' live token streaming
tee = ThreadStdoutTee(sys.stdout)
sys.stdout = tee
tee.attach()
# LIVE draining: agent construction + model load block the generator
# for a long time with NO yields (the tee is otherwise drained only
# between yields), so the construction sequence would only appear in
# one lump together with the first step β and stay on screen the
# whole run. A timer polls the tee AND the live-streaming bus and
# streams them in real time: `log` events carry [Tag] status prints,
# `live` events carry the raw generated text tokens (the model's
# ACTUAL output growing in the answer bubble).
stop_drainer = threading.Event()
def _live_drain():
# 0.2 s polling: fast enough that streamed tokens appear fluid in
# the answer bubble (a 0.5 s drain felt stuttery β half-second
# text lumps), cheap enough that a long idle run costs nothing.
while not stop_drainer.wait(0.2):
lines = tee.drain()
if lines:
loop.call_soon_threadsafe(
queue.put_nowait, ("log", None, None, lines)
)
reset, live_text = bus.drain()
if live_text or reset:
loop.call_soon_threadsafe(
queue.put_nowait,
("live", reset, live_text, ""),
)
drainer = threading.Thread(target=_live_drain, daemon=True)
drainer.start()
try:
gen = build_gen()
last = None
while True:
if deadline is not None and time.monotonic() > deadline:
try:
gen.close()
except Exception:
pass
loop.call_soon_threadsafe(
queue.put_nowait,
("timeout", None, None, tee.drain(flush_partial=True)),
)
return
try:
h, ex = next(gen)
except StopIteration:
break
last = (h, ex)
# Deep-copy the snapshot: the generator thread keeps mutating
# `history` in place while the event loop serializes it.
loop.call_soon_threadsafe(
queue.put_nowait, ("update", copy.deepcopy(h), None, tee.drain())
)
if last is not None:
loop.call_soon_threadsafe(
queue.put_nowait,
("final", copy.deepcopy(last[0]), last[1] or "",
tee.drain(flush_partial=True)),
)
except Exception:
loop.call_soon_threadsafe(
queue.put_nowait,
("error", None, traceback.format_exc(), tee.drain(flush_partial=True)),
)
finally:
stop_drainer.set()
tee.restore()
bus.end_run()
threading.Thread(target=run, daemon=True).start()
while True:
kind, h, ex, lines = await queue.get()
if kind == "live":
# h = reset flag (bool), ex = accumulated live text.
if ex or h:
await _send_ws_json(ws, {"type": "live", "reset": bool(h), "text": ex or ""})
continue
if lines:
await _send_ws_json(ws, {"type": "log", "lines": lines})
if kind == "update":
await _send_ws_json(ws, {"type": "update", "history": h})
elif kind == "final":
await _send_ws_json(ws, {"type": "final", "history": h, "export": ex or ""})
break
elif kind == "error":
await _send_ws_json(ws, {"type": "error", "message": ex})
break
elif kind == "timeout":
from backend import chat as chat_module
await _send_ws_json(
ws, {"type": "timeout", "message": chat_module.run_timeout_message(lang_key)}
)
break
async def _stream_general(ws, payload, message, history, model_label, lang_key):
"""Stream chat.chat_general(). The agentic path already chunk-streams the
final answer server-side; the direct path's single final yield is
revealed client-side. The Generation Settings "Timeout" (whole-run
wall-clock deadline, seconds) is enforced at the stream layer β the
chat generators themselves have no deadline of their own."""
import backend.chat as chat
await _run_stream(
ws,
lambda: chat.chat_general(
message,
history,
model_label,
use_agentic=bool(payload.get("use_agentic")),
use_memory=bool(payload.get("use_memory", True)),
lang_key=lang_key,
max_steps=payload.get("max_steps"),
execution_timeout=payload.get("execution_timeout"),
use_tool_calling=bool(payload.get("use_tool_calling", True)),
),
# Explicit payload wins; None falls back to the saved per-tab value
# (the control on "auto"), else no deadline. Mirrors the step-budget
# fallback pattern in chat.chat_general_agentic().
timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("gen"),
lang_key=lang_key,
)
async def _stream_rag(ws, payload, message, history, model_label, lang_key):
"""Stream chat.chat_rag() with the multi-select retrieval-topic inputs:
`themes` / `subthemes` are LISTS (each chunk must match ANY selected
value; empty = no filter) and `files` is the list of source filenames
to restrict retrieval to. The legacy single-value `theme` / `subtheme`
keys are still accepted (backward compat). use_tool_calling defaults
True. The "Timeout" whole-run deadline is enforced at the stream layer
like General's."""
import backend.chat as chat
theme = payload.get("themes") or payload.get("theme") or ""
subtheme = payload.get("subthemes") or payload.get("subtheme") or ""
await _run_stream(
ws,
lambda: chat.chat_rag(
message,
history,
model_label,
use_agentic=bool(payload.get("use_agentic", True)),
use_memory=bool(payload.get("use_memory", True)),
theme=theme,
subtheme=subtheme,
sources=payload.get("files") or [],
max_steps=payload.get("max_steps"),
searcher_max_steps=payload.get("searcher_max_steps"),
execution_timeout=payload.get("execution_timeout"),
lang_key=lang_key,
use_tool_calling=bool(payload.get("use_tool_calling", True)),
visual_retrieval=bool(payload.get("visual_retrieval", False)),
),
timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("rag"),
lang_key=lang_key,
)
async def _stream_deep_research(ws, payload, message, history, model_label, lang_key):
"""Stream chat.chat_deep_research() β manager planning + delegated
web_search_agent calls β with the Playwright browser-tools toggle,
headless flag and step/timeout budgets."""
import backend.chat as chat
# Whole-run timeout: explicit payload wins; None falls back to the
# saved value (chat.chat_deep_research() resolves the same way for the
# agent's own per-step budget).
run_timeout = payload.get("timeout") or mr.get_saved_agent_run_timeout("dr")
await _run_stream(
ws,
lambda: chat.chat_deep_research(
message,
history,
model_label,
use_memory=bool(payload.get("use_memory", True)),
use_playwright=bool(payload.get("use_playwright", False)),
headless=bool(payload.get("headless", True)),
manager_max_steps=payload.get("manager_max_steps") or None,
search_max_steps=payload.get("search_max_steps") or None,
# The saved-value fallbacks live in chat.chat_deep_research()
# (same 'payload None β saved' pattern as the step budgets).
timeout=payload.get("timeout") or None,
execution_timeout=payload.get("execution_timeout") or None,
lang_key=lang_key,
use_tool_calling=bool(payload.get("use_tool_calling", True)),
),
timeout=run_timeout,
lang_key=lang_key,
)
async def _stream_vision(ws, payload, message, history, model_label, lang_key):
"""Stream chat.chat_vision(), which yields (history, image_reset, export)
β the image_reset slot is always None (keep the uploaded image) and is
dropped here. The uploaded image arrives as a temp-file path from
/api/upload; it is deleted after the run completes. The "Timeout"
whole-run deadline is enforced at the stream layer."""
import backend.chat as chat
image_path = payload.get("image") or None
mmproj_label = payload.get("mmproj_label") or ""
def build():
try:
for h, _img_reset, ex in chat.chat_vision(
message,
image_path,
history,
model_label,
bool(payload.get("use_memory", True)),
lang_key=lang_key,
mmproj_label=mmproj_label,
):
yield h, ex
finally:
if image_path:
try:
Path(image_path).unlink(missing_ok=True)
except OSError:
pass
await _run_stream(
ws,
build,
timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("vlm"),
lang_key=lang_key,
)
async def _stream_data(ws, payload, message, history, model_label, lang_key):
"""Stream chat.chat_data() β the Data Analysis tab's chat turn. The
uploaded files arrive as temp paths from /api/data/upload; they are
deleted after the run completes (same lifecycle as the Vision image)."""
import backend.chat as chat
files = [str(p) for p in (payload.get("files") or []) if p]
def build():
try:
yield from chat.chat_data(
message,
history,
model_label,
files=files,
use_memory=bool(payload.get("use_memory", True)),
lang_key=lang_key,
max_steps=payload.get("max_steps") or None,
worker_max_steps=payload.get("worker_max_steps") or None,
execution_timeout=payload.get("execution_timeout") or None,
)
finally:
for p in files:
try:
Path(p).unlink(missing_ok=True)
except OSError:
pass
await _run_stream(
ws,
build,
timeout=payload.get("timeout") or mr.get_saved_agent_run_timeout("data"),
lang_key=lang_key,
)
@app.websocket("/ws/stt/analyse")
async def stt_analyse_ws(ws: WebSocket):
"""Stream the STT transcript β Markdown report analysis live, like the
chat tabs: the model's generated tokens flow to the client as `live`
events (backend.live_stream bus drained by _run_stream) so the report
grows in real time, then a final `final` event carries the complete
report (in the export slot). Same token/session guard as /ws/chat."""
token = ws.query_params.get("token") or ws.headers.get("x-session-token")
if not token or token != _SESSION_TOKEN:
await ws.close(code=1008)
return
await ws.accept()
try:
payload = await ws.receive_json()
except Exception:
await ws.close()
return
transcript = payload.get("transcript") or ""
model_label = payload.get("model_label") or ""
lang_key = payload.get("lang", "kh")
import backend.chat as chat
if not (transcript or "").strip():
l = _lang(lang_key)
await _send_ws_json(
ws, {"type": "error", "message": l.get("err_stt_no_transcript", "no transcript")}
)
await ws.close()
return
def build():
# chat.analyse_transcript_to_report yields (status, report) tuples β
# adapt to the (history, export) contract _run_stream expects: the
# report lands in the export slot (the client reads it as the final
# answer), and the intermediate status yields pass through as
# history-less updates while the model's live tokens stream via the
# bus (same as every chat tab).
for _status, report in chat.analyse_transcript_to_report(
transcript, model_label, lang_key=lang_key
):
yield [], report or ""
try:
await _run_stream(ws, build, lang_key=lang_key)
except WebSocketDisconnect:
pass
except Exception:
try:
await _send_ws_json(ws, {"type": "error", "message": traceback.format_exc()})
except Exception:
pass
finally:
try:
await ws.close()
except Exception:
pass
@app.websocket("/ws/stt/transcribe")
async def stt_transcribe_ws(ws: WebSocket):
"""Stream STT transcription progress live β status messages flow as
`log` events and the growing transcript as `update` events, mirroring
the chat tabs' streaming pattern. A final `final` event carries the
complete transcript.
The client sends: {audio_file_url?, audio_blob?, stt_label, language}
Because WebSocket cannot carry binary multipart, the audio must be
uploaded first via POST /api/stt/upload (or the existing POST
/api/stt/transcribe endpoint) and the temp path passed, OR the client
posts the form data separately and sends the resulting temp path.
For simplicity, the client first uploads via a hidden form post, then
opens this socket with the returned temp path.
"""
token = ws.query_params.get("token") or ws.headers.get("x-session-token")
if not token or token != _SESSION_TOKEN:
await ws.close(code=1008)
return
await ws.accept()
try:
payload = await ws.receive_json()
except Exception:
await ws.close()
return
audio_path = payload.get("audio_path") or ""
stt_label = payload.get("stt_label") or ""
language = payload.get("language") or "auto"
lang_key = payload.get("lang") or "kh"
if not audio_path or not Path(audio_path).is_file():
await _send_ws_json(ws, {"type": "error", "message": "no audio file"})
await ws.close()
return
from backend import models
mid = mr.resolve_stt_model_id(stt_label) or mr.DEFAULT_STT_MODEL or None
try:
queue: asyncio.Queue = asyncio.Queue()
loop = asyncio.get_running_loop()
import threading
last_text = ""
def _run():
nonlocal last_text
try:
for chunk in models.transcribe_audio_stream(
audio_path, language=language or None, model_id=mid
):
text = str(chunk or "").strip()
if text.startswith(("β³", "π", "π‘", "π΅", "ποΈ")):
loop.call_soon_threadsafe(
queue.put_nowait, ("log", text)
)
else:
last_text = text
loop.call_soon_threadsafe(
queue.put_nowait, ("update", text)
)
except Exception as e:
loop.call_soon_threadsafe(
queue.put_nowait, ("error", str(e))
)
finally:
loop.call_soon_threadsafe(
queue.put_nowait, ("done", last_text)
)
t = threading.Thread(target=_run, daemon=True)
t.start()
while True:
kind, text = await queue.get()
if kind == "log":
await _send_ws_json(ws, {"type": "log", "message": text})
elif kind == "update":
await _send_ws_json(ws, {"type": "update", "text": text})
elif kind == "error":
await _send_ws_json(ws, {"type": "error", "message": text})
break
elif kind == "done":
# Send the final transcript
await _send_ws_json(ws, {"type": "final", "text": text})
break
except WebSocketDisconnect:
pass
except Exception:
try:
await _send_ws_json(ws, {"type": "error", "message": traceback.format_exc()})
except Exception:
pass
finally:
try:
await ws.close()
except Exception:
pass
@app.post("/api/stt/upload")
async def stt_upload(request: Request):
"""Upload an audio file for WebSocket-based STT β returns a temp path
that the client passes to /ws/stt/transcribe."""
form = await request.form()
files = form.getlist("audio")
paths = _save_uploads(files, "stt")
if not paths:
return JSONResponse({"ok": False, "message": "no audio uploaded"}, status_code=400)
return {"ok": True, "path": paths[0]}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Static SPA (must come last so /api/* routes win)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if (DIST / "assets").is_dir():
app.mount("/assets", StaticFiles(directory=str(DIST / "assets")), name="assets")
if APP_ICON.is_file():
@app.get("/favicon.png", include_in_schema=False)
def favicon():
return FileResponse(str(APP_ICON))
@app.get("/{path:path}", include_in_schema=False)
def spa(path: str):
f = DIST / path
if path and f.is_file():
return FileResponse(str(f))
index_file = DIST / "index.html"
if index_file.is_file():
content = index_file.read_text(encoding="utf-8")
token_script = f'<script>window.__SESSION_TOKEN__="{_SESSION_TOKEN}";</script>'
if "</head>" in content:
content = content.replace("</head>", f"{token_script}</head>", 1)
else:
content = token_script + content
return HTMLResponse(content)
return JSONResponse({"ok": False, "message": "SPA not built"}, status_code=404)
def _reconfigure_stdio():
"""Harden sys.stdout / sys.stderr for the server process.
Delegates to the shared backend.stdio_hardening.harden_stdio() β the
SINGLE source of truth used by every entry point (app.py, run_webview.py,
the frozen runtime hook). Besides forcing UTF-8 + errors=replace (the
old emoji/Khmer UnicodeEncodeError fix), it now also REPLACES streams
whose OS handle is closed/invalid β the Windows GUI-launch case where
`print()` raises `OSError: [WinError 6] The handle is invalid` and
kills a whole chat turn (e.g. the `[Model] Starting/reusing llama-server`
line in get_llm).
"""
from backend.stdio_hardening import harden_stdio, harden_subprocesses
from backend.metadata_hardening import harden_metadata
harden_stdio()
harden_subprocesses()
harden_metadata()
def run(host: str = "127.0.0.1", port: int = 7862, log_level: str = "warning",
progress=None):
"""Blocking uvicorn entry β call from a background thread inside pywebview.
`progress` is an optional callable(msg: str) invoked as the server reaches
startup milestones (loading model registry, binding the port, β¦). The
desktop launcher (run_webview.py) uses it to drive the splash window's
live status line; other callers (tools/_launch_web.py, tools/_dev_web.py,
tests) leave it None and nothing changes.
"""
_reconfigure_stdio()
def _report(msg: str):
if progress is not None:
try:
progress(msg)
except Exception:
pass # a broken status reporter must never kill startup
_report("Loading model registryβ¦")
import uvicorn
# The splash says 'Starting the appβ¦' β there is no user-facing server
# to announce; uvicorn binds the port behind the scenes.
_report("Starting the appβ¦")
uvicorn.run(app, host=host, port=port, log_level=log_level)
|