Spaces:
Build error
Build error
File size: 94,105 Bytes
c5af9d3 | 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 | """
Gapura AI Analysis API
FastAPI server for regression and NLP analysis of irregularity reports
Uses real trained models from ai-model/models/
"""
from fastapi import FastAPI, HTTPException, BackgroundTasks, Request, Body
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, field_validator
from pydantic_core import ValidationError
from typing import List, Optional, Dict, Any, Tuple
from collections import Counter
import os
import json
import logging
from datetime import datetime
import numpy as np
import pickle
import pandas as pd
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from data.cache_service import get_cache, CacheService
from data.nlp_service import NLPModelService
from data.shap_service import get_shap_explainer
from data.anomaly_service import get_anomaly_detector
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
tags_metadata = [
{
"name": "Analysis",
"description": "Core AI analysis endpoints for irregularity reports.",
},
{
"name": "Health",
"description": "System health and model status checks.",
},
{
"name": "Jobs",
"description": "Asynchronous job management.",
},
{
"name": "Training",
"description": "Model retraining and lifecycle management.",
},
]
app = FastAPI(
title="Gapura AI Analysis API",
description="""
Gapura AI Analysis API provides advanced machine learning capabilities for analyzing irregularity reports.
## Features
* **Regression Analysis**: Predict resolution time (days) based on report details.
* **NLP Classification**: Determine severity (Critical, High, Medium, Low) and categorize issues.
* **Entity Extraction**: Extract key entities like Airlines, Flight Numbers, and Dates.
* **Summarization**: Generate executive summaries and key points from long reports.
* **Trend Analysis**: Analyze trends by Airline, Hub, and Category.
* **Anomaly Detection**: Identify unusual patterns in resolution times.
## Models
* **Regression**: Random Forest Regressor (v1.0.0-trained)
* **NLP**: Hybrid Transformer + Rule-based System (v4.0.0-onnx)
""",
version="2.1.0",
openapi_tags=tags_metadata,
docs_url="/docs",
redoc_url="/redoc",
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(GZipMiddleware, minimum_size=500)
@app.exception_handler(ValidationError)
async def validation_exception_handler(request: Request, exc: ValidationError):
return JSONResponse(
status_code=422,
content={
"detail": "Validation error",
"errors": exc.errors(),
"body": exc.json(),
},
)
# ============== Pydantic Models ==============
from enum import Enum
from datetime import date as date_type
class ReportCategoryEnum(str, Enum):
IRREGULARITY = "Irregularity"
COMPLAINT = "Complaint"
class AreaEnum(str, Enum):
APRON = "Apron Area"
TERMINAL = "Terminal Area"
GENERAL = "General"
class StatusEnum(str, Enum):
OPEN = "Open"
CLOSED = "Closed"
IN_PROGRESS = "In Progress"
class IrregularityReport(BaseModel):
Date_of_Event: Optional[str] = Field(None, description="Date of the event")
Airlines: Optional[str] = Field(None, max_length=100)
Flight_Number: Optional[str] = Field(None, max_length=20)
Branch: Optional[str] = Field(None, max_length=10)
HUB: Optional[str] = Field(None, max_length=20)
Route: Optional[str] = Field(None, max_length=50)
Report_Category: Optional[str] = Field(None, max_length=50)
Irregularity_Complain_Category: Optional[str] = Field(None, max_length=100)
Report: Optional[str] = Field(None, max_length=2000)
Root_Caused: Optional[str] = Field(None, max_length=2000)
Action_Taken: Optional[str] = Field(None, max_length=2000)
Area: Optional[str] = Field(None, max_length=50)
Status: Optional[str] = Field(None, max_length=50)
Reported_By: Optional[str] = Field(None, max_length=100)
Upload_Irregularity_Photo: Optional[str] = Field(None)
model_config = {"extra": "allow"}
class AnalysisOptions(BaseModel):
predictResolutionTime: bool = Field(
default=True, description="Run regression model"
)
classifySeverity: bool = Field(
default=True, description="Classify severity using NLP"
)
extractEntities: bool = Field(
default=True, description="Extract entities using NER"
)
generateSummary: bool = Field(default=True, description="Generate text summaries")
analyzeTrends: bool = Field(default=True, description="Analyze trends")
bypassCache: bool = Field(
default=False, description="Bypass cache and fetch fresh data"
)
includeRisk: bool = Field(default=False, description="Include risk assessment in analysis")
class AnalysisRequest(BaseModel):
sheetId: Optional[str] = Field(None, description="Google Sheet ID")
sheetName: Optional[str] = Field(None, description="Sheet name (NON CARGO or CGO)")
rowRange: Optional[str] = Field(None, description="Row range (e.g., A2:Z100)")
data: Optional[List[IrregularityReport]] = Field(
None, description="Direct data upload"
)
options: AnalysisOptions = Field(default_factory=AnalysisOptions)
@field_validator("data")
@classmethod
def validate_data(cls, v):
if v is not None and len(v) == 0:
raise ValueError("data array cannot be empty")
return v
class ShapExplanation(BaseModel):
baseValue: float = Field(description="Base/expected value from model")
predictionExplained: bool = Field(
description="Whether SHAP explanation is available"
)
topFactors: List[Dict[str, Any]] = Field(
default_factory=list, description="Top contributing features"
)
explanation: str = Field(default="", description="Human-readable explanation")
class AnomalyResult(BaseModel):
isAnomaly: bool = Field(description="Whether prediction is anomalous")
anomalyScore: float = Field(description="Anomaly score (0-1)")
anomalies: List[Dict[str, Any]] = Field(
default_factory=list, description="List of detected anomalies"
)
class RegressionPrediction(BaseModel):
reportId: str
predictedDays: float
confidenceInterval: Tuple[float, float]
featureImportance: Dict[str, float]
hasUnknownCategories: bool = Field(
default=False, description="True if unknown categories were used in prediction"
)
shapExplanation: Optional[ShapExplanation] = Field(
default=None, description="SHAP-based explanation for prediction"
)
anomalyDetection: Optional[AnomalyResult] = Field(
default=None, description="Anomaly detection results"
)
class RegressionResult(BaseModel):
predictions: List[RegressionPrediction]
modelMetrics: Dict[str, Any]
class ClassificationResult(BaseModel):
reportId: str
severity: str
severityConfidence: float
areaType: str
issueType: str
issueTypeConfidence: float
class Entity(BaseModel):
text: str
label: str
start: int
end: int
confidence: float
class EntityResult(BaseModel):
reportId: str
entities: List[Entity]
class SummaryResult(BaseModel):
reportId: str
executiveSummary: str
keyPoints: List[str]
class SentimentResult(BaseModel):
reportId: str
urgencyScore: float
sentiment: str
keywords: List[str]
class NLPResult(BaseModel):
classifications: List[ClassificationResult]
entities: List[EntityResult]
summaries: List[SummaryResult]
sentiment: List[SentimentResult]
class TrendData(BaseModel):
count: int
avgResolutionDays: Optional[float]
topIssues: List[str]
class TrendResult(BaseModel):
byAirline: Dict[str, TrendData]
byHub: Dict[str, TrendData]
byCategory: Dict[str, Dict[str, Any]]
timeSeries: List[Dict[str, Any]]
class Metadata(BaseModel):
totalRecords: int
processingTime: float
modelVersions: Dict[str, str]
class AnalysisResponse(BaseModel):
regression: Optional[RegressionResult] = None
nlp: Optional[NLPResult] = None
trends: Optional[TrendResult] = None
risk: Optional[RiskAssessmentResponse] = None
metadata: Metadata
class RiskItem(BaseModel):
reportId: str
severity: str
severityConfidence: float
predictedDays: float
anomalyScore: float
category: str
hub: str
area: str
riskScore: float
priority: str
recommendedActions: List[Dict[str, Any]] = Field(default_factory=list)
preventiveSuggestions: List[str] = Field(default_factory=list)
class RiskAssessmentResponse(BaseModel):
items: List[RiskItem]
topPatterns: List[Dict[str, Any]]
metadata: Dict[str, Any]
def _severity_to_score(level: str) -> float:
m = {"Critical": 1.0, "High": 0.8, "Medium": 0.5, "Low": 0.2}
return m.get(level, 0.3)
def _normalize_days(d: float) -> float:
return max(0.0, min(1.0, float(d) / 7.0))
def _priority_from_score(s: float) -> str:
if s >= 0.75:
return "HIGH"
if s >= 0.45:
return "MEDIUM"
return "LOW"
def _extract_prevention(texts: List[str]) -> List[str]:
kws = ["review", "prosedur", "procedure", "training", "pelatihan", "prevent", "pencegahan", "maintenance", "inspection", "inspeksi", "briefing", "supervision", "checklist", "verify", "verifikasi"]
out = []
seen = set()
for t in texts:
lt = t.lower()
for k in kws:
if k in lt:
if t not in seen:
seen.add(t)
out.append(t)
return out[:5]
# ============== Real Model Service ==============
class ModelService:
"""Service that loads and uses real trained models"""
def __init__(self):
self.regression_version = "1.0.0-trained"
self.nlp_version = "1.0.0-mock"
self.regression_model = None
self.regression_onnx_session = None
self.label_encoders = {}
self.scaler = None
self.feature_names = []
self.model_metrics = {}
self.model_loaded = False
self.nlp_service = None
self._load_regression_model()
self._load_nlp_service()
def _load_nlp_service(self):
"""Load NLP service with trained models or fallback"""
try:
from data.nlp_service import get_nlp_service
self.nlp_service = get_nlp_service()
self.nlp_version = self.nlp_service.version
logger.info(f"NLP service loaded (version: {self.nlp_version})")
except Exception as e:
logger.warning(f"Failed to load NLP service: {e}")
def _load_regression_model(self):
"""Load the trained regression model from file"""
try:
model_path = os.path.join(
os.path.dirname(__file__),
"..",
"models",
"regression",
"resolution_predictor_latest.pkl",
)
if not os.path.exists(model_path):
logger.warning(f"Model file not found at {model_path}")
return
logger.info(f"Loading regression model from {model_path}")
with open(model_path, "rb") as f:
model_data = pickle.load(f)
self.regression_model = model_data.get("model")
self.label_encoders = model_data.get("label_encoders", {})
self.scaler = model_data.get("scaler")
self.feature_names = model_data.get("feature_names", [])
self.model_metrics = model_data.get("metrics", {})
self.model_loaded = True
logger.info(f"✓ Regression model loaded successfully")
logger.info(f" - Features: {len(self.feature_names)}")
logger.info(f" - Metrics: MAE={self.model_metrics.get('test_mae', 'N/A')}")
# Try to load ONNX model for faster inference
onnx_path = os.path.join(
os.path.dirname(__file__),
"..",
"models",
"regression",
"resolution_predictor.onnx",
)
if os.path.exists(onnx_path):
try:
import onnxruntime as ort
sess_options = ort.SessionOptions()
sess_options.intra_op_num_threads = 1
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
self.regression_onnx_session = ort.InferenceSession(onnx_path, sess_options)
logger.info("✓ Regression ONNX model loaded successfully")
except Exception as e:
logger.warning(f"Failed to load Regression ONNX model: {e}")
except Exception as e:
logger.error(f"Failed to load regression model: {e}")
self.model_loaded = False
def _extract_features(self, report: Dict) -> Optional[np.ndarray]:
"""Extract features from a single report matching training preprocessing"""
try:
# Parse date
date_str = report.get("Date_of_Event", "")
try:
date_obj = pd.to_datetime(date_str, errors="coerce")
if pd.isna(date_obj):
date_obj = datetime.now()
day_of_week = date_obj.dayofweek
month = date_obj.month
is_weekend = day_of_week in [5, 6]
week_of_year = date_obj.isocalendar().week
day_of_year = date_obj.dayofyear
except:
day_of_week = 0
month = 1
is_weekend = False
week_of_year = 1
day_of_year = 1
sin_day_of_week = np.sin(2 * np.pi * day_of_week / 7)
cos_day_of_week = np.cos(2 * np.pi * day_of_week / 7)
sin_month = np.sin(2 * np.pi * month / 12)
cos_month = np.cos(2 * np.pi * month / 12)
sin_day_of_year = np.sin(2 * np.pi * day_of_year / 365)
cos_day_of_year = np.cos(2 * np.pi * day_of_year / 365)
# Text features
report_text = report.get("Report", "")
root_cause = report.get("Root_Caused", "")
action_taken = report.get("Action_Taken", "")
# Categorical
airline = report.get("Airlines", "Unknown")
hub = report.get("HUB", "Unknown")
branch = report.get("Branch", "Unknown")
category = report.get("Irregularity_Complain_Category", "Unknown")
area = report.get("Area", "Unknown")
# Binary features
has_photos = bool(report.get("Upload_Irregularity_Photo", ""))
is_complaint = report.get("Report_Category", "") == "Complaint"
# Encode categorical features
categorical_values = {
"airline": airline,
"hub": hub,
"branch": branch,
"category": category,
"area": area,
}
encoded_values = {}
unknown_flags = {}
for col, value in categorical_values.items():
if col in self.label_encoders:
le = self.label_encoders[col]
value_str = str(value)
if value_str in le.classes_:
encoded_values[f"{col}_encoded"] = le.transform([value_str])[0]
unknown_flags[col] = False
else:
unknown_idx = (
le.transform(["Unknown"])[0]
if "Unknown" in le.classes_
else 0
)
encoded_values[f"{col}_encoded"] = unknown_idx
unknown_flags[col] = True
logger.warning(
f"Unknown {col} value: '{value_str}' - using Unknown category"
)
else:
encoded_values[f"{col}_encoded"] = 0
unknown_flags[col] = True
# Build feature vector in correct order
feature_dict = {
"day_of_week": day_of_week,
"month": month,
"is_weekend": int(is_weekend),
"week_of_year": week_of_year,
"sin_day_of_week": sin_day_of_week,
"cos_day_of_week": cos_day_of_week,
"sin_month": sin_month,
"cos_month": cos_month,
"sin_day_of_year": sin_day_of_year,
"cos_day_of_year": cos_day_of_year,
"report_length": len(report_text),
"report_word_count": len(report_text.split()) if report_text else 0,
"root_cause_length": len(root_cause),
"action_taken_length": len(action_taken),
"has_photos": int(has_photos),
"is_complaint": int(is_complaint),
"text_complexity": (len(report_text) * len(report_text.split()) / 100)
if report_text
else 0,
"has_root_cause": int(bool(root_cause)),
"has_action_taken": int(bool(action_taken)),
}
feature_dict.update(encoded_values)
has_unknown_categories = any(unknown_flags.values())
# Create feature array in correct order
features = []
for feature_name in self.feature_names:
features.append(feature_dict.get(feature_name, 0))
X = np.array([features])
# Scale features
if self.scaler:
X = self.scaler.transform(X)
return X, has_unknown_categories
except Exception as e:
logger.error(f"Feature extraction error: {e}")
return None, True
def _extract_features_batch(self, df: pd.DataFrame) -> Tuple[Optional[np.ndarray], np.ndarray]:
"""Extract features from a dataframe matching training preprocessing (Batch optimized)"""
try:
# Ensure required columns exist
required_cols = [
"Date_of_Event", "Report", "Root_Caused", "Action_Taken",
"Upload_Irregularity_Photo", "Report_Category",
"Airlines", "HUB", "Branch", "Irregularity_Complain_Category", "Area"
]
for col in required_cols:
if col not in df.columns:
df[col] = None
# Copy to avoid modifying original
df = df.copy()
# Parse date
df["Date_of_Event"] = pd.to_datetime(df["Date_of_Event"], errors="coerce")
now = datetime.now()
df["Date_of_Event"] = df["Date_of_Event"].fillna(now)
df["day_of_week"] = df["Date_of_Event"].dt.dayofweek
df["month"] = df["Date_of_Event"].dt.month
df["is_weekend"] = df["day_of_week"].isin([5, 6]).astype(int)
df["week_of_year"] = df["Date_of_Event"].dt.isocalendar().week.astype(int)
df["day_of_year"] = df["Date_of_Event"].dt.dayofyear
# Sin/Cos transforms
df["sin_day_of_week"] = np.sin(2 * np.pi * df["day_of_week"] / 7)
df["cos_day_of_week"] = np.cos(2 * np.pi * df["day_of_week"] / 7)
df["sin_month"] = np.sin(2 * np.pi * df["month"] / 12)
df["cos_month"] = np.cos(2 * np.pi * df["month"] / 12)
df["sin_day_of_year"] = np.sin(2 * np.pi * df["day_of_year"] / 365)
df["cos_day_of_year"] = np.cos(2 * np.pi * df["day_of_year"] / 365)
# Text features
df["Report"] = df["Report"].fillna("").astype(str)
df["Root_Caused"] = df["Root_Caused"].fillna("").astype(str)
df["Action_Taken"] = df["Action_Taken"].fillna("").astype(str)
df["report_length"] = df["Report"].str.len()
df["report_word_count"] = df["Report"].apply(lambda x: len(x.split()) if x else 0)
df["root_cause_length"] = df["Root_Caused"].str.len()
df["action_taken_length"] = df["Action_Taken"].str.len()
df["has_photos"] = df["Upload_Irregularity_Photo"].fillna("").astype(bool).astype(int)
df["is_complaint"] = (df["Report_Category"] == "Complaint").astype(int)
df["text_complexity"] = np.where(
df["Report"].str.len() > 0,
(df["report_length"] * df["report_word_count"] / 100),
0
)
df["has_root_cause"] = (df["Root_Caused"].str.len() > 0).astype(int)
df["has_action_taken"] = (df["Action_Taken"].str.len() > 0).astype(int)
# Categorical encoding
categorical_cols = {
"airline": "Airlines",
"hub": "HUB",
"branch": "Branch",
"category": "Irregularity_Complain_Category",
"area": "Area"
}
unknown_flags = np.zeros(len(df), dtype=bool)
for feature_name, col_name in categorical_cols.items():
df[col_name] = df[col_name].fillna("Unknown").astype(str)
if feature_name in self.label_encoders:
le = self.label_encoders[feature_name]
# Create mapping for fast lookup
mapping = {label: idx for idx, label in enumerate(le.classes_)}
unknown_idx = mapping.get("Unknown", 0)
if "Unknown" in le.classes_:
unknown_idx = mapping["Unknown"]
# Map values
encoded_col = df[col_name].map(mapping)
# Track unknowns (NaN after map means unknown)
is_unknown = encoded_col.isna()
unknown_flags |= is_unknown.values
# Fill unknowns
df[f"{feature_name}_encoded"] = encoded_col.fillna(unknown_idx).astype(int)
else:
df[f"{feature_name}_encoded"] = 0
unknown_flags[:] = True
# Select features in order
for f in self.feature_names:
if f not in df.columns:
df[f] = 0
X = df[self.feature_names].values
# Scale
if self.scaler:
X = self.scaler.transform(X)
return X, unknown_flags
except Exception as e:
logger.error(f"Batch feature extraction error: {e}")
return None, np.ones(len(df), dtype=bool)
def predict_regression(self, data: List[Dict]) -> List[RegressionPrediction]:
"""Predict resolution time using trained model"""
predictions = []
shap_explainer = get_shap_explainer()
anomaly_detector = get_anomaly_detector()
# Batch processing
try:
df = pd.DataFrame(data)
X_batch, unknown_flags_batch = self._extract_features_batch(df)
if X_batch is not None:
if self.regression_onnx_session:
# Use ONNX model
input_name = self.regression_onnx_session.get_inputs()[0].name
predicted_batch = self.regression_onnx_session.run(None, {input_name: X_batch.astype(np.float32)})[0]
predicted_batch = predicted_batch.ravel() # Flatten to 1D array
elif self.regression_model is not None:
# Use Pickle model
predicted_batch = self.regression_model.predict(X_batch)
else:
predicted_batch = None
unknown_flags_batch = [True] * len(data)
else:
predicted_batch = None
unknown_flags_batch = [True] * len(data)
except Exception as e:
logger.error(f"Batch prediction setup failed: {e}")
predicted_batch = None
unknown_flags_batch = [True] * len(data)
for i, item in enumerate(data):
# Use batch results
has_unknown = unknown_flags_batch[i]
features = X_batch[i:i+1] if X_batch is not None else None
category = item.get("Irregularity_Complain_Category", "Unknown")
hub = item.get("HUB", "Unknown")
if predicted_batch is not None:
predicted = predicted_batch[i]
mae = self.model_metrics.get("test_mae", 0.5)
lower = max(0.1, predicted - mae)
upper = predicted + mae
shap_exp = None
if shap_explainer.explainer is not None and features is not None:
try:
shap_result = shap_explainer.explain_prediction(features)
shap_exp = ShapExplanation(
baseValue=shap_result.get("base_value", 0),
predictionExplained=shap_result.get(
"prediction_explained", False
),
topFactors=shap_result.get("top_factors", [])[:5],
explanation=shap_result.get("explanation", ""),
)
except Exception as e:
logger.debug(f"SHAP explanation failed: {e}")
anomaly_result = None
try:
anomaly_data = anomaly_detector.detect_prediction_anomaly(
predicted, category, hub
)
anomaly_result = AnomalyResult(
isAnomaly=anomaly_data.get("is_anomaly", False),
anomalyScore=anomaly_data.get("anomaly_score", 0),
anomalies=anomaly_data.get("anomalies", []),
)
except Exception as e:
logger.debug(f"Anomaly detection failed: {e}")
else:
base_days = {
"Cargo Problems": 2.5,
"Pax Handling": 1.8,
"GSE": 3.2,
"Operation": 2.1,
"Baggage Handling": 1.5,
}.get(category, 2.0)
predicted = base_days + np.random.normal(0, 0.3)
lower = max(0.1, predicted - 0.5)
upper = predicted + 0.5
has_unknown = True
shap_exp = None
anomaly_result = None
if self.model_metrics and "feature_importance" in self.model_metrics:
importance = self.model_metrics["feature_importance"]
else:
importance = {
"category": 0.35,
"airline": 0.28,
"hub": 0.15,
"reportLength": 0.12,
"hasPhotos": 0.10,
}
predictions.append(
RegressionPrediction(
reportId=f"row_{i}",
predictedDays=round(max(0.1, predicted), 2),
confidenceInterval=(round(lower, 2), round(upper, 2)),
featureImportance=importance,
hasUnknownCategories=has_unknown,
shapExplanation=shap_exp,
anomalyDetection=anomaly_result,
)
)
return predictions
def classify_text(self, data: List[Dict]) -> List[ClassificationResult]:
"""Classify text using trained NLP models or rule-based fallback"""
results = []
texts = [
(item.get("Report") or "") + " " + (item.get("Root_Caused") or "")
for item in data
]
# Get multi-task predictions if available
mt_results = None
if self.nlp_service:
mt_results = self.nlp_service.predict_multi_task(texts)
severity_results = self.nlp_service.classify_severity(texts)
else:
severity_results = self._classify_severity_fallback(texts)
for i, (item, sev_result) in enumerate(zip(data, severity_results)):
severity = sev_result.get("severity", "Low")
severity_conf = sev_result.get("confidence", 0.8)
# Use multi-task predictions for area and issue type if available
if mt_results and i < len(mt_results):
mt_res = mt_results[i]
area = mt_res.get("area", {}).get("label", item.get("Area", "Unknown")).replace(" Area", "")
area_conf = mt_res.get("area", {}).get("confidence", 0.85)
issue = mt_res.get("irregularity", {}).get("label", item.get("Irregularity_Complain_Category", "Unknown"))
issue_conf = mt_res.get("irregularity", {}).get("confidence", 0.85)
else:
area = item.get("Area", "Unknown").replace(" Area", "")
area_conf = 0.85
issue = item.get("Irregularity_Complain_Category", "Unknown")
issue_conf = 0.85
results.append(
ClassificationResult(
reportId=f"row_{i}",
severity=severity,
severityConfidence=severity_conf,
areaType=area,
issueType=issue,
issueTypeConfidence=issue_conf,
)
)
return results
def _classify_severity_fallback(self, texts: List[str]) -> List[Dict]:
"""Fallback severity classification"""
results = []
for text in texts:
report = text.lower()
if any(
kw in report
for kw in ["damage", "torn", "broken", "critical", "emergency"]
):
severity = "High"
severity_conf = 0.89
elif any(kw in report for kw in ["delay", "late", "wrong", "error"]):
severity = "Medium"
severity_conf = 0.75
else:
severity = "Low"
severity_conf = 0.82
results.append({"severity": severity, "confidence": severity_conf})
return results
def extract_entities(self, data: List[Dict]) -> List[EntityResult]:
"""Extract entities from reports"""
results = []
for i, item in enumerate(data):
entities = []
report_text = item.get("Report", "") + " " + item.get("Root_Caused", "")
# Extract airline
airline = item.get("Airlines", "")
if airline and airline != "Unknown":
# Find position in text
idx = report_text.lower().find(airline.lower())
start = max(0, idx) if idx >= 0 else 0
entities.append(
Entity(
text=airline,
label="AIRLINE",
start=start,
end=start + len(airline),
confidence=0.95,
)
)
# Extract flight number
flight = item.get("Flight_Number", "")
if flight and flight != "#N/A":
entities.append(
Entity(
text=flight,
label="FLIGHT_NUMBER",
start=0,
end=len(flight),
confidence=0.92,
)
)
# Extract dates
date_str = item.get("Date_of_Event", "")
if date_str:
entities.append(
Entity(
text=date_str,
label="DATE",
start=0,
end=len(date_str),
confidence=0.90,
)
)
results.append(EntityResult(reportId=f"row_{i}", entities=entities))
return results
def generate_summary(self, data: List[Dict]) -> List[SummaryResult]:
"""Generate summaries using NLP service or fallback"""
results = []
for i, item in enumerate(data):
combined_text = (
item.get("Report", "")
+ " "
+ item.get("Root_Caused", "")
+ " "
+ item.get("Action_Taken", "")
)
if self.nlp_service and len(combined_text) > 100:
summary_result = self.nlp_service.summarize(combined_text)
executive_summary = summary_result.get("executiveSummary", "")
key_points = summary_result.get("keyPoints", [])
else:
category = item.get("Irregularity_Complain_Category", "Issue")
report = item.get("Report", "")[:120]
root_cause = item.get("Root_Caused", "")[:80]
action = item.get("Action_Taken", "")[:80]
executive_summary = f"{category}: {report}"
if root_cause:
executive_summary += f" Root cause: {root_cause}."
key_points = [
f"Category: {category}",
f"Status: {item.get('Status', 'Unknown')}",
f"Area: {item.get('Area', 'Unknown')}",
]
if action:
key_points.append(f"Action: {action[:50]}...")
results.append(
SummaryResult(
reportId=f"row_{i}",
executiveSummary=executive_summary,
keyPoints=key_points,
)
)
return results
def analyze_sentiment(self, data: List[Dict]) -> List[SentimentResult]:
"""Analyze sentiment/urgency using NLP service or fallback"""
results = []
texts = [
item.get("Report", "") + " " + item.get("Root_Caused", "") for item in data
]
if self.nlp_service:
urgency_results = self.nlp_service.analyze_urgency(texts)
else:
urgency_results = self._analyze_urgency_fallback(texts)
for i, (item, urg_result) in enumerate(zip(data, urgency_results)):
results.append(
SentimentResult(
reportId=f"row_{i}",
urgencyScore=urg_result.get("urgency_score", 0.0),
sentiment=urg_result.get("sentiment", "Neutral"),
keywords=urg_result.get("keywords", []),
)
)
return results
def _analyze_urgency_fallback(self, texts: List[str]) -> List[Dict]:
"""Fallback urgency analysis"""
urgency_keywords = [
"damage",
"broken",
"emergency",
"critical",
"urgent",
"torn",
"severe",
]
results = []
for text in texts:
report = text.lower()
keyword_matches = [kw for kw in urgency_keywords if kw in report]
urgency_count = len(keyword_matches)
urgency_score = min(1.0, urgency_count / 3.0)
results.append(
{
"urgency_score": round(urgency_score, 2),
"sentiment": "Negative" if urgency_score > 0.3 else "Neutral",
"keywords": keyword_matches,
}
)
return results
# Initialize model service
model_service = ModelService()
# ============== API Endpoints ==============
@app.get(
"/",
tags=["Health"],
summary="API Root & Status",
)
async def root():
"""Returns basic API status, version, and model availability."""
return {
"status": "healthy",
"service": "Gapura AI Analysis API",
"version": "1.0.0",
"models": {
"regression": "loaded" if model_service.model_loaded else "unavailable",
"nlp": model_service.nlp_service.version if model_service.nlp_service and model_service.nlp_service.models_loaded else "unavailable",
},
"timestamp": datetime.now().isoformat(),
}
@app.get(
"/health",
tags=["Health"],
summary="Detailed Health Check",
)
async def health_check():
"""
Returns detailed health status including:
- **Models**: Version and load status of Regression and NLP models.
- **Cache**: Redis/Local cache connectivity.
- **Metrics**: Current model performance metrics (MAE, RMSE, R2).
"""
cache = get_cache()
cache_health = cache.health_check()
return {
"status": "healthy",
"models": {
"regression": {
"version": model_service.regression_version,
"loaded": model_service.model_loaded,
"metrics": model_service.model_metrics
if model_service.model_loaded
else None,
},
"nlp": {
"version": model_service.nlp_version,
"status": "rule_based",
},
},
"cache": cache_health,
"timestamp": datetime.now().isoformat(),
}
@app.post("/api/ai/risk/assess", response_model=RiskAssessmentResponse, tags=["Analysis"])
async def assess_risk(
request: Optional[AnalysisRequest] = Body(None),
sheetId: Optional[str] = None,
sheetName: Optional[str] = None,
rowRange: Optional[str] = None,
bypass_cache: bool = False,
top_k_patterns: int = 5,
):
from data.sheets_service import GoogleSheetsService
from data.action_service import get_action_service
items_data: List[Dict[str, Any]] = []
if request and request.data:
items_data = [r.model_dump(exclude_none=True) for r in request.data]
elif sheetId and sheetName and rowRange:
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
items_data = sheets_service.fetch_sheet_data(sheetId, sheetName, rowRange, bypass_cache=bypass_cache)
else:
raise HTTPException(status_code=400, detail="sheetId, sheetName, and rowRange are required, or provide data in body")
if len(items_data) == 0:
return RiskAssessmentResponse(items=[], topPatterns=[], metadata={"count": 0})
preds = model_service.predict_regression(items_data)
classes = model_service.classify_text(items_data)
try:
action_service = get_action_service()
eff = action_service.action_effectiveness or {}
except Exception:
eff = {}
items: List[RiskItem] = []
for i, item in enumerate(items_data):
cat = item.get("Irregularity_Complain_Category", "Unknown") or "Unknown"
hub = item.get("HUB", "Unknown") or "Unknown"
area = (item.get("Area", "Unknown") or "Unknown").replace(" Area", "")
pr = preds[i]
cl = classes[i]
sev = cl.severity
sev_conf = cl.severityConfidence
pdays = pr.predictedDays
anom = 0.0
if pr.anomalyDetection:
anom = pr.anomalyDetection.anomalyScore
sev_s = _severity_to_score(sev)
d_s = _normalize_days(pdays)
cat_w = 1.0 - float(eff.get(cat, 0.8))
risk = min(1.0, 0.5 * sev_s + 0.25 * d_s + 0.15 * anom + 0.10 * cat_w)
recs: List[Dict[str, Any]] = []
try:
recs_resp = action_service.recommend(
report=item.get("Report", "") or "",
issue_type=cat,
severity=sev,
area=area if area else None,
airline=item.get("Airlines") or None,
top_n=5,
)
recs = recs_resp.get("recommendations", [])
except Exception:
recs = []
prev = _extract_prevention([r.get("action", "") for r in recs])
items.append(
RiskItem(
reportId=f"row_{i}",
severity=sev,
severityConfidence=sev_conf,
predictedDays=pdays,
anomalyScore=anom,
category=cat,
hub=hub,
area=area,
riskScore=round(risk, 3),
priority=_priority_from_score(risk),
recommendedActions=recs[:5],
preventiveSuggestions=prev,
)
)
groups: Dict[str, Dict[str, Any]] = {}
for it, raw in zip(items, items_data):
key = f"{it.category}|{it.hub}|{it.area}"
g = groups.get(key) or {"key": key, "category": it.category, "hub": it.hub, "area": it.area, "count": 0, "avgRisk": 0.0, "avgDays": 0.0, "highSeverityShare": 0.0}
g["count"] += 1
g["avgRisk"] += it.riskScore
g["avgDays"] += it.predictedDays
g["highSeverityShare"] += 1.0 if it.severity in ("Critical", "High") else 0.0
groups[key] = g
patterns = []
for g in groups.values():
c = g["count"]
g["avgRisk"] = round(g["avgRisk"] / max(1, c), 3)
g["avgDays"] = round(g["avgDays"] / max(1, c), 2)
g["highSeverityShare"] = round(g["highSeverityShare"] / max(1, c), 3)
patterns.append(g)
patterns.sort(key=lambda x: (-x["avgRisk"], -x["highSeverityShare"], -x["avgDays"], -x["count"]))
return RiskAssessmentResponse(
items=sorted(items, key=lambda x: -x.riskScore),
topPatterns=patterns[:top_k_patterns],
metadata={"count": len(items)},
)
from data.job_service import JobService, JobStatus
# Initialize job service
job_service = JobService()
def perform_analysis(data: List[Dict], options: AnalysisOptions, compact: bool) -> AnalysisResponse:
"""Core analysis logic reused by sync and async endpoints"""
start_time = datetime.now()
total_records = len(data)
logger.info(f"Analyzing {total_records} records...")
# Initialize response
response = AnalysisResponse(
metadata=Metadata(
totalRecords=total_records,
processingTime=0.0,
modelVersions={
"regression": model_service.regression_version,
"nlp": model_service.nlp_version,
},
)
)
# Regression Analysis
predictions: List[RegressionPrediction] = []
if options.predictResolutionTime or options.includeRisk:
logger.info(f"Running regression analysis...")
predictions = model_service.predict_regression(data)
# Use real metrics if available
if model_service.model_loaded and model_service.model_metrics:
metrics = {
"mae": round(model_service.model_metrics.get("test_mae", 1.2), 3),
"rmse": round(model_service.model_metrics.get("test_rmse", 1.8), 3),
"r2": round(model_service.model_metrics.get("test_r2", 0.78), 3),
"model_loaded": True,
"note": "Using trained model"
if model_service.model_loaded
else "Using fallback",
}
else:
metrics = {
"mae": None,
"rmse": None,
"r2": None,
"model_loaded": False,
"note": "Model not available - using fallback predictions",
}
if options.predictResolutionTime:
response.regression = RegressionResult(
predictions=predictions,
modelMetrics=metrics,
)
# NLP Analysis
classifications: List[ClassificationResult] = []
if any(
[
options.classifySeverity,
options.extractEntities,
options.generateSummary,
options.includeRisk,
]
):
logger.info(f"Running NLP analysis...")
entities = []
summaries = []
sentiment = []
if options.classifySeverity or options.includeRisk:
classifications = model_service.classify_text(data)
if options.extractEntities:
entities = model_service.extract_entities(data)
if options.generateSummary:
summaries = model_service.generate_summary(data)
sentiment = model_service.analyze_sentiment(data)
response.nlp = NLPResult(
classifications=classifications,
entities=entities,
summaries=summaries,
sentiment=sentiment,
)
# Trend Analysis
if options.analyzeTrends:
logger.info(f"Running trend analysis...")
by_airline = {}
by_hub = {}
by_category = {}
for item in data:
airline = item.get("Airlines", "Unknown")
hub = item.get("HUB", "Unknown")
category = item.get("Irregularity_Complain_Category", "Unknown")
# Airline aggregation
if airline not in by_airline:
by_airline[airline] = {"count": 0, "issues": []}
by_airline[airline]["count"] += 1
by_airline[airline]["issues"].append(category)
# Hub aggregation
if hub not in by_hub:
by_hub[hub] = {"count": 0, "issues": []}
by_hub[hub]["count"] += 1
by_hub[hub]["issues"].append(category)
# Category aggregation
if category not in by_category:
by_category[category] = {"count": 0}
by_category[category]["count"] += 1
# Convert to TrendData format
by_airline_trend = {
k: TrendData(
count=v["count"],
avgResolutionDays=2.0 + np.random.random(),
topIssues=list(set(v["issues"]))[:3],
)
for k, v in by_airline.items()
}
by_hub_trend = {
k: TrendData(
count=v["count"],
avgResolutionDays=2.0 + np.random.random(),
topIssues=list(set(v["issues"]))[:3],
)
for k, v in by_hub.items()
}
by_category_trend = {
k: {"count": v["count"], "trend": "stable"}
for k, v in by_category.items()
}
response.trends = TrendResult(
byAirline=by_airline_trend,
byHub=by_hub_trend,
byCategory=by_category_trend,
timeSeries=[],
)
# Risk Assessment
if options.includeRisk:
try:
from data.action_service import get_action_service
action_service = get_action_service()
eff = action_service.action_effectiveness or {}
except Exception:
eff = {}
action_service = None
items: List[RiskItem] = []
for i, item in enumerate(data):
cat = item.get("Irregularity_Complain_Category", "Unknown") or "Unknown"
hub = item.get("HUB", "Unknown") or "Unknown"
area = (item.get("Area", "Unknown") or "Unknown").replace(" Area", "")
pr = predictions[i] if i < len(predictions) else None
cl = classifications[i] if i < len(classifications) else None
sev = cl.severity if cl else "Low"
sev_conf = cl.severityConfidence if cl else 0.6
pdays = pr.predictedDays if pr else 0.0
anom = pr.anomalyDetection.anomalyScore if pr and pr.anomalyDetection else 0.0
sev_s = _severity_to_score(sev)
d_s = _normalize_days(pdays)
cat_w = 1.0 - float(eff.get(cat, 0.8))
risk = min(1.0, 0.5 * sev_s + 0.25 * d_s + 0.15 * anom + 0.10 * cat_w)
recs: List[Dict[str, Any]] = []
if action_service:
try:
recs_resp = action_service.recommend(
report=item.get("Report", "") or "",
issue_type=cat,
severity=sev,
area=area if area else None,
airline=item.get("Airlines") or None,
top_n=5,
)
recs = recs_resp.get("recommendations", [])
except Exception:
recs = []
prev = _extract_prevention([r.get("action", "") for r in recs])
items.append(
RiskItem(
reportId=f"row_{i}",
severity=sev,
severityConfidence=sev_conf,
predictedDays=pdays,
anomalyScore=anom,
category=cat,
hub=hub,
area=area,
riskScore=round(risk, 3),
priority=_priority_from_score(risk),
recommendedActions=recs[:5],
preventiveSuggestions=prev,
)
)
groups: Dict[str, Dict[str, Any]] = {}
for it, raw in zip(items, data):
key = f"{it.category}|{it.hub}|{it.area}"
g = groups.get(key) or {"key": key, "category": it.category, "hub": it.hub, "area": it.area, "count": 0, "avgRisk": 0.0, "avgDays": 0.0, "highSeverityShare": 0.0}
g["count"] += 1
g["avgRisk"] += it.riskScore
g["avgDays"] += it.predictedDays
g["highSeverityShare"] += 1.0 if it.severity in ("Critical", "High") else 0.0
groups[key] = g
patterns = []
for g in groups.values():
c = g["count"]
g["avgRisk"] = round(g["avgRisk"] / max(1, c), 3)
g["avgDays"] = round(g["avgDays"] / max(1, c), 2)
g["highSeverityShare"] = round(g["highSeverityShare"] / max(1, c), 3)
patterns.append(g)
patterns.sort(key=lambda x: (-x["avgRisk"], -x["highSeverityShare"], -x["avgDays"], -x["count"]))
response.risk = RiskAssessmentResponse(
items=sorted(items, key=lambda x: -x.riskScore),
topPatterns=patterns[:5],
metadata={"count": len(items)},
)
if compact:
if response.regression and response.regression.predictions:
for p in response.regression.predictions:
p.shapExplanation = None
p.anomalyDetection = None
if response.nlp:
response.nlp.entities = []
response.nlp.summaries = []
# Calculate processing time
processing_time = (datetime.now() - start_time).total_seconds() * 1000
response.metadata.processingTime = round(processing_time, 2)
logger.info(f"Analysis completed in {processing_time:.2f}ms")
return response
@app.post(
"/api/ai/analyze",
response_model=AnalysisResponse,
tags=["Analysis"],
summary="Analyze Irregularity Reports",
response_description="Analysis results including predictions, severity, and entities.",
)
async def analyze_reports(request: AnalysisRequest, compact: bool = False):
"""
Perform comprehensive AI analysis on a batch of irregularity reports.
- **Regression**: Predicts days to resolve based on category and description.
- **NLP**: Classifies severity, extracts entities (Flight No, Airline), and summarizes text.
- **Trends**: Aggregates data by Airline, Hub, and Category.
The endpoint accepts a list of `IrregularityReport` objects.
"""
try:
# Use direct data
if not request.data:
raise HTTPException(
status_code=400,
detail="No data provided. Either sheetId or data must be specified.",
)
# Convert IrregularityReport objects to dicts
data = [report.model_dump(exclude_none=True) for report in request.data]
return perform_analysis(data, request.options, compact)
except HTTPException:
raise
except Exception as e:
logger.error(f"Analysis error: {str(e)}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
def background_analysis_task(job_id: str, data: List[Dict], options: AnalysisOptions, compact: bool):
"""Background task for analysis"""
try:
job_service.update_job(job_id, JobStatus.PROCESSING)
response = perform_analysis(data, options, compact)
job_service.update_job(job_id, JobStatus.COMPLETED, result=response.model_dump())
except Exception as e:
logger.error(f"Job {job_id} failed: {e}")
job_service.update_job(job_id, JobStatus.FAILED, error=str(e))
@app.post(
"/api/ai/analyze-async",
response_model=Dict[str, str],
tags=["Analysis", "Jobs"],
summary="Start Async Analysis Job",
)
async def analyze_async(
request: AnalysisRequest, background_tasks: BackgroundTasks, compact: bool = False
):
"""
Start a background analysis job for large datasets.
Returns a `jobId` immediately, which can be used to poll status via `/api/ai/jobs/{jobId}`.
"""
if not request.data:
raise HTTPException(status_code=400, detail="No data provided")
data = [report.model_dump(exclude_none=True) for report in request.data]
job_id = job_service.create_job()
background_tasks.add_task(background_analysis_task, job_id, data, request.options, compact)
return {"job_id": job_id, "status": "queued"}
@app.get(
"/api/ai/jobs/{job_id}",
tags=["Jobs"],
summary="Get Job Status",
)
async def get_job_status(job_id: str):
"""
Retrieve the status and results of a background analysis job.
Possible statuses: `queued`, `processing`, `completed`, `failed`.
"""
job = job_service.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return job
@app.post(
"/api/ai/predict-single",
tags=["Analysis"],
summary="Real-time Single Prediction",
)
async def predict_single(report: IrregularityReport):
"""
Get immediate AI predictions for a single irregularity report.
Useful for real-time validation or "what-if" analysis in the UI.
"""
try:
report_dict = report.model_dump(exclude_none=True)
predictions = model_service.predict_regression([report_dict])
classifications = model_service.classify_text([report_dict])
entities = model_service.extract_entities([report_dict])
summaries = model_service.generate_summary([report_dict])
sentiment = model_service.analyze_sentiment([report_dict])
return {
"prediction": predictions[0],
"classification": classifications[0],
"entities": entities[0],
"summary": summaries[0],
"sentiment": sentiment[0],
"modelLoaded": model_service.model_loaded,
}
except Exception as e:
logger.error(f"Single prediction error: {str(e)}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@app.post(
"/api/ai/train",
tags=["Training"],
summary="Trigger Model Retraining",
)
async def train_models(background_tasks: BackgroundTasks, force: bool = False):
"""
Trigger a background task to retrain AI models.
Checks if new data is available in Google Sheets before training, unless `force=True`.
"""
from scripts.scheduled_training import TrainingScheduler
def run_training_task():
scheduler = TrainingScheduler()
result = scheduler.run_training(force=force)
logger.info(f"Training completed: {result}")
background_tasks.add_task(run_training_task)
return {
"status": "training_queued",
"message": "Model retraining has been started in the background",
"force": force,
"timestamp": datetime.now().isoformat(),
}
@app.get(
"/api/ai/train/status",
tags=["Training"],
summary="Get Training Status",
)
async def training_status():
"""
Get the status of the latest training job and training history.
"""
from scripts.scheduled_training import TrainingScheduler
scheduler = TrainingScheduler()
status = scheduler.get_status()
return {
"status": "success",
"data": status,
"timestamp": datetime.now().isoformat(),
}
@app.get("/api/ai/model-info")
async def model_info():
"""Get current model information"""
return {
"regression": {
"version": model_service.regression_version,
"type": "GradientBoostingRegressor",
"status": "loaded" if model_service.model_loaded else "unavailable",
"last_trained": "2025-01-15",
"metrics": model_service.model_metrics
if model_service.model_loaded
else None,
},
"nlp": {
"version": model_service.nlp_version,
"type": "Rule-based + Keyword extraction",
"status": "active",
"tasks": ["classification", "ner", "summarization", "sentiment"],
"note": "Full ML NLP models coming soon",
},
}
@app.post("/api/ai/cache/invalidate")
async def invalidate_cache(sheet_name: Optional[str] = None):
"""Invalidate cache for sheets data"""
cache = get_cache()
if sheet_name:
pattern = f"sheets:*{sheet_name}*"
deleted = cache.delete_pattern(pattern)
return {
"status": "success",
"message": f"Invalidated cache for sheet: {sheet_name}",
"keys_deleted": deleted,
}
else:
deleted = cache.delete_pattern("sheets:*")
return {
"status": "success",
"message": "Invalidated all sheets cache",
"keys_deleted": deleted,
}
@app.get("/api/ai/cache/status")
async def cache_status():
"""Get cache status and statistics"""
cache = get_cache()
return cache.health_check()
class AnalyzeAllResponse(BaseModel):
status: str
metadata: Dict[str, Any]
sheets: Dict[str, Any]
results: List[Dict[str, Any]]
summary: Dict[str, Any]
timestamp: str
@app.get("/api/ai/analyze-all", response_model=AnalyzeAllResponse)
async def analyze_all_sheets(
bypass_cache: bool = False,
include_regression: bool = True,
include_nlp: bool = True,
include_trends: bool = True,
max_rows_per_sheet: int = 10000,
compact: bool = False,
):
"""
Analyze ALL rows from all Google Sheets
Fetches data from both NON CARGO and CGO sheets, analyzes each row,
and returns comprehensive results.
Args:
bypass_cache: Skip cache and fetch fresh data
include_regression: Include regression predictions
include_nlp: Include NLP analysis (severity, entities, summary)
include_trends: Include trend analysis
max_rows_per_sheet: Maximum rows to process per sheet
"""
start_time = datetime.now()
try:
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(
status_code=500, detail="GOOGLE_SHEET_ID not configured"
)
all_data = []
sheet_info = {}
sheets_to_fetch = [
{"name": "NON CARGO", "range": f"A1:AA{max_rows_per_sheet + 1}"},
{"name": "CGO", "range": f"A1:Z{max_rows_per_sheet + 1}"},
]
for sheet in sheets_to_fetch:
try:
sheet_name = sheet["name"]
range_str = sheet["range"]
logger.info(f"Fetching {sheet_name}...")
data = sheets_service.fetch_sheet_data(
spreadsheet_id, sheet_name, range_str, bypass_cache=bypass_cache
)
for row in data:
row["_source_sheet"] = sheet_name
all_data.append(row)
sheet_info[sheet_name] = {
"rows_fetched": len(data),
"status": "success",
}
except Exception as e:
logger.error(f"Failed to fetch {sheet['name']}: {e}")
sheet_info[sheet["name"]] = {
"rows_fetched": 0,
"status": "error",
"error": str(e),
}
total_records = len(all_data)
if total_records == 0:
raise HTTPException(status_code=404, detail="No data found in any sheet")
logger.info(f"Analyzing {total_records} total records...")
results = []
batch_size = 100
for i in range(0, total_records, batch_size):
batch = all_data[i : i + batch_size]
if include_regression:
regression_preds = model_service.predict_regression(batch)
else:
regression_preds = [None] * len(batch)
if include_nlp:
classifications = model_service.classify_text(batch)
entities = model_service.extract_entities(batch)
summaries = model_service.generate_summary(batch)
sentiments = model_service.analyze_sentiment(batch)
else:
classifications = [None] * len(batch)
entities = [None] * len(batch)
summaries = [None] * len(batch)
sentiments = [None] * len(batch)
for j, row in enumerate(batch):
result = {
"rowId": row.get("_row_id", f"row_{i + j}"),
"sourceSheet": row.get("_source_sheet", "Unknown"),
"originalData": {
"date": row.get("Date_of_Event"),
"airline": row.get("Airlines"),
"flightNumber": row.get("Flight_Number"),
"branch": row.get("Branch"),
"hub": row.get("HUB"),
"route": row.get("Route"),
"category": row.get("Report_Category"),
"issueType": row.get("Irregularity_Complain_Category"),
"report": row.get("Report"),
"status": row.get("Status"),
},
}
if regression_preds[j]:
pred = {
"predictedDays": regression_preds[j].predictedDays,
"confidenceInterval": regression_preds[j].confidenceInterval,
"hasUnknownCategories": regression_preds[j].hasUnknownCategories,
}
if not compact:
pred["shapExplanation"] = (
regression_preds[j].shapExplanation.model_dump()
if regression_preds[j].shapExplanation
else None
)
pred["anomalyDetection"] = (
regression_preds[j].anomalyDetection.model_dump()
if regression_preds[j].anomalyDetection
else None
)
result["prediction"] = pred
if classifications[j]:
result["classification"] = classifications[j].model_dump()
if entities[j] and not compact:
result["entities"] = entities[j].model_dump()
if summaries[j] and not compact:
result["summary"] = summaries[j].model_dump()
if sentiments[j] and not compact:
result["sentiment"] = sentiments[j].model_dump()
results.append(result)
summary = {
"totalRecords": total_records,
"sheetsProcessed": len(
[s for s in sheet_info.values() if s["status"] == "success"]
),
"regressionEnabled": include_regression,
"nlpEnabled": include_nlp,
}
if include_nlp and results:
severity_counts = {}
for r in results:
sev = r.get("classification", {}).get("severity", "Unknown")
severity_counts[sev] = severity_counts.get(sev, 0) + 1
summary["severityDistribution"] = severity_counts
if include_regression and results:
predictions = [
r["prediction"]["predictedDays"] for r in results if r.get("prediction")
]
if predictions:
summary["predictionStats"] = {
"min": round(min(predictions), 2),
"max": round(max(predictions), 2),
"mean": round(sum(predictions) / len(predictions), 2),
}
processing_time = (datetime.now() - start_time).total_seconds()
return AnalyzeAllResponse(
status="success",
metadata={
"totalRecords": total_records,
"processingTimeSeconds": round(processing_time, 2),
"recordsPerSecond": round(total_records / processing_time, 2)
if processing_time > 0
else 0,
"modelVersions": {
"regression": model_service.regression_version,
"nlp": model_service.nlp_version,
},
},
sheets=sheet_info,
results=results,
summary=summary,
timestamp=datetime.now().isoformat(),
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Analyze all error: {str(e)}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
# ============== Risk Scoring Endpoints ==============
@app.get("/api/ai/risk/summary")
async def risk_summary():
"""Get overall risk summary for all entities"""
from data.risk_service import get_risk_service
risk_service = get_risk_service()
return risk_service.get_risk_summary()
@app.get("/api/ai/risk/airlines")
async def airline_risks():
"""Get risk scores for all airlines"""
from data.risk_service import get_risk_service
risk_service = get_risk_service()
return risk_service.get_all_airline_risks()
@app.get("/api/ai/risk/airlines/{airline_name}")
async def airline_risk(airline_name: str):
"""Get risk score for a specific airline"""
from data.risk_service import get_risk_service
risk_service = get_risk_service()
risk_data = risk_service.get_airline_risk(airline_name)
if not risk_data:
raise HTTPException(
status_code=404, detail=f"Airline '{airline_name}' not found"
)
recommendations = risk_service.get_risk_recommendations("airline", airline_name)
return {
"airline": airline_name,
"risk_data": risk_data,
"recommendations": recommendations,
}
@app.get("/api/ai/risk/branches")
async def branch_risks():
"""Get risk scores for all branches"""
from data.risk_service import get_risk_service
risk_service = get_risk_service()
return risk_service.get_all_branch_risks()
@app.get("/api/ai/risk/hubs")
async def hub_risks():
"""Get risk scores for all hubs"""
from data.risk_service import get_risk_service
risk_service = get_risk_service()
return risk_service.get_all_hub_risks()
@app.post("/api/ai/risk/calculate")
async def calculate_risk_scores(bypass_cache: bool = False):
"""Calculate risk scores from current Google Sheets data"""
from data.risk_service import get_risk_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
# Fetch all data
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA2000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z2000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
risk_service = get_risk_service()
risk_data = risk_service.calculate_all_risk_scores(all_data)
return {
"status": "success",
"records_processed": len(all_data),
"risk_summary": risk_service.get_risk_summary(),
}
# ============== Subcategory Classification Endpoints ==============
@app.post("/api/ai/subcategory")
async def classify_subcategory(
report: str,
area: Optional[str] = None,
issue_type: Optional[str] = None,
root_cause: Optional[str] = None,
):
"""Classify report into subcategory"""
from data.subcategory_service import get_subcategory_classifier
classifier = get_subcategory_classifier()
result = classifier.classify(report, area, issue_type, root_cause)
return result
@app.get("/api/ai/subcategory/categories")
async def get_subcategories(area: Optional[str] = None):
"""Get list of available subcategories"""
from data.subcategory_service import get_subcategory_classifier
classifier = get_subcategory_classifier()
return classifier.get_available_categories(area)
# ============== Action Recommendation Endpoints ==============
@app.post("/api/ai/action/recommend")
async def recommend_actions(
report: str,
issue_type: str,
severity: str = "Medium",
area: Optional[str] = None,
airline: Optional[str] = None,
top_n: int = 5,
):
"""Get action recommendations for an issue"""
from data.action_service import get_action_service
action_service = get_action_service()
recommendations = action_service.recommend(
report=report,
issue_type=issue_type,
severity=severity,
area=area,
airline=airline,
top_n=top_n,
)
return recommendations
@app.post("/api/ai/action/train")
async def train_action_recommender(
bypass_cache: bool = False, background_tasks: BackgroundTasks = None
):
"""Train action recommender from historical data"""
from data.action_service import get_action_service
from data.sheets_service import GoogleSheetsService
from data.similarity_service import get_similarity_service
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA2000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z2000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
similarity_service = get_similarity_service()
similarity_service.build_index(all_data)
action_service = get_action_service()
action_service.train_from_data(all_data)
return {
"status": "success",
"records_processed": len(all_data),
}
# ============== Advanced NER Endpoints ==============
@app.post("/api/ai/ner/extract")
async def extract_entities(text: str):
"""Extract entities from text"""
from data.advanced_ner_service import get_advanced_ner
ner = get_advanced_ner()
entities = ner.extract(text)
summary = ner.extract_summary(text)
return {
"entities": entities,
"summary": summary,
}
# ============== Similarity Endpoints ==============
@app.post("/api/ai/similar")
async def find_similar_reports(
text: str,
top_k: int = 5,
threshold: float = 0.3,
):
"""Find similar reports"""
from data.similarity_service import get_similarity_service
similarity_service = get_similarity_service()
similar = similarity_service.find_similar(text, top_k, threshold)
return {
"query_preview": text[:100],
"similar_reports": similar,
}
@app.post("/api/ai/similar/build-index")
async def build_similarity_index(bypass_cache: bool = False):
"""Build similarity index from Google Sheets data"""
from data.similarity_service import get_similarity_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA2000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z2000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
similarity_service = get_similarity_service()
similarity_service.build_index(all_data)
return {
"status": "success",
"records_indexed": len(all_data),
}
# ============== Forecasting Endpoints ==============
@app.get("/api/ai/forecast/issues")
async def forecast_issues(periods: int = 4):
"""Forecast issue volume for next periods"""
from data.forecast_service import get_forecast_service
forecast_service = get_forecast_service()
forecast = forecast_service.forecast_issues(periods)
return forecast
@app.get("/api/ai/forecast/trends")
async def predict_trends():
"""Predict category trends"""
from data.forecast_service import get_forecast_service
forecast_service = get_forecast_service()
trends = forecast_service.predict_category_trends()
return trends
@app.get("/api/ai/forecast/seasonal")
async def get_seasonal_patterns():
"""Get seasonal patterns"""
from data.forecast_service import get_forecast_service
forecast_service = get_forecast_service()
patterns = forecast_service.get_seasonal_patterns()
return patterns
@app.post("/api/ai/forecast/build")
async def build_forecast_data(bypass_cache: bool = False):
"""Build forecast historical data from Google Sheets"""
from data.forecast_service import get_forecast_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA2000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z2000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
forecast_service = get_forecast_service()
forecast_service.build_historical_data(all_data)
return {
"status": "success",
"records_processed": len(all_data),
"forecast_summary": forecast_service.get_forecast_summary(),
}
# ============== Report Generation Endpoints ==============
@app.post("/api/ai/report/generate")
async def generate_report(
row_id: str,
bypass_cache: bool = False,
):
"""Generate formal incident report"""
from data.report_generator_service import get_report_generator
from data.sheets_service import GoogleSheetsService
from data.risk_service import get_risk_service
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
# Fetch all data and find the record
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA2000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z2000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
record = None
for r in all_data:
if r.get("_row_id") == row_id:
record = r
break
if not record:
raise HTTPException(status_code=404, detail=f"Record '{row_id}' not found")
# Generate analysis
report_text = record.get("Report", "") + " " + record.get("Root_Caused", "")
analysis = {
"severity": model_service._classify_severity_fallback([report_text])[0].get(
"severity", "Medium"
),
"issueType": record.get("Irregularity_Complain_Category", ""),
}
# Get risk data
risk_service = get_risk_service()
airline = record.get("Airlines", "")
risk_data = risk_service.get_airline_risk(airline)
# Generate report
report_gen = get_report_generator()
formal_report = report_gen.generate_incident_report(record, analysis, risk_data)
exec_summary = report_gen.generate_executive_summary(record, analysis)
json_report = report_gen.generate_json_report(record, analysis, risk_data)
return {
"row_id": row_id,
"formal_report": formal_report,
"executive_summary": exec_summary,
"structured_report": json_report,
}
# ============== Dashboard Endpoints ==============
@app.get("/api/ai/dashboard/summary")
async def dashboard_summary(bypass_cache: bool = False):
"""Get comprehensive dashboard summary"""
from data.risk_service import get_risk_service
from data.forecast_service import get_forecast_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
# Fetch data
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA2000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z2000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
# Get risk summary
risk_service = get_risk_service()
risk_summary = risk_service.get_risk_summary()
# Get forecast summary
forecast_service = get_forecast_service()
forecast_summary = forecast_service.get_forecast_summary()
# Calculate statistics
severity_dist = Counter()
category_dist = Counter()
airline_dist = Counter()
for record in all_data:
report_text = record.get("Report", "") + " " + record.get("Root_Caused", "")
sev = model_service._classify_severity_fallback([report_text])[0].get(
"severity", "Low"
)
severity_dist[sev] += 1
category_dist[record.get("Irregularity_Complain_Category", "Unknown")] += 1
airline_dist[record.get("Airlines", "Unknown")] += 1
return {
"total_records": len(all_data),
"sheets": {
"non_cargo": len(non_cargo),
"cargo": len(cargo),
},
"severity_distribution": dict(severity_dist),
"category_distribution": dict(category_dist.most_common(10)),
"top_airlines": dict(airline_dist.most_common(10)),
"risk_summary": risk_summary,
"forecast_summary": forecast_summary,
"model_status": {
"regression": model_service.model_loaded,
"nlp": model_service.nlp_service is not None,
},
"last_updated": datetime.now().isoformat(),
}
# ============== Seasonality Endpoints ==============
@app.get("/api/ai/seasonality/summary")
async def seasonality_summary(category_type: Optional[str] = None):
"""
Get seasonality summary and patterns
Args:
category_type: "landside_airside", "cgo", or None for both
"""
from data.seasonality_service import get_seasonality_service
service = get_seasonality_service()
return service.get_seasonality_summary(category_type)
@app.get("/api/ai/seasonality/forecast")
async def seasonality_forecast(
category_type: Optional[str] = None,
periods: int = 4,
granularity: str = "weekly",
):
"""
Forecast issue volumes
Args:
category_type: "landside_airside", "cgo", or None for both
periods: Number of periods to forecast
granularity: "daily", "weekly", or "monthly"
"""
from data.seasonality_service import get_seasonality_service
service = get_seasonality_service()
return service.forecast(category_type, periods, granularity)
@app.get("/api/ai/seasonality/peaks")
async def seasonality_peaks(
category_type: Optional[str] = None, threshold: float = 1.2
):
"""
Identify peak periods
Args:
category_type: "landside_airside", "cgo", or None for both
threshold: Multiplier above average (1.2 = 20% above)
"""
from data.seasonality_service import get_seasonality_service
service = get_seasonality_service()
return service.get_peak_periods(category_type, threshold)
@app.post("/api/ai/seasonality/build")
async def build_seasonality_patterns(bypass_cache: bool = False):
"""Build seasonality patterns from Google Sheets data"""
from data.seasonality_service import get_seasonality_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA5000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z5000", bypass_cache=bypass_cache
)
for row in non_cargo:
row["_sheet_name"] = "NON CARGO"
for row in cargo:
row["_sheet_name"] = "CGO"
all_data = non_cargo + cargo
service = get_seasonality_service()
result = service.build_patterns(all_data)
return {
"status": "success",
"records_processed": len(all_data),
"patterns": result,
}
# ============== Root Cause Endpoints ==============
@app.post("/api/ai/root-cause/classify")
async def classify_root_cause(
root_cause: str,
report: Optional[str] = None,
area: Optional[str] = None,
category: Optional[str] = None,
):
"""
Classify a root cause text into categories
Categories: Equipment Failure, Staff Competency, Process/Procedure,
Communication, External Factors, Documentation, Training Gap, Resource/Manpower
"""
from data.root_cause_service import get_root_cause_service
service = get_root_cause_service()
context = {"area": area, "category": category}
result = service.classify(root_cause, report or "", context)
return result
@app.post("/api/ai/root-cause/classify-batch")
async def classify_root_cause_batch(bypass_cache: bool = False):
"""Classify root causes for all records"""
from data.root_cause_service import get_root_cause_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA5000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z5000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
service = get_root_cause_service()
results = service.classify_batch(all_data)
return {
"status": "success",
"records_processed": len(all_data),
"classifications": results[:100],
"total_classified": len(
[r for r in results if r["primary_category"] != "Unknown"]
),
}
@app.get("/api/ai/root-cause/categories")
async def get_root_cause_categories():
"""Get all available root cause categories"""
from data.root_cause_service import get_root_cause_service
service = get_root_cause_service()
return service.get_categories()
@app.get("/api/ai/root-cause/stats")
async def get_root_cause_stats(source: Optional[str] = None, bypass_cache: bool = False):
"""
Get root cause statistics from data
Args:
source: "NON CARGO", "CGO", or None for both
bypass_cache: Skip cache and fetch fresh data
"""
from data.root_cause_service import get_root_cause_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
all_data = []
# Conditional fetching based on source to reduce I/O and processing
if not source or source.upper() == "NON CARGO":
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA5000", bypass_cache=bypass_cache
)
all_data.extend(non_cargo)
if not source or source.upper() == "CGO":
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z5000", bypass_cache=bypass_cache
)
all_data.extend(cargo)
service = get_root_cause_service()
stats = service.get_statistics(all_data)
return stats
@app.post("/api/ai/root-cause/train")
async def train_root_cause_classifier(background_tasks: BackgroundTasks, bypass_cache: bool = False):
"""Train root cause classifier from historical data"""
from data.root_cause_service import get_root_cause_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA5000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z5000", bypass_cache=bypass_cache
)
all_data = non_cargo + cargo
service = get_root_cause_service()
# Offload the intensive training process to the background
background_tasks.add_task(service.train_from_data, all_data)
return {
"status": "training_started",
"records_fetched": len(all_data),
"message": "Classification training is now running in the background. The model will be automatically updated once complete."
}
# ============== Category Summarization Endpoints ==============
class CategorySummaryResponse(BaseModel):
status: str
category_type: str
summary: Dict[str, Any]
timestamp: str
@app.get("/api/ai/summarize", response_model=CategorySummaryResponse)
async def summarize_by_category(category: str = "all", bypass_cache: bool = False):
"""
Get summarized insights for Non-cargo and/or CGO categories
Query Parameters:
category: "non_cargo", "cgo", or "all" (default: "all")
bypass_cache: Skip cache and fetch fresh data (default: false)
Returns aggregated summary including:
- Severity distribution
- Top categories, airlines, hubs, branches
- Key insights and recommendations
- Common issues
- Monthly trends
"""
from data.category_summarization_service import get_category_summarization_service
from data.sheets_service import GoogleSheetsService
valid_categories = ["non_cargo", "cgo", "all"]
if category.lower() not in valid_categories:
raise HTTPException(
status_code=400,
detail=f"Invalid category. Must be one of: {valid_categories}",
)
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA5000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z5000", bypass_cache=bypass_cache
)
for row in non_cargo:
row["_sheet_name"] = "NON CARGO"
for row in cargo:
row["_sheet_name"] = "CGO"
all_data = non_cargo + cargo
summarization_service = get_category_summarization_service()
summary = summarization_service.summarize_category(all_data, category.lower())
return CategorySummaryResponse(
status="success",
category_type=category.lower(),
summary=summary,
timestamp=datetime.now().isoformat(),
)
@app.get("/api/ai/summarize/non-cargo")
async def summarize_non_cargo(bypass_cache: bool = False):
"""Quick endpoint for Non-cargo summary"""
return await summarize_by_category(category="non_cargo", bypass_cache=bypass_cache)
@app.get("/api/ai/summarize/cgo")
async def summarize_cgo(bypass_cache: bool = False):
"""Quick endpoint for CGO (Cargo) summary"""
return await summarize_by_category(category="cgo", bypass_cache=bypass_cache)
@app.get("/api/ai/summarize/compare")
async def compare_categories(bypass_cache: bool = False):
"""Compare Non-cargo and CGO categories side by side"""
return await summarize_by_category(category="all", bypass_cache=bypass_cache)
# ============== Branch Analytics Endpoints ==============
@app.get("/api/ai/branch/summary")
async def branch_analytics_summary(category_type: Optional[str] = None):
"""
Get branch analytics summary
Args:
category_type: "landside_airside", "cgo", or None for both
"""
from data.branch_analytics_service import get_branch_analytics_service
service = get_branch_analytics_service()
return service.get_summary(category_type)
@app.get("/api/ai/branch/{branch_name}")
async def get_branch_metrics(branch_name: str, category_type: Optional[str] = None):
"""
Get metrics for a specific branch
Args:
branch_name: Branch name
category_type: "landside_airside", "cgo", or None for combined
"""
from data.branch_analytics_service import get_branch_analytics_service
service = get_branch_analytics_service()
data = service.get_branch(branch_name, category_type)
if not data:
raise HTTPException(status_code=404, detail=f"Branch '{branch_name}' not found")
return data
@app.get("/api/ai/branch/ranking")
async def branch_ranking(
category_type: Optional[str] = None,
sort_by: str = "risk_score",
limit: int = 20,
):
"""
Get branch ranking
Args:
category_type: "landside_airside", "cgo", or None for both
sort_by: Field to sort by (risk_score, total_issues, critical_high_count)
limit: Maximum branches to return
"""
from data.branch_analytics_service import get_branch_analytics_service
service = get_branch_analytics_service()
return service.get_ranking(category_type, sort_by, limit)
@app.get("/api/ai/branch/comparison")
async def branch_comparison():
"""Compare all branches across category types"""
from data.branch_analytics_service import get_branch_analytics_service
service = get_branch_analytics_service()
return service.get_comparison()
@app.post("/api/ai/branch/calculate")
async def calculate_branch_metrics(bypass_cache: bool = False):
"""Calculate branch metrics from Google Sheets data"""
from data.branch_analytics_service import get_branch_analytics_service
from data.sheets_service import GoogleSheetsService
cache = get_cache() if not bypass_cache else None
sheets_service = GoogleSheetsService(cache=cache)
spreadsheet_id = os.getenv("GOOGLE_SHEET_ID")
if not spreadsheet_id:
raise HTTPException(status_code=500, detail="GOOGLE_SHEET_ID not configured")
non_cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "NON CARGO", "A1:AA5000", bypass_cache=bypass_cache
)
cargo = sheets_service.fetch_sheet_data(
spreadsheet_id, "CGO", "A1:Z5000", bypass_cache=bypass_cache
)
for row in non_cargo:
row["_sheet_name"] = "NON CARGO"
for row in cargo:
row["_sheet_name"] = "CGO"
all_data = non_cargo + cargo
service = get_branch_analytics_service()
result = service.calculate_branch_metrics(all_data)
return {
"status": "success",
"records_processed": len(all_data),
"metrics": result,
}
# ============== Main ==============
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("API_PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port)
|