File size: 132,592 Bytes
e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a a719a46 36bb8b0 a719a46 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a a452459 e5dec5c a452459 36bb8b0 a452459 36bb8b0 a452459 36bb8b0 a452459 36bb8b0 a452459 36bb8b0 a452459 36bb8b0 a452459 36bb8b0 a452459 e5dec5c a452459 e5dec5c 6a4369a e5dec5c a452459 e5dec5c 6a4369a e5dec5c a452459 e5dec5c a452459 e5dec5c a452459 e5dec5c a452459 e5dec5c a452459 e5dec5c a452459 e5dec5c 36bb8b0 e5dec5c 36bb8b0 e5dec5c 36bb8b0 e5dec5c 36bb8b0 c602672 36bb8b0 e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c d68638b e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a baa5d38 6a4369a e5dec5c baa5d38 6a4369a e5dec5c 6a4369a e5dec5c baa5d38 6a4369a baa5d38 e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a e5dec5c 6a4369a baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c 6a4369a e5dec5c d68638b a452459 baa5d38 d68638b e5dec5c baa5d38 d68638b e5dec5c a452459 e5dec5c a452459 d68638b a452459 d68638b baa5d38 d68638b baa5d38 d68638b e5dec5c d68638b e5dec5c d68638b a452459 d68638b a452459 d68638b a452459 d68638b a452459 d68638b a452459 d68638b a452459 d68638b e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 4ace40e baa5d38 e5dec5c 6a4369a baa5d38 e5dec5c 4ace40e baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 4ace40e baa5d38 4ace40e baa5d38 4ace40e e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c 6a4369a e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c 6a4369a e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c baa5d38 e5dec5c 5a52d94 baa5d38 e5dec5c baa5d38 e5dec5c 5a52d94 baa5d38 e5dec5c 4ace40e 6a4369a 4ace40e baa5d38 a452459 d68638b a452459 d68638b a452459 d68638b baa5d38 d68638b a452459 d68638b a452459 d68638b a452459 baa5d38 d68638b baa5d38 d68638b 6a4369a baa5d38 a452459 d68638b baa5d38 d68638b baa5d38 d68638b baa5d38 d68638b baa5d38 a452459 baa5d38 d68638b a452459 d68638b 4ace40e baa5d38 d68638b 4ace40e a452459 baa5d38 4ace40e baa5d38 4ace40e 6a4369a 4ace40e baa5d38 4ace40e baa5d38 6a4369a baa5d38 e5dec5c | 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 | #!/usr/bin/env python3
"""
AI Invoice Processing System - Complete Single File for Hugging Face Spaces
A comprehensive system with AI-powered extraction, semantic search, and analytics.
Author: AI Assistant
Date: 2024
Version: HuggingFace Single File v1.0
"""
# ===============================================================================
# IMPORTS AND COMPATIBILITY CHECKS
# ===============================================================================
import os
import json
import re
import tempfile
import shutil
import pickle
import numpy as np
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from pathlib import Path
import time
import logging
import uuid
# Check if running on Hugging Face Spaces
IS_HF_SPACE = os.getenv("SPACE_ID") is not None
# Get Hugging Face token from environment or Streamlit secrets
HF_TOKEN = None
try:
# Try Streamlit secrets first (for HF Spaces)
HF_TOKEN = st.secrets.get("HF_TOKEN", None)
except:
# Fall back to environment variable
HF_TOKEN = os.getenv("HF_TOKEN", None)
# Streamlit and core libraries
import streamlit as st
import sqlite3
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import requests
# Vector storage and embeddings (with fallbacks)
try:
import faiss
FAISS_AVAILABLE = True
except ImportError:
FAISS_AVAILABLE = False
st.warning("β οΈ FAISS not available. Vector search will be disabled.")
try:
from sentence_transformers import SentenceTransformer
SENTENCE_TRANSFORMERS_AVAILABLE = True
except ImportError:
SENTENCE_TRANSFORMERS_AVAILABLE = False
st.warning("β οΈ Sentence Transformers not available. Using fallback methods.")
try:
import torch
TORCH_AVAILABLE = True
except ImportError:
TORCH_AVAILABLE = False
# Document processing (simplified for HF)
try:
import pdfplumber
PDF_PROCESSING_AVAILABLE = True
PDF_PROCESSOR = "pdfplumber"
except ImportError:
try:
import PyPDF2
PDF_PROCESSING_AVAILABLE = True
PDF_PROCESSOR = "PyPDF2"
except ImportError:
PDF_PROCESSING_AVAILABLE = False
PDF_PROCESSOR = None
# ===============================================================================
# STREAMLIT CONFIGURATION
# ===============================================================================
st.set_page_config(
page_title="AI Invoice Processing System",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://huggingface.co/spaces',
'Report a bug': 'https://huggingface.co/spaces',
'About': """
# AI Invoice Processing System
Built for Hugging Face Spaces with AI-powered extraction and semantic search.
"""
}
)
# ===============================================================================
# CONFIGURATION
# ===============================================================================
HF_CONFIG = {
"max_file_size_mb": 10,
"max_concurrent_files": 3,
"timeout_seconds": 30,
"use_cpu_only": True,
"embedding_model": "all-MiniLM-L6-v2",
"cache_dir": "./cache",
"data_dir": "./data",
"enable_ollama": False,
}
# Create necessary directories
os.makedirs(HF_CONFIG["cache_dir"], exist_ok=True)
os.makedirs(HF_CONFIG["data_dir"], exist_ok=True)
# ===============================================================================
# DATA STRUCTURES
# ===============================================================================
@dataclass
class InvoiceData:
"""Data structure for extracted invoice information"""
supplier_name: str = ""
buyer_name: str = ""
invoice_number: str = ""
date: str = ""
amount: float = 0.0
quantity: int = 0
product_description: str = ""
file_path: str = ""
extraction_confidence: float = 0.0
processing_method: str = "regex"
@dataclass
class VectorSearchResult:
"""Data structure for vector search results"""
invoice_id: str
invoice_number: str
supplier_name: str
similarity_score: float
content_preview: str
metadata: Dict
# ===============================================================================
# DOCUMENT PROCESSING CLASSES
# ===============================================================================
class DocumentProcessor:
"""Simplified document processor for Hugging Face Spaces"""
def __init__(self):
self.setup_processors()
def setup_processors(self):
"""Setup available document processors"""
self.processors = {}
# PDF processing
if PDF_PROCESSING_AVAILABLE:
if PDF_PROCESSOR == "pdfplumber":
self.processors['pdf'] = self.extract_with_pdfplumber
st.success("β
PDF processing available (pdfplumber)")
elif PDF_PROCESSOR == "PyPDF2":
self.processors['pdf'] = self.extract_with_pypdf2
st.success("β
PDF processing available (PyPDF2)")
else:
st.warning("β οΈ No PDF processor available")
# Text files
self.processors['txt'] = self.extract_text_file
def extract_with_pdfplumber(self, file_path: str) -> str:
"""Extract text using pdfplumber"""
try:
import pdfplumber
text = ""
with pdfplumber.open(file_path) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
return text
except Exception as e:
st.error(f"PDF extraction failed: {e}")
return ""
def extract_with_pypdf2(self, file_path: str) -> str:
"""Extract text using PyPDF2"""
try:
import PyPDF2
text = ""
with open(file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text
except Exception as e:
st.error(f"PDF extraction failed: {e}")
return ""
def extract_text_file(self, file_path: str) -> str:
"""Extract text from text files"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
st.error(f"Text file extraction failed: {e}")
return ""
def extract_text_from_document(self, file_path: str) -> str:
"""Extract text from document based on file type"""
file_ext = Path(file_path).suffix.lower()
if file_ext == '.pdf':
processor = self.processors.get('pdf')
elif file_ext == '.txt':
processor = self.processors.get('txt')
else:
st.warning(f"Unsupported file type: {file_ext}")
return ""
if processor:
return processor(file_path)
else:
st.error(f"No processor available for {file_ext}")
return ""
# ===============================================================================
# AI EXTRACTION CLASS
# ===============================================================================
class AIExtractor:
"""AI extraction for Hugging Face Spaces with Mistral 7B support"""
def __init__(self):
self.use_mistral = self.setup_mistral()
self.use_transformers = self.setup_transformers() if not self.use_mistral else False
def setup_mistral(self):
"""Try to setup Mistral 7B model with proper authentication"""
try:
# Check if we have HF token
if not HF_TOKEN:
st.warning("β οΈ Hugging Face token not found. Add HF_TOKEN to secrets for Mistral access.")
return False
# Check if we're in a high-resource environment
import psutil
memory_gb = psutil.virtual_memory().total / (1024**3)
if memory_gb < 8:
st.warning("β οΈ Insufficient memory for Mistral 7B. Using lighter models.")
return False
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from huggingface_hub import login
# Login with HF token
login(token=HF_TOKEN)
with st.spinner("π Loading Mistral 7B model (this may take a few minutes)..."):
# Use the instruction-tuned model
model_name = "mistralai/Mistral-7B-Instruct-v0.1"
# Load with reduced precision for memory efficiency
self.mistral_tokenizer = AutoTokenizer.from_pretrained(
model_name,
cache_dir=HF_CONFIG["cache_dir"],
token=HF_TOKEN
)
self.mistral_model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16 if TORCH_AVAILABLE else None,
device_map="auto" if TORCH_AVAILABLE else None,
load_in_8bit=True, # Use 8-bit quantization
cache_dir=HF_CONFIG["cache_dir"],
token=HF_TOKEN
)
# Create pipeline
self.mistral_pipeline = pipeline(
"text-generation",
model=self.mistral_model,
tokenizer=self.mistral_tokenizer,
torch_dtype=torch.float16 if TORCH_AVAILABLE else None,
device_map="auto" if TORCH_AVAILABLE else None
)
st.success("β
Mistral 7B model loaded successfully!")
return True
except ImportError as e:
st.warning(f"β οΈ Missing dependencies for Mistral 7B: {e}")
return False
except Exception as e:
st.warning(f"β οΈ Mistral 7B not available: {e}")
st.info("π‘ To use Mistral 7B: Add your Hugging Face token to secrets as 'HF_TOKEN'")
return False
def setup_transformers(self):
"""Fallback to lighter NER model"""
try:
from transformers import pipeline
with st.spinner("Loading fallback AI model..."):
self.ner_pipeline = pipeline(
"ner",
model="dbmdz/bert-large-cased-finetuned-conll03-english",
aggregation_strategy="simple"
)
st.success("β
Fallback AI extraction model loaded")
return True
except Exception as e:
st.warning(f"β οΈ AI extraction not available: {e}")
return False
def extract_with_mistral(self, text: str) -> InvoiceData:
"""Extract invoice data using Mistral 7B"""
try:
# Create a detailed prompt for Mistral
prompt = f"""<s>[INST] You are an expert at extracting structured information from invoices.
Extract the following information from this invoice text and respond ONLY with valid JSON:
{{
"invoice_number": "invoice or bill number",
"supplier_name": "company providing goods/services",
"buyer_name": "company receiving goods/services",
"date": "date in YYYY-MM-DD format",
"amount": "total amount as number only",
"quantity": "total quantity as integer",
"product_description": "brief description of items/services"
}}
Invoice text:
{text[:2000]}
Respond with JSON only: [/INST]"""
# Generate response
response = self.mistral_pipeline(
prompt,
max_new_tokens=300,
temperature=0.1,
do_sample=True,
pad_token_id=self.mistral_tokenizer.eos_token_id
)
# Extract the generated text
generated_text = response[0]['generated_text']
# Find JSON in the response
json_start = generated_text.find('{')
json_end = generated_text.rfind('}') + 1
if json_start != -1 and json_end > json_start:
json_str = generated_text[json_start:json_end]
# Parse JSON
import json
data = json.loads(json_str)
# Create InvoiceData object
invoice_data = InvoiceData()
invoice_data.supplier_name = str(data.get('supplier_name', '')).strip()
invoice_data.buyer_name = str(data.get('buyer_name', '')).strip()
invoice_data.invoice_number = str(data.get('invoice_number', '')).strip()
invoice_data.date = self.parse_date(str(data.get('date', '')))
# Parse amount
try:
amount_val = data.get('amount', 0)
if isinstance(amount_val, str):
amount_clean = re.sub(r'[^\d.]', '', amount_val)
invoice_data.amount = float(amount_clean) if amount_clean else 0.0
else:
invoice_data.amount = float(amount_val)
except:
invoice_data.amount = 0.0
# Parse quantity
try:
qty_val = data.get('quantity', 0)
invoice_data.quantity = int(float(str(qty_val).replace(',', '')))
except:
invoice_data.quantity = 0
invoice_data.product_description = str(data.get('product_description', '')).strip()
invoice_data.extraction_confidence = 0.95 # High confidence for Mistral
invoice_data.processing_method = "mistral_7b"
return invoice_data
else:
st.warning("β οΈ Mistral response didn't contain valid JSON, falling back to regex")
return self.extract_with_regex(text)
except Exception as e:
st.error(f"Mistral extraction failed: {e}")
return self.extract_with_regex(text)
def extract_with_ai(self, text: str) -> InvoiceData:
"""Extract invoice data using available AI method"""
if self.use_mistral:
st.info("π€ Using Mistral 7B for extraction...")
return self.extract_with_mistral(text)
elif self.use_transformers:
st.info("π€ Using NER model for extraction...")
return self.extract_with_ner(text)
else:
st.info("π§ Using regex extraction...")
return self.extract_with_regex(text)
def extract_with_ner(self, text: str) -> InvoiceData:
"""Extract using NER model (fallback method)"""
try:
# Use NER to extract entities
entities = self.ner_pipeline(text[:512]) # Limit text length
invoice_data = InvoiceData()
invoice_data.processing_method = "ai_ner"
# Extract specific entities
for entity in entities:
entity_text = entity['word'].replace('##', '')
if entity['entity_group'] == 'ORG':
if not invoice_data.supplier_name:
invoice_data.supplier_name = entity_text
elif not invoice_data.buyer_name:
invoice_data.buyer_name = entity_text
elif entity['entity_group'] == 'MISC':
if not invoice_data.invoice_number and any(c.isdigit() for c in entity_text):
invoice_data.invoice_number = entity_text
# Fall back to regex for missing fields
regex_data = self.extract_with_regex(text)
# Combine results
if not invoice_data.invoice_number:
invoice_data.invoice_number = regex_data.invoice_number
if not invoice_data.amount:
invoice_data.amount = regex_data.amount
if not invoice_data.date:
invoice_data.date = regex_data.date
if not invoice_data.quantity:
invoice_data.quantity = regex_data.quantity
invoice_data.extraction_confidence = 0.8
return invoice_data
except Exception as e:
st.error(f"NER extraction failed: {e}")
return self.extract_with_regex(text)
def extract_with_regex(self, text: str) -> InvoiceData:
"""Enhanced regex extraction with better amount detection"""
invoice_data = InvoiceData()
invoice_data.processing_method = "regex"
# Enhanced regex patterns with more comprehensive matching
patterns = {
'invoice_number': [
r'invoice\s*(?:no|number|#)?\s*:?\s*([A-Z0-9\-_/]+)',
r'bill\s*(?:no|number|#)?\s*:?\s*([A-Z0-9\-_/]+)',
r'inv\s*(?:no|number|#)?\s*:?\s*([A-Z0-9\-_/]+)',
r'ref\s*(?:no|number|#)?\s*:?\s*([A-Z0-9\-_/]+)',
r'#\s*([A-Z0-9\-_/]{3,})',
r'(?:^|\s)([A-Z]{2,}\d{3,}|\d{3,}[A-Z]{2,})', # Common patterns like ABC123 or 123ABC
],
'amount': [
# Currency symbols with amounts
r'total\s*(?:amount)?\s*:?\s*[\$βΉΒ£β¬]?\s*([0-9,]+\.?\d*)',
r'amount\s*(?:due|paid|total)?\s*:?\s*[\$βΉΒ£β¬]?\s*([0-9,]+\.?\d*)',
r'grand\s*total\s*:?\s*[\$βΉΒ£β¬]?\s*([0-9,]+\.?\d*)',
r'net\s*(?:amount|total)\s*:?\s*[\$βΉΒ£β¬]?\s*([0-9,]+\.?\d*)',
r'sub\s*total\s*:?\s*[\$βΉΒ£β¬]?\s*([0-9,]+\.?\d*)',
# Currency symbols at the beginning
r'[\$βΉΒ£β¬]\s*([0-9,]+\.?\d*)',
# Amounts at end of lines (common in invoices)
r'([0-9,]+\.?\d*)\s*[\$βΉΒ£β¬]?\s*
def parse_date(self, date_str: str) -> str:
"""Parse date to YYYY-MM-DD format"""
if not date_str:
return ""
formats = ['%Y-%m-%d', '%m/%d/%Y', '%d/%m/%Y', '%m-%d-%Y', '%d-%m-%Y', '%Y/%m/%d']
for fmt in formats:
try:
parsed_date = datetime.strptime(date_str, fmt)
return parsed_date.strftime('%Y-%m-%d')
except ValueError:
continue
return date_str
# ===============================================================================
# VECTOR STORE CLASS
# ===============================================================================
class VectorStore:
"""Simplified vector store for Hugging Face Spaces"""
def __init__(self, embedding_model: str = "all-MiniLM-L6-v2"):
self.embedding_model_name = embedding_model
self.vector_store_path = os.path.join(HF_CONFIG["data_dir"], "vectors.pkl")
self.metadata_path = os.path.join(HF_CONFIG["data_dir"], "metadata.pkl")
self.embedding_model = None
self.vectors = []
self.document_metadata = []
self.embedding_dimension = None
self.setup_embedding_model()
self.load_vector_store()
def setup_embedding_model(self):
"""Initialize the sentence transformer model"""
if not SENTENCE_TRANSFORMERS_AVAILABLE:
st.warning("β οΈ Sentence Transformers not available. Vector search disabled.")
return
try:
with st.spinner(f"Loading embedding model: {self.embedding_model_name}..."):
self.embedding_model = SentenceTransformer(
self.embedding_model_name,
cache_folder=HF_CONFIG["cache_dir"]
)
# Get embedding dimension
test_embedding = self.embedding_model.encode(["test"])
self.embedding_dimension = test_embedding.shape[0]
st.success(f"β
Embedding model loaded: {self.embedding_model_name}")
except Exception as e:
st.error(f"β Failed to load embedding model: {e}")
self.embedding_model = None
def load_vector_store(self):
"""Load existing vector store"""
try:
if os.path.exists(self.vector_store_path) and os.path.exists(self.metadata_path):
with open(self.vector_store_path, 'rb') as f:
self.vectors = pickle.load(f)
with open(self.metadata_path, 'rb') as f:
self.document_metadata = pickle.load(f)
st.success(f"β
Vector store loaded: {len(self.document_metadata)} documents")
else:
self.vectors = []
self.document_metadata = []
st.info("π New vector store initialized")
except Exception as e:
st.error(f"β Error loading vector store: {e}")
self.vectors = []
self.document_metadata = []
def save_vector_store(self):
"""Save vector store to disk"""
try:
with open(self.vector_store_path, 'wb') as f:
pickle.dump(self.vectors, f)
with open(self.metadata_path, 'wb') as f:
pickle.dump(self.document_metadata, f)
return True
except Exception as e:
st.error(f"Error saving vector store: {e}")
return False
def create_document_text(self, invoice_data: dict, raw_text: str = "") -> str:
"""Create searchable text from invoice data"""
text_parts = []
for field, value in invoice_data.items():
if value and field != 'id':
text_parts.append(f"{field}: {value}")
if raw_text:
text_parts.append(f"content: {raw_text[:300]}")
return " | ".join(text_parts)
def add_document(self, invoice_data: dict, raw_text: str = "") -> bool:
"""Add a document to the vector store"""
if not self.embedding_model:
return False
try:
document_text = self.create_document_text(invoice_data, raw_text)
# Generate embedding
embedding = self.embedding_model.encode(document_text, normalize_embeddings=True)
# Create metadata
metadata = {
'invoice_id': invoice_data.get('id', ''),
'invoice_number': invoice_data.get('invoice_number', ''),
'supplier_name': invoice_data.get('supplier_name', ''),
'buyer_name': invoice_data.get('buyer_name', ''),
'amount': invoice_data.get('amount', 0),
'date': invoice_data.get('date', ''),
'file_name': invoice_data.get('file_info', {}).get('file_name', ''),
'document_text': document_text[:200],
'timestamp': datetime.now().isoformat()
}
# Add to store
self.vectors.append(embedding)
self.document_metadata.append(metadata)
return True
except Exception as e:
st.error(f"Error adding document to vector store: {e}")
return False
def semantic_search(self, query: str, top_k: int = 5) -> List[VectorSearchResult]:
"""Perform semantic search using cosine similarity"""
if not self.embedding_model or not self.vectors:
return []
try:
# Generate query embedding
query_embedding = self.embedding_model.encode(query, normalize_embeddings=True)
# Calculate similarities
similarities = []
for i, doc_embedding in enumerate(self.vectors):
similarity = np.dot(query_embedding, doc_embedding)
similarities.append((similarity, i))
# Sort by similarity
similarities.sort(reverse=True)
# Return top results
results = []
for similarity, idx in similarities[:top_k]:
if similarity > 0.1: # Relevance threshold
metadata = self.document_metadata[idx]
result = VectorSearchResult(
invoice_id=metadata.get('invoice_id', ''),
invoice_number=metadata.get('invoice_number', ''),
supplier_name=metadata.get('supplier_name', ''),
similarity_score=float(similarity),
content_preview=metadata.get('document_text', ''),
metadata=metadata
)
results.append(result)
return results
except Exception as e:
st.error(f"Error in semantic search: {e}")
return []
# ===============================================================================
# MAIN PROCESSOR CLASS
# ===============================================================================
class InvoiceProcessor:
"""Main invoice processor for Hugging Face Spaces"""
def __init__(self):
self.setup_storage()
self.document_processor = DocumentProcessor()
self.ai_extractor = AIExtractor()
self.vector_store = VectorStore() if SENTENCE_TRANSFORMERS_AVAILABLE else None
# Initialize stats
self.processing_stats = {
'total_processed': 0,
'successful': 0,
'failed': 0,
'start_time': datetime.now()
}
def setup_storage(self):
"""Setup storage paths"""
self.data_dir = HF_CONFIG["data_dir"]
self.json_path = os.path.join(self.data_dir, "invoices.json")
# Initialize JSON storage
if not os.path.exists(self.json_path):
initial_data = {
"metadata": {
"created_at": datetime.now().isoformat(),
"version": "hf_v1.0",
"total_invoices": 0
},
"invoices": [],
"summary": {
"total_amount": 0.0,
"unique_suppliers": [],
"processing_stats": {"successful": 0, "failed": 0}
}
}
self.save_json_data(initial_data)
def load_json_data(self) -> dict:
"""Load invoice data from JSON"""
try:
with open(self.json_path, 'r', encoding='utf-8') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
self.setup_storage()
return self.load_json_data()
def save_json_data(self, data: dict):
"""Save invoice data to JSON"""
try:
with open(self.json_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
except Exception as e:
st.error(f"Error saving data: {e}")
def process_uploaded_file(self, uploaded_file) -> InvoiceData:
"""Process a single uploaded file with enhanced debugging"""
self.processing_stats['total_processed'] += 1
try:
# Debug file info
file_size = len(uploaded_file.getvalue())
file_extension = uploaded_file.name.split('.')[-1].lower() if '.' in uploaded_file.name else 'unknown'
st.info(f"π Processing: {uploaded_file.name} ({file_size/1024:.1f} KB, .{file_extension})")
# Check file size
if file_size > HF_CONFIG["max_file_size_mb"] * 1024 * 1024:
error_msg = f"File too large: {file_size / 1024 / 1024:.2f}MB > {HF_CONFIG['max_file_size_mb']}MB"
st.error(error_msg)
self.processing_stats['failed'] += 1
return InvoiceData()
# Check file type
if file_extension not in ['pdf', 'txt']:
error_msg = f"Unsupported file type: .{file_extension} (supported: PDF, TXT)"
st.warning(error_msg)
self.processing_stats['failed'] += 1
return InvoiceData()
# Save temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_extension}") as tmp_file:
file_content = uploaded_file.getvalue()
tmp_file.write(file_content)
tmp_file_path = tmp_file.name
st.info(f"πΎ Saved temporarily to: {tmp_file_path}")
try:
# Extract text
st.info("π Extracting text from document...")
text = self.document_processor.extract_text_from_document(tmp_file_path)
if not text or not text.strip():
st.warning(f"β No text extracted from {uploaded_file.name}")
self.processing_stats['failed'] += 1
return InvoiceData()
text_length = len(text)
st.info(f"π Extracted {text_length} characters of text")
# Show text preview
if text_length > 0:
with st.expander("π Text Preview (First 500 characters)", expanded=False):
st.text(text[:500] + "..." if len(text) > 500 else text)
# Extract invoice data
st.info("π€ Extracting invoice data using AI/Regex...")
invoice_data = self.ai_extractor.extract_with_ai(text)
invoice_data.file_path = uploaded_file.name
# Show extraction results
st.info(f"π Extraction completed with {invoice_data.extraction_confidence:.1%} confidence")
# Save to storage
st.info("πΎ Saving extracted data...")
self.save_invoice_data(invoice_data, text, file_size)
self.processing_stats['successful'] += 1
st.success(f"β
Successfully processed {uploaded_file.name}")
return invoice_data
finally:
# Cleanup
try:
os.unlink(tmp_file_path)
st.info("π§Ή Cleaned up temporary file")
except:
pass
except Exception as e:
error_msg = f"Error processing {uploaded_file.name}: {str(e)}"
st.error(error_msg)
self.processing_stats['failed'] += 1
# Show detailed error for debugging
with st.expander("π Error Details", expanded=False):
st.code(str(e))
import traceback
st.code(traceback.format_exc())
return InvoiceData()
def save_invoice_data(self, invoice_data: InvoiceData, raw_text: str, file_size: int):
"""Save invoice data to JSON and vector store"""
try:
# Load existing data
data = self.load_json_data()
# Create invoice record
invoice_record = {
"id": len(data["invoices"]) + 1,
"invoice_number": invoice_data.invoice_number,
"supplier_name": invoice_data.supplier_name,
"buyer_name": invoice_data.buyer_name,
"date": invoice_data.date,
"amount": invoice_data.amount,
"quantity": invoice_data.quantity,
"product_description": invoice_data.product_description,
"file_info": {
"file_name": invoice_data.file_path,
"file_size": file_size
},
"extraction_info": {
"confidence": invoice_data.extraction_confidence,
"method": invoice_data.processing_method,
"raw_text_preview": raw_text[:300]
},
"timestamps": {
"created_at": datetime.now().isoformat()
}
}
# Add to invoices
data["invoices"].append(invoice_record)
# Update summary
self.update_summary(data)
# Save JSON
self.save_json_data(data)
# Add to vector store
if self.vector_store:
self.vector_store.add_document(invoice_record, raw_text)
self.vector_store.save_vector_store()
except Exception as e:
st.error(f"Error saving invoice data: {e}")
def update_summary(self, data: dict):
"""Update summary statistics"""
invoices = data["invoices"]
total_amount = sum(inv.get("amount", 0) for inv in invoices)
unique_suppliers = list(set(inv.get("supplier_name", "") for inv in invoices if inv.get("supplier_name")))
data["summary"] = {
"total_amount": total_amount,
"unique_suppliers": unique_suppliers,
"processing_stats": {
"successful": self.processing_stats['successful'],
"failed": self.processing_stats['failed'],
"total_processed": self.processing_stats['total_processed']
}
}
data["metadata"]["last_updated"] = datetime.now().isoformat()
data["metadata"]["total_invoices"] = len(invoices)
# ===============================================================================
# CHATBOT CLASS
# ===============================================================================
class ChatBot:
"""Chatbot for invoice queries"""
def __init__(self, processor: InvoiceProcessor):
self.processor = processor
def query_database(self, query: str) -> str:
"""Process user query and return response"""
try:
data = self.processor.load_json_data()
invoices = data.get("invoices", [])
if not invoices:
return "No invoice data found. Please upload some invoices first."
query_lower = query.lower()
# Handle different query types
if any(phrase in query_lower for phrase in ["summary", "overview", "total"]):
return self.generate_summary(data)
elif "count" in query_lower or "how many" in query_lower:
return self.handle_count_query(data)
elif any(phrase in query_lower for phrase in ["amount", "value", "money", "cost"]):
return self.handle_amount_query(data)
elif any(phrase in query_lower for phrase in ["supplier", "vendor", "company"]):
return self.handle_supplier_query(data, query)
elif self.processor.vector_store:
return self.handle_semantic_search(query)
else:
return self.handle_general_query(data, query)
except Exception as e:
return f"Error processing query: {e}"
def generate_summary(self, data: dict) -> str:
"""Generate comprehensive summary"""
invoices = data.get("invoices", [])
summary = data.get("summary", {})
if not invoices:
return "No invoices found in the system."
total_amount = summary.get("total_amount", 0)
avg_amount = total_amount / len(invoices) if invoices else 0
unique_suppliers = len(summary.get("unique_suppliers", []))
response = f"""
**π Invoice System Summary**
β’ **Total Invoices**: {len(invoices):,}
β’ **Total Value**: βΉ{total_amount:,.2f}
β’ **Average Invoice**: βΉ{avg_amount:,.2f}
β’ **Unique Suppliers**: {unique_suppliers}
**π Processing Stats**
β’ **Successful**: {summary.get('processing_stats', {}).get('successful', 0)}
β’ **Failed**: {summary.get('processing_stats', {}).get('failed', 0)}
**π Recent Invoices**
"""
# Show recent invoices
recent = sorted(invoices, key=lambda x: x.get('timestamps', {}).get('created_at', ''), reverse=True)[:5]
for i, inv in enumerate(recent, 1):
response += f"\n{i}. **{inv.get('invoice_number', 'N/A')}** - {inv.get('supplier_name', 'Unknown')} (βΉ{inv.get('amount', 0):,.2f})"
return response
def handle_count_query(self, data: dict) -> str:
"""Handle count-related queries"""
invoices = data.get("invoices", [])
total = len(invoices)
unique_numbers = len(set(inv.get('invoice_number', '') for inv in invoices if inv.get('invoice_number')))
return f"""
**π Invoice Count Summary**
β’ **Total Records**: {total}
β’ **Unique Invoice Numbers**: {unique_numbers}
β’ **Duplicates**: {total - unique_numbers if total > unique_numbers else 0}
**π
Processing Timeline**
β’ **First Invoice**: {invoices[0].get('timestamps', {}).get('created_at', 'N/A')[:10] if invoices else 'N/A'}
β’ **Latest Invoice**: {invoices[-1].get('timestamps', {}).get('created_at', 'N/A')[:10] if invoices else 'N/A'}
"""
def handle_amount_query(self, data: dict) -> str:
"""Handle amount-related queries"""
invoices = data.get("invoices", [])
amounts = [inv.get('amount', 0) for inv in invoices if inv.get('amount', 0) > 0]
if not amounts:
return "No amount information found in invoices."
total_amount = sum(amounts)
avg_amount = total_amount / len(amounts)
max_amount = max(amounts)
min_amount = min(amounts)
# Find high-value invoices
high_value_threshold = sorted(amounts, reverse=True)[min(4, len(amounts)-1)] if len(amounts) > 5 else max_amount
high_value_invoices = [inv for inv in invoices if inv.get('amount', 0) >= high_value_threshold]
response = f"""
**π° Financial Analysis**
β’ **Total Amount**: βΉ{total_amount:,.2f}
β’ **Average Amount**: βΉ{avg_amount:,.2f}
β’ **Highest Invoice**: βΉ{max_amount:,.2f}
β’ **Lowest Invoice**: βΉ{min_amount:,.2f}
**π― High-Value Invoices (βΉ{high_value_threshold:,.2f}+)**
"""
for i, inv in enumerate(high_value_invoices[:5], 1):
response += f"\n{i}. **{inv.get('invoice_number', 'N/A')}** - {inv.get('supplier_name', 'Unknown')} (βΉ{inv.get('amount', 0):,.2f})"
return response
def handle_supplier_query(self, data: dict, query: str) -> str:
"""Handle supplier-related queries"""
invoices = data.get("invoices", [])
# Count invoices by supplier
supplier_counts = {}
supplier_amounts = {}
for inv in invoices:
supplier = inv.get('supplier_name', '').strip()
if supplier:
supplier_counts[supplier] = supplier_counts.get(supplier, 0) + 1
supplier_amounts[supplier] = supplier_amounts.get(supplier, 0) + inv.get('amount', 0)
if not supplier_counts:
return "No supplier information found in invoices."
# Sort suppliers by amount
top_suppliers = sorted(supplier_amounts.items(), key=lambda x: x[1], reverse=True)[:10]
response = f"""
**π’ Supplier Analysis**
β’ **Total Unique Suppliers**: {len(supplier_counts)}
β’ **Most Active**: {max(supplier_counts, key=supplier_counts.get)} ({supplier_counts[max(supplier_counts, key=supplier_counts.get)]} invoices)
**π° Top Suppliers by Amount**
"""
for i, (supplier, amount) in enumerate(top_suppliers, 1):
count = supplier_counts[supplier]
avg = amount / count if count > 0 else 0
response += f"\n{i}. **{supplier}** - βΉ{amount:,.2f} ({count} invoices, avg: βΉ{avg:,.2f})"
return response
def handle_semantic_search(self, query: str) -> str:
"""Handle semantic search queries"""
try:
results = self.processor.vector_store.semantic_search(query, top_k=5)
if not results:
return f"No relevant results found for '{query}'. Try different keywords."
response = f"π **Semantic Search Results for '{query}'**\n\n"
for i, result in enumerate(results, 1):
response += f"{i}. **{result.invoice_number}** - {result.supplier_name}\n"
response += f" β’ Similarity: {result.similarity_score:.3f}\n"
response += f" β’ Amount: βΉ{result.metadata.get('amount', 0):,.2f}\n"
response += f" β’ Preview: {result.content_preview[:100]}...\n\n"
return response
except Exception as e:
return f"Semantic search error: {e}"
def handle_general_query(self, data: dict, query: str) -> str:
"""Handle general queries with keyword search"""
invoices = data.get("invoices", [])
query_words = query.lower().split()
# Simple keyword matching
matching_invoices = []
for inv in invoices:
text_to_search = (
inv.get('supplier_name', '') + ' ' +
inv.get('buyer_name', '') + ' ' +
inv.get('product_description', '') + ' ' +
inv.get('extraction_info', {}).get('raw_text_preview', '')
).lower()
if any(word in text_to_search for word in query_words):
matching_invoices.append(inv)
if not matching_invoices:
return f"No invoices found matching '{query}'. Try different keywords or check the summary."
response = f"π **Found {len(matching_invoices)} invoices matching '{query}'**\n\n"
for i, inv in enumerate(matching_invoices[:5], 1):
response += f"{i}. **{inv.get('invoice_number', 'N/A')}** - {inv.get('supplier_name', 'Unknown')}\n"
response += f" β’ Amount: βΉ{inv.get('amount', 0):,.2f}\n"
response += f" β’ Date: {inv.get('date', 'N/A')}\n\n"
if len(matching_invoices) > 5:
response += f"... and {len(matching_invoices) - 5} more results."
return response
# ===============================================================================
# STREAMLIT APPLICATION
# ===============================================================================
def create_app():
"""Main Streamlit application"""
# Generate unique session ID for this run
if 'session_id' not in st.session_state:
st.session_state.session_id = str(uuid.uuid4())[:8]
session_id = st.session_state.session_id
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
text-align: center;
color: #FF6B35;
margin-bottom: 1rem;
}
.feature-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1rem;
border-radius: 10px;
color: white;
margin: 0.5rem 0;
text-align: center;
}
.status-ok { color: #28a745; font-weight: bold; }
.status-warning { color: #ffc107; font-weight: bold; }
.status-error { color: #dc3545; font-weight: bold; }
</style>
""", unsafe_allow_html=True)
# Header
st.markdown('<h1 class="main-header">π AI Invoice Processing System</h1>', unsafe_allow_html=True)
st.markdown("""
<div style="text-align: center; margin-bottom: 2rem;">
<p style="font-size: 1.1rem; color: #666;">
AI-Powered Document Processing β’ Semantic Search β’ Smart Analytics β’ Hugging Face Spaces
</p>
</div>
""", unsafe_allow_html=True)
# Initialize processor
if 'processor' not in st.session_state:
with st.spinner("π§ Initializing AI Invoice Processor..."):
try:
st.session_state.processor = InvoiceProcessor()
st.session_state.chatbot = ChatBot(st.session_state.processor)
st.session_state.chat_history = []
st.success("β
System initialized successfully!")
except Exception as e:
st.error(f"β Initialization failed: {e}")
st.stop()
# Sidebar
with st.sidebar:
st.header("ποΈ System Status")
processor = st.session_state.processor
# Component status
if processor.document_processor.processors:
st.markdown('<span class="status-ok">β
Document Processing</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="status-error">β Document Processing</span>', unsafe_allow_html=True)
if processor.ai_extractor.use_transformers:
st.markdown('<span class="status-ok">β
AI Extraction</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="status-warning">β οΈ Regex Extraction</span>', unsafe_allow_html=True)
if processor.vector_store and processor.vector_store.embedding_model:
st.markdown('<span class="status-ok">β
Semantic Search</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="status-warning">β οΈ Keyword Search Only</span>', unsafe_allow_html=True)
# Quick stats
st.header("π Quick Stats")
try:
data = processor.load_json_data()
total_invoices = len(data.get("invoices", []))
total_amount = data.get("summary", {}).get("total_amount", 0)
st.metric("Total Invoices", total_invoices)
st.metric("Total Value", f"βΉ{total_amount:,.2f}")
st.metric("Success Rate", f"{processor.processing_stats['successful']}/{processor.processing_stats['total_processed']}")
except Exception as e:
st.error(f"Stats error: {e}")
# System info
st.header("βοΈ System Info")
st.info(f"""
**Session ID:** {session_id}
**Limits:**
β’ Max file size: 10MB
β’ Max concurrent files: 3
β’ Timeout: 30s
""")
# Main navigation
selected_tab = st.radio(
"Choose a section:",
["π€ Upload & Process", "π¬ AI Chat", "π Analytics", "π Data Explorer"],
horizontal=True,
key=f"main_navigation_{session_id}"
)
# -------------------------------------------------------------------------
# UPLOAD & PROCESS SECTION
# -------------------------------------------------------------------------
if selected_tab == "π€ Upload & Process":
st.header("π€ Upload Invoice Documents")
# Feature highlights
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="feature-box">
<h4>π€ AI Extraction</h4>
<p>Advanced NLP models extract structured data automatically</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="feature-box">
<h4>π Smart Search</h4>
<p>Semantic search finds invoices using natural language</p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="feature-box">
<h4>π Analytics</h4>
<p>Comprehensive insights and visualizations</p>
</div>
""", unsafe_allow_html=True)
# File upload
st.markdown("### π Upload Your Invoices")
# Initialize session state for files if not exists
if f'uploaded_files_{session_id}' not in st.session_state:
st.session_state[f'uploaded_files_{session_id}'] = None
if f'processing_complete_{session_id}' not in st.session_state:
st.session_state[f'processing_complete_{session_id}'] = False
if f'currently_processing_{session_id}' not in st.session_state:
st.session_state[f'currently_processing_{session_id}'] = False
if f'processed_file_hashes_{session_id}' not in st.session_state:
st.session_state[f'processed_file_hashes_{session_id}'] = set()
# File uploader with stable key
uploaded_files = st.file_uploader(
"Choose invoice files (PDF, TXT supported)",
type=['pdf', 'txt'],
accept_multiple_files=True,
help="Maximum file size: 10MB per file",
key=f"file_uploader_stable_{session_id}"
)
# Store uploaded files in session state only if they're new
if uploaded_files:
# Create file hashes to detect if files have changed
current_file_hashes = set()
for file in uploaded_files:
file_hash = hash((file.name, file.size))
current_file_hashes.add(file_hash)
# Check if files have changed
stored_hashes = st.session_state.get(f'uploaded_file_hashes_{session_id}', set())
if current_file_hashes != stored_hashes:
st.session_state[f'uploaded_files_{session_id}'] = uploaded_files
st.session_state[f'uploaded_file_hashes_{session_id}'] = current_file_hashes
st.session_state[f'processing_complete_{session_id}'] = False
st.session_state[f'currently_processing_{session_id}'] = False
st.info("π New files detected - ready for processing")
# Get files from session state
current_files = st.session_state[f'uploaded_files_{session_id}']
is_processing = st.session_state[f'currently_processing_{session_id}']
is_complete = st.session_state[f'processing_complete_{session_id}']
if current_files:
max_files = 3
if len(current_files) > max_files:
st.warning(f"β οΈ Too many files selected. Processing first {max_files} files.")
current_files = current_files[:max_files]
st.info(f"π {len(current_files)} files selected")
# Show file names
st.markdown("**Selected Files:**")
for i, file in enumerate(current_files, 1):
file_size_mb = len(file.getvalue()) / (1024 * 1024)
file_hash = hash((file.name, file.size))
processed_icon = "β
" if file_hash in st.session_state[f'processed_file_hashes_{session_id}'] else "π"
st.write(f"{processed_icon} {i}. {file.name} ({file_size_mb:.2f} MB)")
# Process button - only show if not currently processing
col1, col2 = st.columns([1, 1])
with col1:
if not is_processing and not is_complete:
if st.button("π Process Files", type="primary", key=f"process_btn_{session_id}"):
st.session_state[f'currently_processing_{session_id}'] = True
st.rerun()
elif is_processing:
st.info("π Processing in progress...")
# Actually process the files here
process_files_once(current_files, session_id)
elif is_complete:
st.success("β
Processing completed!")
if st.button("π Process Again", key=f"reprocess_btn_{session_id}"):
st.session_state[f'processing_complete_{session_id}'] = False
st.session_state[f'currently_processing_{session_id}'] = False
st.session_state[f'processed_file_hashes_{session_id}'] = set()
st.rerun()
with col2:
if st.button("ποΈ Clear Files", key=f"clear_files_{session_id}"):
# Clear all session state related to files
keys_to_clear = [
f'uploaded_files_{session_id}',
f'uploaded_file_hashes_{session_id}',
f'processing_complete_{session_id}',
f'currently_processing_{session_id}',
f'processed_file_hashes_{session_id}'
]
for key in keys_to_clear:
if key in st.session_state:
del st.session_state[key]
st.success("ποΈ Files cleared successfully!")
time.sleep(1) # Brief pause to show message
st.rerun()
else:
st.info("π Please select invoice files to upload and process")
# Show processing results if completed
if is_complete:
st.markdown("### π Recent Processing Results")
try:
data = st.session_state.processor.load_json_data()
recent_invoices = sorted(
data.get("invoices", []),
key=lambda x: x.get('timestamps', {}).get('created_at', ''),
reverse=True
)[:5]
if recent_invoices:
for i, inv in enumerate(recent_invoices, 1):
with st.expander(f"π {inv.get('invoice_number', f'Invoice {i}')} - {inv.get('supplier_name', 'Unknown')}", expanded=False):
col1, col2 = st.columns(2)
with col1:
st.write(f"**Invoice #:** {inv.get('invoice_number', 'N/A')}")
st.write(f"**Supplier:** {inv.get('supplier_name', 'N/A')}")
st.write(f"**Amount:** βΉ{inv.get('amount', 0):.2f}")
with col2:
st.write(f"**Date:** {inv.get('date', 'N/A')}")
st.write(f"**Method:** {inv.get('extraction_info', {}).get('method', 'N/A')}")
st.write(f"**Confidence:** {inv.get('extraction_info', {}).get('confidence', 0):.1%}")
else:
st.info("No recent processing results found.")
except Exception as e:
st.error(f"Error loading recent results: {e}")
# -------------------------------------------------------------------------
# AI CHAT SECTION
# -------------------------------------------------------------------------
elif selected_tab == "π¬ AI Chat":
st.header("π¬ AI Chat Interface")
# Display chat history
if st.session_state.chat_history:
st.markdown("### π¬ Chat History")
for i, message in enumerate(st.session_state.chat_history):
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
st.markdown("### βοΈ Ask a Question")
col1, col2 = st.columns([4, 1])
with col1:
user_input = st.text_input(
"Type your question:",
placeholder="e.g., 'show me total spending'",
key=f"chat_input_{session_id}"
)
with col2:
ask_btn = st.button("π Ask", type="primary", key=f"ask_btn_{session_id}")
if ask_btn and user_input:
handle_chat_query(user_input)
# Suggested queries
if not st.session_state.chat_history:
st.markdown("### π‘ Try These Queries")
col1, col2 = st.columns(2)
with col1:
st.markdown("**π Basic Queries:**")
basic_queries = [
"Show me a summary of all invoices",
"How much have we spent in total?",
"Who are our top suppliers?",
"Find invoices with high amounts"
]
for i, query in enumerate(basic_queries):
if st.button(query, key=f"basic_{session_id}_{i}"):
handle_chat_query(query)
with col2:
st.markdown("**π Advanced Queries:**")
advanced_queries = [
"Find technology purchases",
"Show office supplies",
"Search consulting services",
"Recent high-value invoices"
]
for i, query in enumerate(advanced_queries):
if st.button(query, key=f"advanced_{session_id}_{i}"):
handle_chat_query(query)
# Clear chat
if st.session_state.chat_history:
if st.button("ποΈ Clear Chat", key=f"clear_chat_{session_id}"):
st.session_state.chat_history = []
st.rerun()
# -------------------------------------------------------------------------
# ANALYTICS SECTION
# -------------------------------------------------------------------------
elif selected_tab == "π Analytics":
st.header("π Analytics Dashboard")
try:
data = st.session_state.processor.load_json_data()
invoices = data.get("invoices", [])
if not invoices:
st.info("π No data available. Upload some invoices to see analytics.")
return
# Convert to DataFrame
df_data = []
for inv in invoices:
df_data.append({
'invoice_number': inv.get('invoice_number', ''),
'supplier_name': inv.get('supplier_name', ''),
'amount': inv.get('amount', 0),
'date': inv.get('date', ''),
'confidence': inv.get('extraction_info', {}).get('confidence', 0)
})
df = pd.DataFrame(df_data)
# Key metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Invoices", len(df))
with col2:
st.metric("Total Amount", f"βΉ{df['amount'].sum():,.2f}")
with col3:
st.metric("Avg Amount", f"βΉ{df['amount'].mean():,.2f}")
with col4:
st.metric("Unique Suppliers", df['supplier_name'].nunique())
# Visualizations
if len(df) > 0:
# Amount distribution
fig_hist = px.histogram(
df,
x='amount',
title="Invoice Amount Distribution",
labels={'amount': 'Amount (βΉ)', 'count': 'Number of Invoices'}
)
st.plotly_chart(fig_hist, use_container_width=True)
# Top suppliers
if df['supplier_name'].notna().any():
supplier_amounts = df.groupby('supplier_name')['amount'].sum().sort_values(ascending=False).head(10)
if len(supplier_amounts) > 0:
fig_suppliers = px.bar(
x=supplier_amounts.values,
y=supplier_amounts.index,
orientation='h',
title="Top 10 Suppliers by Total Amount",
labels={'x': 'Total Amount (βΉ)', 'y': 'Supplier'}
)
st.plotly_chart(fig_suppliers, use_container_width=True)
except Exception as e:
st.error(f"Analytics error: {e}")
# -------------------------------------------------------------------------
# DATA EXPLORER SECTION
# -------------------------------------------------------------------------
elif selected_tab == "π Data Explorer":
st.header("π Data Explorer")
try:
data = st.session_state.processor.load_json_data()
invoices = data.get("invoices", [])
if not invoices:
st.info("π No data available. Upload some invoices first.")
return
# Convert to DataFrame
df_data = []
for inv in invoices:
df_data.append({
'Invoice Number': inv.get('invoice_number', ''),
'Supplier': inv.get('supplier_name', ''),
'Buyer': inv.get('buyer_name', ''),
'Amount': inv.get('amount', 0),
'Date': inv.get('date', ''),
'Confidence': inv.get('extraction_info', {}).get('confidence', 0),
'Method': inv.get('extraction_info', {}).get('method', ''),
'File': inv.get('file_info', {}).get('file_name', ''),
'Created': inv.get('timestamps', {}).get('created_at', '')[:19]
})
df = pd.DataFrame(df_data)
# Filters
col1, col2, col3 = st.columns(3)
with col1:
suppliers = ['All'] + sorted(df['Supplier'].dropna().unique().tolist())
selected_supplier = st.selectbox("Filter by Supplier", suppliers, key=f"supplier_filter_{session_id}")
with col2:
methods = ['All'] + sorted(df['Method'].dropna().unique().tolist())
selected_method = st.selectbox("Filter by Method", methods, key=f"method_filter_{session_id}")
with col3:
min_amount = st.number_input("Min Amount", min_value=0.0, value=0.0, key=f"amount_filter_{session_id}")
# Apply filters
filtered_df = df.copy()
if selected_supplier != 'All':
filtered_df = filtered_df[filtered_df['Supplier'] == selected_supplier]
if selected_method != 'All':
filtered_df = filtered_df[filtered_df['Method'] == selected_method]
if min_amount > 0:
filtered_df = filtered_df[filtered_df['Amount'] >= min_amount]
# Display data
st.dataframe(
filtered_df,
use_container_width=True,
column_config={
"Amount": st.column_config.NumberColumn("Amount", format="βΉ%.2f"),
"Confidence": st.column_config.ProgressColumn("Confidence", min_value=0, max_value=1)
}
)
# Export options
col1, col2 = st.columns(2)
with col1:
if st.button("π₯ Export CSV", key=f"export_csv_{session_id}"):
csv_data = filtered_df.to_csv(index=False)
st.download_button(
"Download CSV",
csv_data,
f"invoices_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
"text/csv",
key=f"download_csv_{session_id}"
)
with col2:
if st.button("π Export JSON", key=f"export_json_{session_id}"):
filtered_invoices = [inv for inv in invoices
if inv.get('invoice_number') in filtered_df['Invoice Number'].values]
export_data = {
"exported_at": datetime.now().isoformat(),
"total_records": len(filtered_invoices),
"invoices": filtered_invoices
}
st.download_button(
"Download JSON",
json.dumps(export_data, indent=2),
f"invoices_{datetime.now().strftime('%Y%m%d_%H%M')}.json",
"application/json",
key=f"download_json_{session_id}"
)
except Exception as e:
st.error(f"Data explorer error: {e}")
# -------------------------------------------------------------------------
# GLOBAL CHAT INPUT
# -------------------------------------------------------------------------
st.markdown("---")
st.markdown("### π¬ Quick Chat (Works from any section)")
global_query = st.chat_input("Ask about your invoices...", key=f"global_chat_{session_id}")
if global_query:
handle_chat_query(global_query, show_response=True)
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666;">
<p>π <strong>AI Invoice Processing System</strong> - Optimized for Hugging Face Spaces</p>
<p>Built with β€οΈ using Streamlit, Transformers, and AI</p>
</div>
""", unsafe_allow_html=True)
# ===============================================================================
# HELPER FUNCTIONS
# ===============================================================================
def process_files_once(uploaded_files, session_id):
"""Process uploaded files only once with proper state management"""
if not uploaded_files:
st.error("No files to process!")
st.session_state[f'currently_processing_{session_id}'] = False
return
st.markdown("### π Processing Files...")
# Get already processed file hashes
processed_hashes = st.session_state[f'processed_file_hashes_{session_id}']
# Filter out already processed files
files_to_process = []
for file in uploaded_files:
file_hash = hash((file.name, file.size))
if file_hash not in processed_hashes:
files_to_process.append((file, file_hash))
if not files_to_process:
st.info("β
All files have already been processed!")
st.session_state[f'currently_processing_{session_id}'] = False
st.session_state[f'processing_complete_{session_id}'] = True
return
# Create containers for dynamic updates
progress_container = st.container()
status_container = st.container()
results_container = st.container()
successful = 0
failed = 0
# Show progress
with progress_container:
progress_bar = st.progress(0)
progress_text = st.empty()
with status_container:
st.info(f"Starting to process {len(files_to_process)} new files...")
# Process each file only once
for i, (uploaded_file, file_hash) in enumerate(files_to_process):
current_progress = (i + 1) / len(files_to_process)
with progress_container:
progress_bar.progress(current_progress)
progress_text.text(f"Processing file {i+1}/{len(files_to_process)}: {uploaded_file.name}")
with status_container:
st.info(f"π Processing: {uploaded_file.name} ({len(uploaded_file.getvalue())/1024:.1f} KB)")
try:
# Process the file
result = st.session_state.processor.process_uploaded_file(uploaded_file)
# Mark file as processed regardless of result
processed_hashes.add(file_hash)
# Show result immediately
with results_container:
if result and hasattr(result, 'invoice_number') and result.invoice_number:
successful += 1
st.success(f"β
Successfully processed: {uploaded_file.name}")
# Show extracted data
col1, col2, col3 = st.columns(3)
with col1:
st.write(f"**Invoice #:** {result.invoice_number}")
st.write(f"**Supplier:** {result.supplier_name or 'Not found'}")
with col2:
st.write(f"**Amount:** βΉ{result.amount:.2f}")
st.write(f"**Date:** {result.date or 'Not found'}")
with col3:
st.write(f"**Method:** {result.processing_method}")
st.write(f"**Confidence:** {result.extraction_confidence:.1%}")
st.markdown("---")
else:
failed += 1
st.warning(f"β οΈ Could not extract complete data from: {uploaded_file.name}")
if result:
st.write(f"Partial data: {result.supplier_name}, βΉ{result.amount}")
st.markdown("---")
except Exception as e:
failed += 1
# Still mark as processed to avoid reprocessing
processed_hashes.add(file_hash)
with results_container:
st.error(f"β Error processing {uploaded_file.name}: {str(e)}")
st.markdown("---")
# Update session state
st.session_state[f'processed_file_hashes_{session_id}'] = processed_hashes
# Final summary
with progress_container:
progress_bar.progress(1.0)
progress_text.text("β
Processing completed!")
with status_container:
if successful > 0:
st.success(f"π Processing complete! {successful} successful, {failed} failed")
if successful > 0:
st.balloons()
else:
st.error(f"β Processing failed for all {failed} files. Please check file formats and content.")
# Update processing state
st.session_state[f'currently_processing_{session_id}'] = False
st.session_state[f'processing_complete_{session_id}'] = True
# Force rerun to update UI
st.rerun()
def process_files(uploaded_files, session_id):
"""Legacy function - redirect to process_files_once"""
return process_files_once(uploaded_files, session_id)
def handle_chat_query(query, show_response=False):
"""Handle chat query"""
st.session_state.chat_history.append({
"role": "user",
"content": query,
"timestamp": datetime.now()
})
try:
with st.spinner("π€ AI is analyzing..."):
response = st.session_state.chatbot.query_database(query)
st.session_state.chat_history.append({
"role": "assistant",
"content": response,
"timestamp": datetime.now()
})
if show_response:
with st.chat_message("assistant"):
st.markdown(response)
st.info("π‘ Switch to the 'AI Chat' section to see full conversation history!")
st.rerun()
except Exception as e:
st.error(f"Chat error: {e}")
# ===============================================================================
# MAIN ENTRY POINT
# ===============================================================================
def main():
"""Main entry point for Hugging Face Spaces"""
try:
if IS_HF_SPACE:
st.sidebar.info("π€ Running on Hugging Face Spaces")
create_app()
except Exception as e:
st.error(f"""
## π¨ Application Error
{e}
Please refresh the page or check the logs for more details.
""")
if __name__ == "__main__":
main(),
# Standalone amounts with currency words
r'([0-9,]+\.?\d*)\s*(?:dollars?|rupees?|usd|inr|eur|gbp)',
# Table-like patterns
r'(?:price|cost|rate)\s*:?\s*[\$βΉΒ£β¬]?\s*([0-9,]+\.?\d*)',
# Amount with decimal precision
r'(?:^|\s)([0-9]{1,3}(?:,\d{3})*\.?\d{0,2})(?=\s|$)',
],
'date': [
r'date\s*:?\s*(\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4})',
r'(?:invoice|bill)\s*date\s*:?\s*(\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4})',
r'(?:^|\s)(\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4})(?=\s|$)',
r'(\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2})',
r'(\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+\d{2,4})',
],
'quantity': [
r'qty\s*:?\s*(\d+)',
r'quantity\s*:?\s*(\d+)',
r'(?:units?|pcs?|pieces?)\s*:?\s*(\d+)',
r'(\d+)\s*(?:pcs?|units?|items?|pieces?)',
]
}
text_lower = text.lower()
# Extract invoice number with multiple attempts
for pattern in patterns['invoice_number']:
match = re.search(pattern, text_lower, re.IGNORECASE | re.MULTILINE)
if match:
invoice_data.invoice_number = match.group(1).upper().strip()
break
# Extract amount with enhanced logic
amounts_found = []
for pattern in patterns['amount']:
matches = re.finditer(pattern, text_lower, re.IGNORECASE | re.MULTILINE)
for match in matches:
try:
amount_str = match.group(1).replace(',', '').replace(' ', '')
amount_val = float(amount_str)
if 0.01 <= amount_val <= 1000000: # Reasonable range
amounts_found.append(amount_val)
except (ValueError, IndexError):
continue
# Choose the most likely amount (highest value or most repeated)
if amounts_found:
# Remove duplicates and sort
unique_amounts = sorted(set(amounts_found), reverse=True)
# Take the highest reasonable amount
invoice_data.amount = unique_amounts[0]
# Extract date
for pattern in patterns['date']:
match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
if match:
invoice_data.date = self.parse_date(match.group(1))
break
# Extract quantity
for pattern in patterns['quantity']:
match = re.search(pattern, text_lower, re.IGNORECASE)
if match:
try:
invoice_data.quantity = int(match.group(1))
break
except ValueError:
continue
# Enhanced company name extraction
company_patterns = [
r'(?:from|supplier|vendor)\s*:?\s*([A-Z][A-Za-z\s&,\.]{3,50})',
r'(?:to|buyer|client)\s*:?\s*([A-Z][A-Za-z\s&,\.]{3,50})',
r'([A-Z][A-Za-z\s&,\.]{3,50})\s*(?:ltd|inc|corp|llc|co\.|company|pvt|private|limited)',
r'(?:^|\n)([A-Z][A-Za-z\s&,\.]{3,50})\s*(?:\n|$)',
]
companies_found = []
for pattern in company_patterns:
matches = re.findall(pattern, text, re.MULTILINE)
for match in matches:
clean_company = match.strip().title()
if len(clean_company) > 3 and not any(word in clean_company.lower() for word in ['total', 'amount', 'date', 'invoice']):
companies_found.append(clean_company)
# Assign companies (first as supplier, second as buyer)
if companies_found:
invoice_data.supplier_name = companies_found[0]
if len(companies_found) > 1:
invoice_data.buyer_name = companies_found[1]
# Extract product description
desc_patterns = [
r'(?:description|item|product|service)\s*:?\s*([A-Za-z0-9\s,.-]{10,200})',
r'(?:for|regarding)\s*:?\s*([A-Za-z0-9\s,.-]{10,200})',
]
for pattern in desc_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
desc = match.group(1).strip()
if len(desc) > 5:
invoice_data.product_description = desc[:200] # Limit length
break
# Set confidence based on how much we extracted
confidence_factors = []
if invoice_data.invoice_number:
confidence_factors.append(0.3)
if invoice_data.amount > 0:
confidence_factors.append(0.3)
if invoice_data.supplier_name:
confidence_factors.append(0.2)
if invoice_data.date:
confidence_factors.append(0.1)
if invoice_data.quantity > 0:
confidence_factors.append(0.1)
invoice_data.extraction_confidence = sum(confidence_factors)
return invoice_data
def parse_date(self, date_str: str) -> str:
"""Parse date to YYYY-MM-DD format"""
if not date_str:
return ""
formats = ['%Y-%m-%d', '%m/%d/%Y', '%d/%m/%Y', '%m-%d-%Y', '%d-%m-%Y', '%Y/%m/%d']
for fmt in formats:
try:
parsed_date = datetime.strptime(date_str, fmt)
return parsed_date.strftime('%Y-%m-%d')
except ValueError:
continue
return date_str
# ===============================================================================
# VECTOR STORE CLASS
# ===============================================================================
class VectorStore:
"""Simplified vector store for Hugging Face Spaces"""
def __init__(self, embedding_model: str = "all-MiniLM-L6-v2"):
self.embedding_model_name = embedding_model
self.vector_store_path = os.path.join(HF_CONFIG["data_dir"], "vectors.pkl")
self.metadata_path = os.path.join(HF_CONFIG["data_dir"], "metadata.pkl")
self.embedding_model = None
self.vectors = []
self.document_metadata = []
self.embedding_dimension = None
self.setup_embedding_model()
self.load_vector_store()
def setup_embedding_model(self):
"""Initialize the sentence transformer model"""
if not SENTENCE_TRANSFORMERS_AVAILABLE:
st.warning("β οΈ Sentence Transformers not available. Vector search disabled.")
return
try:
with st.spinner(f"Loading embedding model: {self.embedding_model_name}..."):
self.embedding_model = SentenceTransformer(
self.embedding_model_name,
cache_folder=HF_CONFIG["cache_dir"]
)
# Get embedding dimension
test_embedding = self.embedding_model.encode(["test"])
self.embedding_dimension = test_embedding.shape[0]
st.success(f"β
Embedding model loaded: {self.embedding_model_name}")
except Exception as e:
st.error(f"β Failed to load embedding model: {e}")
self.embedding_model = None
def load_vector_store(self):
"""Load existing vector store"""
try:
if os.path.exists(self.vector_store_path) and os.path.exists(self.metadata_path):
with open(self.vector_store_path, 'rb') as f:
self.vectors = pickle.load(f)
with open(self.metadata_path, 'rb') as f:
self.document_metadata = pickle.load(f)
st.success(f"β
Vector store loaded: {len(self.document_metadata)} documents")
else:
self.vectors = []
self.document_metadata = []
st.info("π New vector store initialized")
except Exception as e:
st.error(f"β Error loading vector store: {e}")
self.vectors = []
self.document_metadata = []
def save_vector_store(self):
"""Save vector store to disk"""
try:
with open(self.vector_store_path, 'wb') as f:
pickle.dump(self.vectors, f)
with open(self.metadata_path, 'wb') as f:
pickle.dump(self.document_metadata, f)
return True
except Exception as e:
st.error(f"Error saving vector store: {e}")
return False
def create_document_text(self, invoice_data: dict, raw_text: str = "") -> str:
"""Create searchable text from invoice data"""
text_parts = []
for field, value in invoice_data.items():
if value and field != 'id':
text_parts.append(f"{field}: {value}")
if raw_text:
text_parts.append(f"content: {raw_text[:300]}")
return " | ".join(text_parts)
def add_document(self, invoice_data: dict, raw_text: str = "") -> bool:
"""Add a document to the vector store"""
if not self.embedding_model:
return False
try:
document_text = self.create_document_text(invoice_data, raw_text)
# Generate embedding
embedding = self.embedding_model.encode(document_text, normalize_embeddings=True)
# Create metadata
metadata = {
'invoice_id': invoice_data.get('id', ''),
'invoice_number': invoice_data.get('invoice_number', ''),
'supplier_name': invoice_data.get('supplier_name', ''),
'buyer_name': invoice_data.get('buyer_name', ''),
'amount': invoice_data.get('amount', 0),
'date': invoice_data.get('date', ''),
'file_name': invoice_data.get('file_info', {}).get('file_name', ''),
'document_text': document_text[:200],
'timestamp': datetime.now().isoformat()
}
# Add to store
self.vectors.append(embedding)
self.document_metadata.append(metadata)
return True
except Exception as e:
st.error(f"Error adding document to vector store: {e}")
return False
def semantic_search(self, query: str, top_k: int = 5) -> List[VectorSearchResult]:
"""Perform semantic search using cosine similarity"""
if not self.embedding_model or not self.vectors:
return []
try:
# Generate query embedding
query_embedding = self.embedding_model.encode(query, normalize_embeddings=True)
# Calculate similarities
similarities = []
for i, doc_embedding in enumerate(self.vectors):
similarity = np.dot(query_embedding, doc_embedding)
similarities.append((similarity, i))
# Sort by similarity
similarities.sort(reverse=True)
# Return top results
results = []
for similarity, idx in similarities[:top_k]:
if similarity > 0.1: # Relevance threshold
metadata = self.document_metadata[idx]
result = VectorSearchResult(
invoice_id=metadata.get('invoice_id', ''),
invoice_number=metadata.get('invoice_number', ''),
supplier_name=metadata.get('supplier_name', ''),
similarity_score=float(similarity),
content_preview=metadata.get('document_text', ''),
metadata=metadata
)
results.append(result)
return results
except Exception as e:
st.error(f"Error in semantic search: {e}")
return []
# ===============================================================================
# MAIN PROCESSOR CLASS
# ===============================================================================
class InvoiceProcessor:
"""Main invoice processor for Hugging Face Spaces"""
def __init__(self):
self.setup_storage()
self.document_processor = DocumentProcessor()
self.ai_extractor = AIExtractor()
self.vector_store = VectorStore() if SENTENCE_TRANSFORMERS_AVAILABLE else None
# Initialize stats
self.processing_stats = {
'total_processed': 0,
'successful': 0,
'failed': 0,
'start_time': datetime.now()
}
def setup_storage(self):
"""Setup storage paths"""
self.data_dir = HF_CONFIG["data_dir"]
self.json_path = os.path.join(self.data_dir, "invoices.json")
# Initialize JSON storage
if not os.path.exists(self.json_path):
initial_data = {
"metadata": {
"created_at": datetime.now().isoformat(),
"version": "hf_v1.0",
"total_invoices": 0
},
"invoices": [],
"summary": {
"total_amount": 0.0,
"unique_suppliers": [],
"processing_stats": {"successful": 0, "failed": 0}
}
}
self.save_json_data(initial_data)
def load_json_data(self) -> dict:
"""Load invoice data from JSON"""
try:
with open(self.json_path, 'r', encoding='utf-8') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
self.setup_storage()
return self.load_json_data()
def save_json_data(self, data: dict):
"""Save invoice data to JSON"""
try:
with open(self.json_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
except Exception as e:
st.error(f"Error saving data: {e}")
def process_uploaded_file(self, uploaded_file) -> InvoiceData:
"""Process a single uploaded file with enhanced debugging"""
self.processing_stats['total_processed'] += 1
try:
# Debug file info
file_size = len(uploaded_file.getvalue())
file_extension = uploaded_file.name.split('.')[-1].lower() if '.' in uploaded_file.name else 'unknown'
st.info(f"π Processing: {uploaded_file.name} ({file_size/1024:.1f} KB, .{file_extension})")
# Check file size
if file_size > HF_CONFIG["max_file_size_mb"] * 1024 * 1024:
error_msg = f"File too large: {file_size / 1024 / 1024:.2f}MB > {HF_CONFIG['max_file_size_mb']}MB"
st.error(error_msg)
self.processing_stats['failed'] += 1
return InvoiceData()
# Check file type
if file_extension not in ['pdf', 'txt']:
error_msg = f"Unsupported file type: .{file_extension} (supported: PDF, TXT)"
st.warning(error_msg)
self.processing_stats['failed'] += 1
return InvoiceData()
# Save temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_extension}") as tmp_file:
file_content = uploaded_file.getvalue()
tmp_file.write(file_content)
tmp_file_path = tmp_file.name
st.info(f"πΎ Saved temporarily to: {tmp_file_path}")
try:
# Extract text
st.info("π Extracting text from document...")
text = self.document_processor.extract_text_from_document(tmp_file_path)
if not text or not text.strip():
st.warning(f"β No text extracted from {uploaded_file.name}")
self.processing_stats['failed'] += 1
return InvoiceData()
text_length = len(text)
st.info(f"π Extracted {text_length} characters of text")
# Show text preview
if text_length > 0:
with st.expander("π Text Preview (First 500 characters)", expanded=False):
st.text(text[:500] + "..." if len(text) > 500 else text)
# Extract invoice data
st.info("π€ Extracting invoice data using AI/Regex...")
invoice_data = self.ai_extractor.extract_with_ai(text)
invoice_data.file_path = uploaded_file.name
# Show extraction results
st.info(f"π Extraction completed with {invoice_data.extraction_confidence:.1%} confidence")
# Save to storage
st.info("πΎ Saving extracted data...")
self.save_invoice_data(invoice_data, text, file_size)
self.processing_stats['successful'] += 1
st.success(f"β
Successfully processed {uploaded_file.name}")
return invoice_data
finally:
# Cleanup
try:
os.unlink(tmp_file_path)
st.info("π§Ή Cleaned up temporary file")
except:
pass
except Exception as e:
error_msg = f"Error processing {uploaded_file.name}: {str(e)}"
st.error(error_msg)
self.processing_stats['failed'] += 1
# Show detailed error for debugging
with st.expander("π Error Details", expanded=False):
st.code(str(e))
import traceback
st.code(traceback.format_exc())
return InvoiceData()
def save_invoice_data(self, invoice_data: InvoiceData, raw_text: str, file_size: int):
"""Save invoice data to JSON and vector store"""
try:
# Load existing data
data = self.load_json_data()
# Create invoice record
invoice_record = {
"id": len(data["invoices"]) + 1,
"invoice_number": invoice_data.invoice_number,
"supplier_name": invoice_data.supplier_name,
"buyer_name": invoice_data.buyer_name,
"date": invoice_data.date,
"amount": invoice_data.amount,
"quantity": invoice_data.quantity,
"product_description": invoice_data.product_description,
"file_info": {
"file_name": invoice_data.file_path,
"file_size": file_size
},
"extraction_info": {
"confidence": invoice_data.extraction_confidence,
"method": invoice_data.processing_method,
"raw_text_preview": raw_text[:300]
},
"timestamps": {
"created_at": datetime.now().isoformat()
}
}
# Add to invoices
data["invoices"].append(invoice_record)
# Update summary
self.update_summary(data)
# Save JSON
self.save_json_data(data)
# Add to vector store
if self.vector_store:
self.vector_store.add_document(invoice_record, raw_text)
self.vector_store.save_vector_store()
except Exception as e:
st.error(f"Error saving invoice data: {e}")
def update_summary(self, data: dict):
"""Update summary statistics"""
invoices = data["invoices"]
total_amount = sum(inv.get("amount", 0) for inv in invoices)
unique_suppliers = list(set(inv.get("supplier_name", "") for inv in invoices if inv.get("supplier_name")))
data["summary"] = {
"total_amount": total_amount,
"unique_suppliers": unique_suppliers,
"processing_stats": {
"successful": self.processing_stats['successful'],
"failed": self.processing_stats['failed'],
"total_processed": self.processing_stats['total_processed']
}
}
data["metadata"]["last_updated"] = datetime.now().isoformat()
data["metadata"]["total_invoices"] = len(invoices)
# ===============================================================================
# CHATBOT CLASS
# ===============================================================================
class ChatBot:
"""Chatbot for invoice queries"""
def __init__(self, processor: InvoiceProcessor):
self.processor = processor
def query_database(self, query: str) -> str:
"""Process user query and return response"""
try:
data = self.processor.load_json_data()
invoices = data.get("invoices", [])
if not invoices:
return "No invoice data found. Please upload some invoices first."
query_lower = query.lower()
# Handle different query types
if any(phrase in query_lower for phrase in ["summary", "overview", "total"]):
return self.generate_summary(data)
elif "count" in query_lower or "how many" in query_lower:
return self.handle_count_query(data)
elif any(phrase in query_lower for phrase in ["amount", "value", "money", "cost"]):
return self.handle_amount_query(data)
elif any(phrase in query_lower for phrase in ["supplier", "vendor", "company"]):
return self.handle_supplier_query(data, query)
elif self.processor.vector_store:
return self.handle_semantic_search(query)
else:
return self.handle_general_query(data, query)
except Exception as e:
return f"Error processing query: {e}"
def generate_summary(self, data: dict) -> str:
"""Generate comprehensive summary"""
invoices = data.get("invoices", [])
summary = data.get("summary", {})
if not invoices:
return "No invoices found in the system."
total_amount = summary.get("total_amount", 0)
avg_amount = total_amount / len(invoices) if invoices else 0
unique_suppliers = len(summary.get("unique_suppliers", []))
response = f"""
**π Invoice System Summary**
β’ **Total Invoices**: {len(invoices):,}
β’ **Total Value**: βΉ{total_amount:,.2f}
β’ **Average Invoice**: βΉ{avg_amount:,.2f}
β’ **Unique Suppliers**: {unique_suppliers}
**π Processing Stats**
β’ **Successful**: {summary.get('processing_stats', {}).get('successful', 0)}
β’ **Failed**: {summary.get('processing_stats', {}).get('failed', 0)}
**π Recent Invoices**
"""
# Show recent invoices
recent = sorted(invoices, key=lambda x: x.get('timestamps', {}).get('created_at', ''), reverse=True)[:5]
for i, inv in enumerate(recent, 1):
response += f"\n{i}. **{inv.get('invoice_number', 'N/A')}** - {inv.get('supplier_name', 'Unknown')} (βΉ{inv.get('amount', 0):,.2f})"
return response
def handle_count_query(self, data: dict) -> str:
"""Handle count-related queries"""
invoices = data.get("invoices", [])
total = len(invoices)
unique_numbers = len(set(inv.get('invoice_number', '') for inv in invoices if inv.get('invoice_number')))
return f"""
**π Invoice Count Summary**
β’ **Total Records**: {total}
β’ **Unique Invoice Numbers**: {unique_numbers}
β’ **Duplicates**: {total - unique_numbers if total > unique_numbers else 0}
**π
Processing Timeline**
β’ **First Invoice**: {invoices[0].get('timestamps', {}).get('created_at', 'N/A')[:10] if invoices else 'N/A'}
β’ **Latest Invoice**: {invoices[-1].get('timestamps', {}).get('created_at', 'N/A')[:10] if invoices else 'N/A'}
"""
def handle_amount_query(self, data: dict) -> str:
"""Handle amount-related queries"""
invoices = data.get("invoices", [])
amounts = [inv.get('amount', 0) for inv in invoices if inv.get('amount', 0) > 0]
if not amounts:
return "No amount information found in invoices."
total_amount = sum(amounts)
avg_amount = total_amount / len(amounts)
max_amount = max(amounts)
min_amount = min(amounts)
# Find high-value invoices
high_value_threshold = sorted(amounts, reverse=True)[min(4, len(amounts)-1)] if len(amounts) > 5 else max_amount
high_value_invoices = [inv for inv in invoices if inv.get('amount', 0) >= high_value_threshold]
response = f"""
**π° Financial Analysis**
β’ **Total Amount**: βΉ{total_amount:,.2f}
β’ **Average Amount**: βΉ{avg_amount:,.2f}
β’ **Highest Invoice**: βΉ{max_amount:,.2f}
β’ **Lowest Invoice**: βΉ{min_amount:,.2f}
**π― High-Value Invoices (βΉ{high_value_threshold:,.2f}+)**
"""
for i, inv in enumerate(high_value_invoices[:5], 1):
response += f"\n{i}. **{inv.get('invoice_number', 'N/A')}** - {inv.get('supplier_name', 'Unknown')} (βΉ{inv.get('amount', 0):,.2f})"
return response
def handle_supplier_query(self, data: dict, query: str) -> str:
"""Handle supplier-related queries"""
invoices = data.get("invoices", [])
# Count invoices by supplier
supplier_counts = {}
supplier_amounts = {}
for inv in invoices:
supplier = inv.get('supplier_name', '').strip()
if supplier:
supplier_counts[supplier] = supplier_counts.get(supplier, 0) + 1
supplier_amounts[supplier] = supplier_amounts.get(supplier, 0) + inv.get('amount', 0)
if not supplier_counts:
return "No supplier information found in invoices."
# Sort suppliers by amount
top_suppliers = sorted(supplier_amounts.items(), key=lambda x: x[1], reverse=True)[:10]
response = f"""
**π’ Supplier Analysis**
β’ **Total Unique Suppliers**: {len(supplier_counts)}
β’ **Most Active**: {max(supplier_counts, key=supplier_counts.get)} ({supplier_counts[max(supplier_counts, key=supplier_counts.get)]} invoices)
**π° Top Suppliers by Amount**
"""
for i, (supplier, amount) in enumerate(top_suppliers, 1):
count = supplier_counts[supplier]
avg = amount / count if count > 0 else 0
response += f"\n{i}. **{supplier}** - βΉ{amount:,.2f} ({count} invoices, avg: βΉ{avg:,.2f})"
return response
def handle_semantic_search(self, query: str) -> str:
"""Handle semantic search queries"""
try:
results = self.processor.vector_store.semantic_search(query, top_k=5)
if not results:
return f"No relevant results found for '{query}'. Try different keywords."
response = f"π **Semantic Search Results for '{query}'**\n\n"
for i, result in enumerate(results, 1):
response += f"{i}. **{result.invoice_number}** - {result.supplier_name}\n"
response += f" β’ Similarity: {result.similarity_score:.3f}\n"
response += f" β’ Amount: βΉ{result.metadata.get('amount', 0):,.2f}\n"
response += f" β’ Preview: {result.content_preview[:100]}...\n\n"
return response
except Exception as e:
return f"Semantic search error: {e}"
def handle_general_query(self, data: dict, query: str) -> str:
"""Handle general queries with keyword search"""
invoices = data.get("invoices", [])
query_words = query.lower().split()
# Simple keyword matching
matching_invoices = []
for inv in invoices:
text_to_search = (
inv.get('supplier_name', '') + ' ' +
inv.get('buyer_name', '') + ' ' +
inv.get('product_description', '') + ' ' +
inv.get('extraction_info', {}).get('raw_text_preview', '')
).lower()
if any(word in text_to_search for word in query_words):
matching_invoices.append(inv)
if not matching_invoices:
return f"No invoices found matching '{query}'. Try different keywords or check the summary."
response = f"π **Found {len(matching_invoices)} invoices matching '{query}'**\n\n"
for i, inv in enumerate(matching_invoices[:5], 1):
response += f"{i}. **{inv.get('invoice_number', 'N/A')}** - {inv.get('supplier_name', 'Unknown')}\n"
response += f" β’ Amount: βΉ{inv.get('amount', 0):,.2f}\n"
response += f" β’ Date: {inv.get('date', 'N/A')}\n\n"
if len(matching_invoices) > 5:
response += f"... and {len(matching_invoices) - 5} more results."
return response
# ===============================================================================
# STREAMLIT APPLICATION
# ===============================================================================
def create_app():
"""Main Streamlit application"""
# Generate unique session ID for this run
if 'session_id' not in st.session_state:
st.session_state.session_id = str(uuid.uuid4())[:8]
session_id = st.session_state.session_id
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
text-align: center;
color: #FF6B35;
margin-bottom: 1rem;
}
.feature-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1rem;
border-radius: 10px;
color: white;
margin: 0.5rem 0;
text-align: center;
}
.status-ok { color: #28a745; font-weight: bold; }
.status-warning { color: #ffc107; font-weight: bold; }
.status-error { color: #dc3545; font-weight: bold; }
</style>
""", unsafe_allow_html=True)
# Header
st.markdown('<h1 class="main-header">π AI Invoice Processing System</h1>', unsafe_allow_html=True)
st.markdown("""
<div style="text-align: center; margin-bottom: 2rem;">
<p style="font-size: 1.1rem; color: #666;">
AI-Powered Document Processing β’ Semantic Search β’ Smart Analytics β’ Hugging Face Spaces
</p>
</div>
""", unsafe_allow_html=True)
# Initialize processor
if 'processor' not in st.session_state:
with st.spinner("π§ Initializing AI Invoice Processor..."):
try:
st.session_state.processor = InvoiceProcessor()
st.session_state.chatbot = ChatBot(st.session_state.processor)
st.session_state.chat_history = []
st.success("β
System initialized successfully!")
except Exception as e:
st.error(f"β Initialization failed: {e}")
st.stop()
# Sidebar
with st.sidebar:
st.header("ποΈ System Status")
processor = st.session_state.processor
# Component status
if processor.document_processor.processors:
st.markdown('<span class="status-ok">β
Document Processing</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="status-error">β Document Processing</span>', unsafe_allow_html=True)
if processor.ai_extractor.use_transformers:
st.markdown('<span class="status-ok">β
AI Extraction</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="status-warning">β οΈ Regex Extraction</span>', unsafe_allow_html=True)
if processor.vector_store and processor.vector_store.embedding_model:
st.markdown('<span class="status-ok">β
Semantic Search</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="status-warning">β οΈ Keyword Search Only</span>', unsafe_allow_html=True)
# Quick stats
st.header("π Quick Stats")
try:
data = processor.load_json_data()
total_invoices = len(data.get("invoices", []))
total_amount = data.get("summary", {}).get("total_amount", 0)
st.metric("Total Invoices", total_invoices)
st.metric("Total Value", f"βΉ{total_amount:,.2f}")
st.metric("Success Rate", f"{processor.processing_stats['successful']}/{processor.processing_stats['total_processed']}")
except Exception as e:
st.error(f"Stats error: {e}")
# System info
st.header("βοΈ System Info")
st.info(f"""
**Session ID:** {session_id}
**Limits:**
β’ Max file size: 10MB
β’ Max concurrent files: 3
β’ Timeout: 30s
""")
# Main navigation
selected_tab = st.radio(
"Choose a section:",
["π€ Upload & Process", "π¬ AI Chat", "π Analytics", "π Data Explorer"],
horizontal=True,
key=f"main_navigation_{session_id}"
)
# -------------------------------------------------------------------------
# UPLOAD & PROCESS SECTION
# -------------------------------------------------------------------------
if selected_tab == "π€ Upload & Process":
st.header("π€ Upload Invoice Documents")
# Feature highlights
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="feature-box">
<h4>π€ AI Extraction</h4>
<p>Advanced NLP models extract structured data automatically</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="feature-box">
<h4>π Smart Search</h4>
<p>Semantic search finds invoices using natural language</p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="feature-box">
<h4>π Analytics</h4>
<p>Comprehensive insights and visualizations</p>
</div>
""", unsafe_allow_html=True)
# File upload
st.markdown("### π Upload Your Invoices")
# Initialize session state for files if not exists
if f'uploaded_files_{session_id}' not in st.session_state:
st.session_state[f'uploaded_files_{session_id}'] = None
if f'processing_complete_{session_id}' not in st.session_state:
st.session_state[f'processing_complete_{session_id}'] = False
if f'currently_processing_{session_id}' not in st.session_state:
st.session_state[f'currently_processing_{session_id}'] = False
if f'processed_file_hashes_{session_id}' not in st.session_state:
st.session_state[f'processed_file_hashes_{session_id}'] = set()
# File uploader with stable key
uploaded_files = st.file_uploader(
"Choose invoice files (PDF, TXT supported)",
type=['pdf', 'txt'],
accept_multiple_files=True,
help="Maximum file size: 10MB per file",
key=f"file_uploader_stable_{session_id}"
)
# Store uploaded files in session state only if they're new
if uploaded_files:
# Create file hashes to detect if files have changed
current_file_hashes = set()
for file in uploaded_files:
file_hash = hash((file.name, file.size))
current_file_hashes.add(file_hash)
# Check if files have changed
stored_hashes = st.session_state.get(f'uploaded_file_hashes_{session_id}', set())
if current_file_hashes != stored_hashes:
st.session_state[f'uploaded_files_{session_id}'] = uploaded_files
st.session_state[f'uploaded_file_hashes_{session_id}'] = current_file_hashes
st.session_state[f'processing_complete_{session_id}'] = False
st.session_state[f'currently_processing_{session_id}'] = False
st.info("π New files detected - ready for processing")
# Get files from session state
current_files = st.session_state[f'uploaded_files_{session_id}']
is_processing = st.session_state[f'currently_processing_{session_id}']
is_complete = st.session_state[f'processing_complete_{session_id}']
if current_files:
max_files = 3
if len(current_files) > max_files:
st.warning(f"β οΈ Too many files selected. Processing first {max_files} files.")
current_files = current_files[:max_files]
st.info(f"π {len(current_files)} files selected")
# Show file names
st.markdown("**Selected Files:**")
for i, file in enumerate(current_files, 1):
file_size_mb = len(file.getvalue()) / (1024 * 1024)
file_hash = hash((file.name, file.size))
processed_icon = "β
" if file_hash in st.session_state[f'processed_file_hashes_{session_id}'] else "π"
st.write(f"{processed_icon} {i}. {file.name} ({file_size_mb:.2f} MB)")
# Process button - only show if not currently processing
col1, col2 = st.columns([1, 1])
with col1:
if not is_processing and not is_complete:
if st.button("π Process Files", type="primary", key=f"process_btn_{session_id}"):
st.session_state[f'currently_processing_{session_id}'] = True
st.rerun()
elif is_processing:
st.info("π Processing in progress...")
# Actually process the files here
process_files_once(current_files, session_id)
elif is_complete:
st.success("β
Processing completed!")
if st.button("π Process Again", key=f"reprocess_btn_{session_id}"):
st.session_state[f'processing_complete_{session_id}'] = False
st.session_state[f'currently_processing_{session_id}'] = False
st.session_state[f'processed_file_hashes_{session_id}'] = set()
st.rerun()
with col2:
if st.button("ποΈ Clear Files", key=f"clear_files_{session_id}"):
st.session_state[f'uploaded_files_{session_id}'] = None
st.session_state[f'uploaded_file_hashes_{session_id}'] = set()
st.session_state[f'processing_complete_{session_id}'] = False
st.session_state[f'currently_processing_{session_id}'] = False
st.session_state[f'processed_file_hashes_{session_id}'] = set()
st.rerun()
else:
st.info("π Please select invoice files to upload and process")
# Show processing results if completed
if is_complete:
st.markdown("### π Recent Processing Results")
try:
data = st.session_state.processor.load_json_data()
recent_invoices = sorted(
data.get("invoices", []),
key=lambda x: x.get('timestamps', {}).get('created_at', ''),
reverse=True
)[:5]
if recent_invoices:
for i, inv in enumerate(recent_invoices, 1):
with st.expander(f"π {inv.get('invoice_number', f'Invoice {i}')} - {inv.get('supplier_name', 'Unknown')}", expanded=False):
col1, col2 = st.columns(2)
with col1:
st.write(f"**Invoice #:** {inv.get('invoice_number', 'N/A')}")
st.write(f"**Supplier:** {inv.get('supplier_name', 'N/A')}")
st.write(f"**Amount:** βΉ{inv.get('amount', 0):.2f}")
with col2:
st.write(f"**Date:** {inv.get('date', 'N/A')}")
st.write(f"**Method:** {inv.get('extraction_info', {}).get('method', 'N/A')}")
st.write(f"**Confidence:** {inv.get('extraction_info', {}).get('confidence', 0):.1%}")
else:
st.info("No recent processing results found.")
except Exception as e:
st.error(f"Error loading recent results: {e}")
# -------------------------------------------------------------------------
# AI CHAT SECTION
# -------------------------------------------------------------------------
elif selected_tab == "π¬ AI Chat":
st.header("π¬ AI Chat Interface")
# Display chat history
if st.session_state.chat_history:
st.markdown("### π¬ Chat History")
for i, message in enumerate(st.session_state.chat_history):
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
st.markdown("### βοΈ Ask a Question")
col1, col2 = st.columns([4, 1])
with col1:
user_input = st.text_input(
"Type your question:",
placeholder="e.g., 'show me total spending'",
key=f"chat_input_{session_id}"
)
with col2:
ask_btn = st.button("π Ask", type="primary", key=f"ask_btn_{session_id}")
if ask_btn and user_input:
handle_chat_query(user_input)
# Suggested queries
if not st.session_state.chat_history:
st.markdown("### π‘ Try These Queries")
col1, col2 = st.columns(2)
with col1:
st.markdown("**π Basic Queries:**")
basic_queries = [
"Show me a summary of all invoices",
"How much have we spent in total?",
"Who are our top suppliers?",
"Find invoices with high amounts"
]
for i, query in enumerate(basic_queries):
if st.button(query, key=f"basic_{session_id}_{i}"):
handle_chat_query(query)
with col2:
st.markdown("**π Advanced Queries:**")
advanced_queries = [
"Find technology purchases",
"Show office supplies",
"Search consulting services",
"Recent high-value invoices"
]
for i, query in enumerate(advanced_queries):
if st.button(query, key=f"advanced_{session_id}_{i}"):
handle_chat_query(query)
# Clear chat
if st.session_state.chat_history:
if st.button("ποΈ Clear Chat", key=f"clear_chat_{session_id}"):
st.session_state.chat_history = []
st.rerun()
# -------------------------------------------------------------------------
# ANALYTICS SECTION
# -------------------------------------------------------------------------
elif selected_tab == "π Analytics":
st.header("π Analytics Dashboard")
try:
data = st.session_state.processor.load_json_data()
invoices = data.get("invoices", [])
if not invoices:
st.info("π No data available. Upload some invoices to see analytics.")
return
# Convert to DataFrame
df_data = []
for inv in invoices:
df_data.append({
'invoice_number': inv.get('invoice_number', ''),
'supplier_name': inv.get('supplier_name', ''),
'amount': inv.get('amount', 0),
'date': inv.get('date', ''),
'confidence': inv.get('extraction_info', {}).get('confidence', 0)
})
df = pd.DataFrame(df_data)
# Key metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Invoices", len(df))
with col2:
st.metric("Total Amount", f"βΉ{df['amount'].sum():,.2f}")
with col3:
st.metric("Avg Amount", f"βΉ{df['amount'].mean():,.2f}")
with col4:
st.metric("Unique Suppliers", df['supplier_name'].nunique())
# Visualizations
if len(df) > 0:
# Amount distribution
fig_hist = px.histogram(
df,
x='amount',
title="Invoice Amount Distribution",
labels={'amount': 'Amount (βΉ)', 'count': 'Number of Invoices'}
)
st.plotly_chart(fig_hist, use_container_width=True)
# Top suppliers
if df['supplier_name'].notna().any():
supplier_amounts = df.groupby('supplier_name')['amount'].sum().sort_values(ascending=False).head(10)
if len(supplier_amounts) > 0:
fig_suppliers = px.bar(
x=supplier_amounts.values,
y=supplier_amounts.index,
orientation='h',
title="Top 10 Suppliers by Total Amount",
labels={'x': 'Total Amount (βΉ)', 'y': 'Supplier'}
)
st.plotly_chart(fig_suppliers, use_container_width=True)
except Exception as e:
st.error(f"Analytics error: {e}")
# -------------------------------------------------------------------------
# DATA EXPLORER SECTION
# -------------------------------------------------------------------------
elif selected_tab == "π Data Explorer":
st.header("π Data Explorer")
try:
data = st.session_state.processor.load_json_data()
invoices = data.get("invoices", [])
if not invoices:
st.info("π No data available. Upload some invoices first.")
return
# Convert to DataFrame
df_data = []
for inv in invoices:
df_data.append({
'Invoice Number': inv.get('invoice_number', ''),
'Supplier': inv.get('supplier_name', ''),
'Buyer': inv.get('buyer_name', ''),
'Amount': inv.get('amount', 0),
'Date': inv.get('date', ''),
'Confidence': inv.get('extraction_info', {}).get('confidence', 0),
'Method': inv.get('extraction_info', {}).get('method', ''),
'File': inv.get('file_info', {}).get('file_name', ''),
'Created': inv.get('timestamps', {}).get('created_at', '')[:19]
})
df = pd.DataFrame(df_data)
# Filters
col1, col2, col3 = st.columns(3)
with col1:
suppliers = ['All'] + sorted(df['Supplier'].dropna().unique().tolist())
selected_supplier = st.selectbox("Filter by Supplier", suppliers, key=f"supplier_filter_{session_id}")
with col2:
methods = ['All'] + sorted(df['Method'].dropna().unique().tolist())
selected_method = st.selectbox("Filter by Method", methods, key=f"method_filter_{session_id}")
with col3:
min_amount = st.number_input("Min Amount", min_value=0.0, value=0.0, key=f"amount_filter_{session_id}")
# Apply filters
filtered_df = df.copy()
if selected_supplier != 'All':
filtered_df = filtered_df[filtered_df['Supplier'] == selected_supplier]
if selected_method != 'All':
filtered_df = filtered_df[filtered_df['Method'] == selected_method]
if min_amount > 0:
filtered_df = filtered_df[filtered_df['Amount'] >= min_amount]
# Display data
st.dataframe(
filtered_df,
use_container_width=True,
column_config={
"Amount": st.column_config.NumberColumn("Amount", format="βΉ%.2f"),
"Confidence": st.column_config.ProgressColumn("Confidence", min_value=0, max_value=1)
}
)
# Export options
col1, col2 = st.columns(2)
with col1:
if st.button("π₯ Export CSV", key=f"export_csv_{session_id}"):
csv_data = filtered_df.to_csv(index=False)
st.download_button(
"Download CSV",
csv_data,
f"invoices_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
"text/csv",
key=f"download_csv_{session_id}"
)
with col2:
if st.button("π Export JSON", key=f"export_json_{session_id}"):
filtered_invoices = [inv for inv in invoices
if inv.get('invoice_number') in filtered_df['Invoice Number'].values]
export_data = {
"exported_at": datetime.now().isoformat(),
"total_records": len(filtered_invoices),
"invoices": filtered_invoices
}
st.download_button(
"Download JSON",
json.dumps(export_data, indent=2),
f"invoices_{datetime.now().strftime('%Y%m%d_%H%M')}.json",
"application/json",
key=f"download_json_{session_id}"
)
except Exception as e:
st.error(f"Data explorer error: {e}")
# -------------------------------------------------------------------------
# GLOBAL CHAT INPUT
# -------------------------------------------------------------------------
st.markdown("---")
st.markdown("### π¬ Quick Chat (Works from any section)")
global_query = st.chat_input("Ask about your invoices...", key=f"global_chat_{session_id}")
if global_query:
handle_chat_query(global_query, show_response=True)
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666;">
<p>π <strong>AI Invoice Processing System</strong> - Optimized for Hugging Face Spaces</p>
<p>Built with β€οΈ using Streamlit, Transformers, and AI</p>
</div>
""", unsafe_allow_html=True)
# ===============================================================================
# HELPER FUNCTIONS
# ===============================================================================
def process_files_once(uploaded_files, session_id):
"""Process uploaded files only once with proper state management"""
if not uploaded_files:
st.error("No files to process!")
st.session_state[f'currently_processing_{session_id}'] = False
return
st.markdown("### π Processing Files...")
# Get already processed file hashes
processed_hashes = st.session_state[f'processed_file_hashes_{session_id}']
# Filter out already processed files
files_to_process = []
for file in uploaded_files:
file_hash = hash((file.name, file.size))
if file_hash not in processed_hashes:
files_to_process.append((file, file_hash))
if not files_to_process:
st.info("β
All files have already been processed!")
st.session_state[f'currently_processing_{session_id}'] = False
st.session_state[f'processing_complete_{session_id}'] = True
return
# Create containers for dynamic updates
progress_container = st.container()
status_container = st.container()
results_container = st.container()
successful = 0
failed = 0
# Show progress
with progress_container:
progress_bar = st.progress(0)
progress_text = st.empty()
with status_container:
st.info(f"Starting to process {len(files_to_process)} new files...")
# Process each file only once
for i, (uploaded_file, file_hash) in enumerate(files_to_process):
current_progress = (i + 1) / len(files_to_process)
with progress_container:
progress_bar.progress(current_progress)
progress_text.text(f"Processing file {i+1}/{len(files_to_process)}: {uploaded_file.name}")
with status_container:
st.info(f"π Processing: {uploaded_file.name} ({len(uploaded_file.getvalue())/1024:.1f} KB)")
try:
# Process the file
result = st.session_state.processor.process_uploaded_file(uploaded_file)
# Mark file as processed regardless of result
processed_hashes.add(file_hash)
# Show result immediately
with results_container:
if result and hasattr(result, 'invoice_number') and result.invoice_number:
successful += 1
st.success(f"β
Successfully processed: {uploaded_file.name}")
# Show extracted data
col1, col2, col3 = st.columns(3)
with col1:
st.write(f"**Invoice #:** {result.invoice_number}")
st.write(f"**Supplier:** {result.supplier_name or 'Not found'}")
with col2:
st.write(f"**Amount:** βΉ{result.amount:.2f}")
st.write(f"**Date:** {result.date or 'Not found'}")
with col3:
st.write(f"**Method:** {result.processing_method}")
st.write(f"**Confidence:** {result.extraction_confidence:.1%}")
st.markdown("---")
else:
failed += 1
st.warning(f"β οΈ Could not extract complete data from: {uploaded_file.name}")
if result:
st.write(f"Partial data: {result.supplier_name}, βΉ{result.amount}")
st.markdown("---")
except Exception as e:
failed += 1
# Still mark as processed to avoid reprocessing
processed_hashes.add(file_hash)
with results_container:
st.error(f"β Error processing {uploaded_file.name}: {str(e)}")
st.markdown("---")
# Update session state
st.session_state[f'processed_file_hashes_{session_id}'] = processed_hashes
# Final summary
with progress_container:
progress_bar.progress(1.0)
progress_text.text("β
Processing completed!")
with status_container:
if successful > 0:
st.success(f"π Processing complete! {successful} successful, {failed} failed")
if successful > 0:
st.balloons()
else:
st.error(f"β Processing failed for all {failed} files. Please check file formats and content.")
# Update processing state
st.session_state[f'currently_processing_{session_id}'] = False
st.session_state[f'processing_complete_{session_id}'] = True
# Force rerun to update UI
st.rerun()
def process_files(uploaded_files, session_id):
"""Legacy function - redirect to process_files_once"""
return process_files_once(uploaded_files, session_id)
def handle_chat_query(query, show_response=False):
"""Handle chat query"""
st.session_state.chat_history.append({
"role": "user",
"content": query,
"timestamp": datetime.now()
})
try:
with st.spinner("π€ AI is analyzing..."):
response = st.session_state.chatbot.query_database(query)
st.session_state.chat_history.append({
"role": "assistant",
"content": response,
"timestamp": datetime.now()
})
if show_response:
with st.chat_message("assistant"):
st.markdown(response)
st.info("π‘ Switch to the 'AI Chat' section to see full conversation history!")
st.rerun()
except Exception as e:
st.error(f"Chat error: {e}")
# ===============================================================================
# MAIN ENTRY POINT
# ===============================================================================
def main():
"""Main entry point for Hugging Face Spaces"""
try:
if IS_HF_SPACE:
st.sidebar.info("π€ Running on Hugging Face Spaces")
create_app()
except Exception as e:
st.error(f"""
## π¨ Application Error
{e}
Please refresh the page or check the logs for more details.
""")
if __name__ == "__main__":
main() |