Spaces:
Running
Running
File size: 87,278 Bytes
9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e bee00cc 9089e3e | 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 | import os
import json
import time
import uuid
import shutil
import traceback
import re
import sys
import importlib.util
import threading
import subprocess
import concurrent.futures
from urllib.parse import urlsplit, urlunsplit
import cv2
import numpy as np
from fastapi import FastAPI, File, UploadFile, Form, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from typing import List
from huggingface_hub import hf_hub_download, snapshot_download, HfApi
app = FastAPI(title="Sporalize Labs 3D Analysis Engine")
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
def default_runtime_root():
if os.path.isdir("/data"):
return os.path.join("/data", "sporalize_runtime")
return os.path.join(os.path.expanduser("~"), ".sporalize_runtime")
RUNTIME_ROOT = os.environ.get("SPORALIZE_RUNTIME_DIR", default_runtime_root())
ASSETS_RUNTIME_ROOT = os.environ.get("SPORALIZE_ASSETS_DIR", os.path.join(RUNTIME_ROOT, "assets"))
WEIGHTS_RUNTIME_ROOT = os.environ.get("SPORALIZE_WEIGHTS_DIR", os.path.join(RUNTIME_ROOT, "weights"))
DEFAULT_LOCAL_STORAGE_ROOT = os.path.join(CURRENT_DIR, "Storage")
if not os.path.isdir("/data") and not os.access(CURRENT_DIR, os.W_OK):
DEFAULT_LOCAL_STORAGE_ROOT = os.path.join(RUNTIME_ROOT, "storage")
STORAGE_ROOT = os.environ.get(
"SPORALIZE_STORAGE_DIR",
os.path.join("/data", "sporalize_storage") if os.path.isdir("/data") else DEFAULT_LOCAL_STORAGE_ROOT,
)
STORAGE_DATASET_REPO_ID = os.environ.get("SPORALIZE_STORAGE_REPO_ID", "Shoraky/SporalizeLabs-runtime-private").strip()
STORAGE_DATASET_REPO_TYPE = os.environ.get("SPORALIZE_STORAGE_REPO_TYPE", "dataset").strip()
STORAGE_DATASET_PATH = os.environ.get("SPORALIZE_STORAGE_DATASET_PATH", "Storage").strip("/").strip()
STORAGE_SYNC_INTERVAL_SECONDS = float(os.environ.get("SPORALIZE_STORAGE_SYNC_INTERVAL_SECONDS", "20"))
CONFIGURED_ASSETS_REPO_ID = os.environ.get("SPORALIZE_ASSETS_REPO_ID", "").strip()
ASSETS_REPO_ID = CONFIGURED_ASSETS_REPO_ID or STORAGE_DATASET_REPO_ID
ASSETS_REPO_TYPE = os.environ.get("SPORALIZE_ASSETS_REPO_TYPE", STORAGE_DATASET_REPO_TYPE or "dataset").strip() or "dataset"
ASSETS_REVISION = os.environ.get("SPORALIZE_ASSETS_REVISION")
ASSETS_REVISION = ASSETS_REVISION.strip() if ASSETS_REVISION else None
USE_LOCAL_ASSETS = os.environ.get("SPORALIZE_USE_LOCAL_ASSETS", "").strip().lower() in {"1", "true", "yes", "on"}
_storage_sync_lock = threading.Lock()
_storage_last_sync_ts = 0.0
DEFAULT_WEIGHT_SPECS = {
"POSE_PATH": {
"filename": "vitpose-s-coco_25.onnx",
"repo_id": os.environ.get("SPORALIZE_POSE_MODEL_REPO_ID", "JunkyByte/easy_ViTPose"),
"repo_type": os.environ.get("SPORALIZE_POSE_MODEL_REPO_TYPE", "model"),
"repo_file": os.environ.get("SPORALIZE_POSE_MODEL_FILE", "onnx/coco_25/vitpose-25-s.onnx"),
"override_env": "SPORALIZE_POSE_MODEL_PATH",
"local_fallback": os.path.join(CURRENT_DIR, "Weights", "vitpose-s-coco_25.onnx"),
},
"YOLO_PATH": {
"filename": "yolov8m.pt",
"repo_id": os.environ.get("SPORALIZE_YOLO_MODEL_REPO_ID", "Ultralytics/YOLOv8"),
"repo_type": os.environ.get("SPORALIZE_YOLO_MODEL_REPO_TYPE", "model"),
"repo_file": os.environ.get("SPORALIZE_YOLO_MODEL_FILE", "yolov8m.pt"),
"override_env": "SPORALIZE_YOLO_MODEL_PATH",
"local_fallback": os.path.join(CURRENT_DIR, "Weights", "yolov8m.pt"),
},
}
runtime_state = {
"ready": False,
"pipeline_root": None,
"pipeline_source": None,
"assets_repo_id": None,
"assets_repo_type": None,
"assets_revision": None,
"run_pipeline": None,
"weights": {},
}
def get_hf_token():
return os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
def hf_storage_enabled():
return bool(STORAGE_DATASET_REPO_ID and STORAGE_DATASET_PATH)
def hf_storage_path(*parts: str) -> str:
normalized = [STORAGE_DATASET_PATH]
normalized.extend(part.strip("/").replace("\\", "/") for part in parts if part is not None and str(part).strip("/"))
return "/".join(segment for segment in normalized if segment)
def sync_storage_from_hf(force: bool = False):
global _storage_last_sync_ts
if not hf_storage_enabled():
return
now = time.time()
if not force and (now - _storage_last_sync_ts) < STORAGE_SYNC_INTERVAL_SECONDS:
return
with _storage_sync_lock:
now = time.time()
if not force and (now - _storage_last_sync_ts) < STORAGE_SYNC_INTERVAL_SECONDS:
return
print(f"[SPORALIZE] Storage sync: downloading from HF repo '{STORAGE_DATASET_REPO_ID}'...", flush=True)
t0 = time.time()
sync_cache_root = os.path.join(RUNTIME_ROOT, "storage-sync-cache")
os.makedirs(sync_cache_root, exist_ok=True)
local_repo_dir = os.path.join(sync_cache_root, safe_name(STORAGE_DATASET_REPO_ID))
snapshot_download(
repo_id=STORAGE_DATASET_REPO_ID,
repo_type=STORAGE_DATASET_REPO_TYPE,
token=get_hf_token(),
local_dir=local_repo_dir,
allow_patterns=[f"{STORAGE_DATASET_PATH}/**"],
)
source_storage = os.path.join(local_repo_dir, STORAGE_DATASET_PATH)
if os.path.isdir(source_storage):
if os.path.isdir(STORAGE_ROOT):
shutil.rmtree(STORAGE_ROOT, ignore_errors=True)
shutil.copytree(source_storage, STORAGE_ROOT, dirs_exist_ok=True)
_storage_last_sync_ts = time.time()
print(f"[SPORALIZE] Storage sync: done in {time.time() - t0:.1f}s", flush=True)
def push_session_to_hf(player_id: str, session_id: str, session_dir: str):
if not hf_storage_enabled():
return
api = HfApi(token=get_hf_token())
api.upload_folder(
repo_id=STORAGE_DATASET_REPO_ID,
repo_type=STORAGE_DATASET_REPO_TYPE,
folder_path=session_dir,
path_in_repo=hf_storage_path(safe_name(player_id), safe_name(session_id)),
commit_message=f"Add session {safe_name(session_id)} for player {safe_name(player_id)}",
)
def delete_session_from_hf(player_id: str, session_id: str):
if not hf_storage_enabled():
return
api = HfApi(token=get_hf_token())
api.delete_folder(
repo_id=STORAGE_DATASET_REPO_ID,
repo_type=STORAGE_DATASET_REPO_TYPE,
path_in_repo=hf_storage_path(safe_name(player_id), safe_name(session_id)),
commit_message=f"Delete session {safe_name(session_id)} for player {safe_name(player_id)}",
)
def delete_player_from_hf(player_id: str):
if not hf_storage_enabled():
return
api = HfApi(token=get_hf_token())
api.delete_folder(
repo_id=STORAGE_DATASET_REPO_ID,
repo_type=STORAGE_DATASET_REPO_TYPE,
path_in_repo=hf_storage_path(safe_name(player_id)),
commit_message=f"Delete player {safe_name(player_id)} storage",
)
def path_has_session_data(directory: str):
if not os.path.isdir(directory):
return False
for _root, _dirs, files in os.walk(directory):
if "session.json" in files:
return True
return False
def seed_storage_if_needed(seed_dir: str, target_dir: str):
if not os.path.isdir(seed_dir):
return
os.makedirs(target_dir, exist_ok=True)
if path_has_session_data(target_dir):
return
shutil.copytree(seed_dir, target_dir, dirs_exist_ok=True)
def local_pipeline_bundle_available():
return (
os.path.isfile(os.path.join(CURRENT_DIR, "pipeline.py"))
and os.path.isdir(os.path.join(CURRENT_DIR, "ViTPose"))
)
def use_local_pipeline_bundle():
seed_storage_if_needed(os.path.join(CURRENT_DIR, "Storage"), STORAGE_ROOT)
runtime_state.update({
"pipeline_source": "local_bundle",
"assets_repo_id": None,
"assets_repo_type": None,
"assets_revision": None,
})
return CURRENT_DIR
def use_private_pipeline_repo():
if not ASSETS_REPO_ID:
raise RuntimeError(
"A private runtime pipeline is required. Set SPORALIZE_ASSETS_REPO_ID "
"or run from a directory that contains both pipeline.py and ViTPose."
)
assets_dir = os.path.join(ASSETS_RUNTIME_ROOT, safe_name(ASSETS_REPO_ID))
snapshot_download(
repo_id=ASSETS_REPO_ID,
repo_type=ASSETS_REPO_TYPE,
revision=ASSETS_REVISION,
token=get_hf_token(),
local_dir=assets_dir,
allow_patterns=["pipeline.py", "ViTPose/**", "Storage/**", "Weights/**"],
)
if not os.path.isfile(os.path.join(assets_dir, "pipeline.py")):
raise RuntimeError(f"pipeline.py was not found in private assets repo {ASSETS_REPO_ID}")
if not os.path.isdir(os.path.join(assets_dir, "ViTPose")):
raise RuntimeError(f"ViTPose was not found in private assets repo {ASSETS_REPO_ID}")
seed_storage_if_needed(os.path.join(assets_dir, "Storage"), STORAGE_ROOT)
runtime_state.update({
"pipeline_source": "private_repo",
"assets_repo_id": ASSETS_REPO_ID,
"assets_repo_type": ASSETS_REPO_TYPE,
"assets_revision": ASSETS_REVISION,
})
return assets_dir
def resolve_pipeline_root():
if local_pipeline_bundle_available() and (USE_LOCAL_ASSETS or not CONFIGURED_ASSETS_REPO_ID):
return use_local_pipeline_bundle()
if ASSETS_REPO_ID:
return use_private_pipeline_repo()
if local_pipeline_bundle_available():
return use_local_pipeline_bundle()
raise RuntimeError(
"No runtime pipeline is available. Provide a private Hugging Face repo via "
"SPORALIZE_ASSETS_REPO_ID or bundle pipeline.py with ViTPose for local development."
)
def load_pipeline_callable(pipeline_root: str):
pipeline_path = os.path.join(pipeline_root, "pipeline.py")
if not os.path.isfile(pipeline_path):
raise RuntimeError(f"pipeline.py was not found at {pipeline_path}")
if pipeline_root not in sys.path:
sys.path.insert(0, pipeline_root)
module_name = "sporalize_runtime_pipeline"
if module_name in sys.modules:
del sys.modules[module_name]
spec = importlib.util.spec_from_file_location(module_name, pipeline_path)
if spec is None or spec.loader is None:
raise RuntimeError(f"Unable to create import spec for {pipeline_path}")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
run_pipeline = getattr(module, "run_pipeline", None)
if run_pipeline is None:
raise RuntimeError("run_pipeline was not found in the resolved pipeline module")
return run_pipeline
def ensure_weight_file(spec: dict, pipeline_root: str):
override_path = os.environ.get(spec["override_env"])
if override_path and os.path.isfile(override_path):
print(f"[SPORALIZE] Weight '{spec['filename']}': using env override at {override_path}", flush=True)
return override_path
pipeline_weight = os.path.join(pipeline_root, "Weights", spec["filename"])
if os.path.isfile(pipeline_weight):
print(f"[SPORALIZE] Weight '{spec['filename']}': found in pipeline bundle", flush=True)
return pipeline_weight
local_fallback = spec.get("local_fallback")
if local_fallback and os.path.isfile(local_fallback):
print(f"[SPORALIZE] Weight '{spec['filename']}': using local fallback at {local_fallback}", flush=True)
return local_fallback
os.makedirs(WEIGHTS_RUNTIME_ROOT, exist_ok=True)
cached_path = os.path.join(WEIGHTS_RUNTIME_ROOT, spec["filename"])
if os.path.isfile(cached_path):
print(f"[SPORALIZE] Weight '{spec['filename']}': cache hit at {cached_path}", flush=True)
return cached_path
print(f"[SPORALIZE] Weight '{spec['filename']}': not cached, downloading from HF repo '{spec['repo_id']}'...", flush=True)
t0 = time.time()
result = hf_hub_download(
repo_id=spec["repo_id"],
repo_type=spec.get("repo_type", "model"),
filename=spec["repo_file"],
token=get_hf_token(),
local_dir=WEIGHTS_RUNTIME_ROOT,
)
print(f"[SPORALIZE] Weight '{spec['filename']}': downloaded in {time.time() - t0:.1f}s -> {result}", flush=True)
return result
def ensure_runtime_ready(force: bool = False):
if runtime_state["ready"] and not force:
return runtime_state
os.makedirs(RUNTIME_ROOT, exist_ok=True)
os.makedirs(STORAGE_ROOT, exist_ok=True)
pipeline_root = resolve_pipeline_root()
run_pipeline = load_pipeline_callable(pipeline_root)
weight_paths = {name: ensure_weight_file(spec, pipeline_root) for name, spec in DEFAULT_WEIGHT_SPECS.items()}
runtime_state.update({
"ready": True,
"pipeline_root": pipeline_root,
"run_pipeline": run_pipeline,
"weights": weight_paths,
})
return runtime_state
os.makedirs(STORAGE_ROOT, exist_ok=True)
app.mount("/storage", StaticFiles(directory=STORAGE_ROOT), name="storage")
progress_store = {}
cancel_store = {}
TERMINAL_PROGRESS_STATUSES = {"completed", "failed", "cancelled"}
CANCEL_PROGRESS_STATUSES = {"cancelling", "cancelled"}
ACTIVE_PROGRESS_STATUSES = {"queued", "running"}
active_job_futures = {}
active_job_lock = threading.Lock()
def env_int(name: str, default: int) -> int:
try:
return int(os.environ.get(name, str(default)))
except Exception:
return default
ANALYSIS_WORKERS = max(1, env_int("SPORALIZE_ANALYSIS_WORKERS", 1))
analysis_executor = concurrent.futures.ThreadPoolExecutor(
max_workers=ANALYSIS_WORKERS,
thread_name_prefix="sporalize-analysis",
)
JOB_PROGRESS_ROOT = os.environ.get("SPORALIZE_JOB_PROGRESS_DIR", os.path.join(RUNTIME_ROOT, "jobs"))
_progress_file_last_write = {}
def progress_file_path(client_id: str) -> str:
return os.path.join(JOB_PROGRESS_ROOT, f"{safe_name(client_id)}.json")
def write_progress_file(client_id: str, payload: dict):
try:
os.makedirs(JOB_PROGRESS_ROOT, exist_ok=True)
with open(progress_file_path(client_id), "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
except Exception:
pass
def read_progress_file(client_id: str):
try:
path = progress_file_path(client_id)
if not os.path.isfile(path):
return None
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def current_progress_payload(client_id: str):
memory_payload = progress_store.get(client_id) or {}
file_payload = read_progress_file(client_id) or {}
if file_payload.get("updatedAt", 0) > memory_payload.get("updatedAt", 0):
return file_payload
return memory_payload or file_payload
def cleanup_active_job_futures():
with active_job_lock:
for stored_client_id, future in list(active_job_futures.items()):
if future.done() or future.cancelled():
active_job_futures.pop(stored_client_id, None)
def register_active_job(client_id: str, future):
cleanup_active_job_futures()
with active_job_lock:
active_job_futures[client_id] = future
def unregister_active_job(client_id: str):
with active_job_lock:
active_job_futures.pop(client_id, None)
def get_active_job_future(client_id: str):
cleanup_active_job_futures()
with active_job_lock:
return active_job_futures.get(client_id)
def active_job_client_ids():
cleanup_active_job_futures()
with active_job_lock:
return list(active_job_futures.keys())
def build_active_job_payload(client_id: str, payload: dict):
updated_at = int(payload.get("updatedAt") or time.time() * 1000)
return {
"clientId": payload.get("clientId") or client_id,
"sessionId": payload.get("sessionId"),
"playerId": payload.get("playerId"),
"createdAt": int(payload.get("createdAt") or updated_at),
"updatedAt": updated_at,
"progress": payload.get("progress", 0.0),
"phase": payload.get("phase") or "Queued for Processing",
"status": payload.get("status") or "queued",
"resultUrl": payload.get("resultUrl"),
"error": payload.get("error"),
}
def is_cancel_requested(client_id: str):
if cancel_store.get(client_id):
return True
stored_progress = read_progress_file(client_id)
return bool(stored_progress and stored_progress.get("status") in CANCEL_PROGRESS_STATUSES)
def clear_cancel_request(client_id: str):
cancel_store.pop(client_id, None)
def should_write_progress_file(client_id: str, payload: dict):
status = payload.get("status")
if status in {"uploading", "queued", "cancelling", "completed", "failed", "cancelled"}:
_progress_file_last_write[client_id] = time.time()
return True
now = time.time()
if (now - _progress_file_last_write.get(client_id, 0.0)) >= 1.0:
_progress_file_last_write[client_id] = now
return True
return False
def set_progress(
client_id: str,
progress: float,
phase: str,
step: int = 0,
total: int = 0,
status: str = "running",
**extra,
):
memory_payload = progress_store.get(client_id, {})
file_payload = read_progress_file(client_id) or {}
if file_payload.get("updatedAt", 0) > memory_payload.get("updatedAt", 0):
payload = dict(file_payload)
else:
payload = dict(memory_payload)
now_ms = int(time.time() * 1000)
if not payload.get("createdAt"):
payload["createdAt"] = now_ms
if payload.get("status") == "cancelling" and status not in TERMINAL_PROGRESS_STATUSES:
status = "cancelling"
phase = payload.get("phase") or "Cancellation Requested"
payload.update({
"clientId": client_id,
"progress": max(0.0, min(100.0, float(progress))),
"step": max(0, int(step or 0)),
"total": max(0, int(total or 0)),
"phase": phase,
"status": status,
"updatedAt": now_ms,
})
payload.update({key: value for key, value in extra.items() if value is not None})
progress_store[client_id] = payload
if should_write_progress_file(client_id, payload):
write_progress_file(client_id, payload)
def safe_name(value: str) -> str:
allowed = []
for ch in str(value):
if ch.isalnum() or ch in ("-", "_", "."):
allowed.append(ch)
else:
allowed.append("_")
cleaned = "".join(allowed).strip("._")
return cleaned or "item"
def session_storage_paths(player_id: str, session_id: str):
player_dir = os.path.join(STORAGE_ROOT, safe_name(player_id))
session_dir = os.path.join(player_dir, safe_name(session_id))
videos_dir = os.path.join(session_dir, "videos")
return player_dir, session_dir, videos_dir
def list_session_files():
session_files = []
for root, _, files in os.walk(STORAGE_ROOT):
if "session.json" in files:
session_files.append(os.path.join(root, "session.json"))
return sorted(session_files, key=os.path.getmtime, reverse=True)
def request_public_base_url(request: Request) -> str:
configured_public_base = os.environ.get("SPORALIZE_PUBLIC_BASE_URL", "").strip()
if configured_public_base:
return configured_public_base.rstrip("/")
forwarded_proto = request.headers.get("x-forwarded-proto", "").split(",")[0].strip().lower()
forwarded_host = request.headers.get("x-forwarded-host", "").split(",")[0].strip()
if forwarded_proto in ("http", "https") and forwarded_host:
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
base_url = str(request.base_url).rstrip("/")
if forwarded_proto in ("http", "https"):
parsed = urlsplit(base_url)
base_url = urlunsplit((forwarded_proto, parsed.netloc, parsed.path, "", "")).rstrip("/")
return base_url
def build_storage_url(request_or_base_url, *parts: str) -> str:
relative = "/".join(safe_name(part) if idx < len(parts) - 1 else part.replace("\\", "/") for idx, part in enumerate(parts))
if isinstance(request_or_base_url, str):
base_url = request_or_base_url.rstrip("/")
else:
base_url = request_public_base_url(request_or_base_url)
return base_url + "/storage/" + relative.lstrip("/")
def parse_video_timecode(value, fps=30.0):
if value is None:
return 0.0
if isinstance(value, (int, float, np.integer, np.floating)):
return max(0.0, float(value))
parts = str(value).split(":")
if len(parts) == 4:
h, m, s, f = [int(float(part or 0)) for part in parts]
return max(0.0, (h * 3600) + (m * 60) + s + (f / max(1.0, float(fps))))
try:
return max(0.0, float(value))
except Exception:
return 0.0
def detect_camera_id(file_name: str):
match = re.search(r"_cam_(\d+)_", file_name)
if match:
return int(match.group(1))
return None
def split_camera_video_variants(videos_dir: str):
grouped: dict[int, dict[str, str]] = {}
for file_name in sorted(os.listdir(videos_dir)):
camera_id = detect_camera_id(file_name)
if camera_id is None:
continue
full_path = os.path.join(videos_dir, file_name)
if not os.path.isfile(full_path):
continue
bucket = grouped.setdefault(camera_id, {})
if file_name.lower().endswith(".web.mp4"):
bucket["web"] = full_path
else:
bucket["base"] = full_path
primary_map = {}
fallback_map = {}
for camera_id in sorted(grouped.keys()):
base_path = grouped[camera_id].get("base")
web_path = grouped[camera_id].get("web")
if base_path:
primary_map[camera_id] = base_path
if web_path:
fallback_map[camera_id] = web_path
elif web_path:
primary_map[camera_id] = web_path
return primary_map, fallback_map
def normalize_video_for_web(input_path: str) -> str:
"""
Re-encode uploaded video to a browser-friendly MP4 stream.
Falls back to the original file if normalization fails.
"""
output_path = os.path.splitext(input_path)[0] + ".web.mp4"
# First try ffmpeg -> H.264 + yuv420p for maximum browser compatibility.
ffmpeg_cmd = [
"ffmpeg",
"-y",
"-i",
input_path,
"-an",
"-c:v",
"libx264",
"-preset",
"veryfast",
"-pix_fmt",
"yuv420p",
"-movflags",
"+faststart",
output_path,
]
try:
ffmpeg_proc = subprocess.run(ffmpeg_cmd, capture_output=True, text=True)
if ffmpeg_proc.returncode == 0 and os.path.exists(output_path) and os.path.getsize(output_path) > 0:
return output_path
except Exception:
pass
# Fallback: OpenCV transcode when ffmpeg is unavailable.
cap = cv2.VideoCapture(input_path)
if not cap.isOpened():
return input_path
fps = cap.get(cv2.CAP_PROP_FPS)
if not fps or not np.isfinite(fps) or fps <= 0:
fps = 30.0
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
if width <= 0 or height <= 0:
cap.release()
return input_path
writer = cv2.VideoWriter(
output_path,
cv2.VideoWriter_fourcc(*"mp4v"),
float(fps),
(width, height),
)
if not writer.isOpened():
cap.release()
return input_path
frame_count = 0
success = True
while True:
ok, frame = cap.read()
if not ok:
break
writer.write(frame)
frame_count += 1
cap.release()
writer.release()
if frame_count <= 0:
success = False
elif not os.path.exists(output_path) or os.path.getsize(output_path) <= 0:
success = False
if not success:
if os.path.exists(output_path):
os.remove(output_path)
return input_path
return output_path
def normalize_camera_videos_for_web(camera_map):
fallback_map = {}
items = [(camera_id, video_path) for camera_id, video_path in sorted(camera_map.items()) if video_path]
if not items:
return fallback_map
def normalize_item(item):
camera_id, video_path = item
normalized_path = normalize_video_for_web(video_path)
if normalized_path != video_path and os.path.exists(normalized_path):
return camera_id, normalized_path
return None
max_workers = min(4, len(items))
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
for result in executor.map(normalize_item, items):
if result is not None:
camera_id, normalized_path = result
fallback_map[int(camera_id)] = normalized_path
return fallback_map
def build_camera_video_entries(request_or_base_url, player_id: str, session_id: str, camera_map):
return [
{
"cameraId": int(camera_id),
"url": build_storage_url(
request_or_base_url,
safe_name(player_id),
safe_name(session_id),
"videos",
os.path.basename(video_path),
),
}
for camera_id, video_path in sorted(camera_map.items())
if video_path and os.path.exists(video_path)
]
def build_action_clip_entries(request_or_base_url, player_id: str, session_id: str, clip_map):
return [
{
"cameraId": int(camera_id),
"url": build_storage_url(
request_or_base_url,
safe_name(player_id),
safe_name(session_id),
"clips",
os.path.basename(clip_path),
),
}
for camera_id, clip_path in sorted(clip_map.items())
if clip_path and os.path.exists(clip_path)
]
def normalize_session_payload(session: dict, request: Request):
session_id = session.get("id")
player_id = session.get("playerId")
if not session_id or not player_id:
return session
session_dir = find_session_path(session_id)
if not session_dir:
return session
videos_dir = os.path.join(session_dir, "videos")
if not os.path.isdir(videos_dir):
return session
camera_map, fallback_camera_map = split_camera_video_variants(videos_dir)
if not camera_map:
return session
normalized_actions = []
for action in session.get("actions", []):
normalized_action = dict(action)
fps = float(normalized_action.get("fps") or 30.0)
fps = max(1.0, fps)
absolute_start_frame = normalized_action.get("sourceStartFrame")
absolute_end_frame = normalized_action.get("sourceEndFrame")
if absolute_start_frame is None or absolute_end_frame is None:
absolute_start_frame = normalized_action.get("startFrame")
absolute_end_frame = normalized_action.get("endFrame")
try:
absolute_start_frame = int(absolute_start_frame) if absolute_start_frame is not None else None
absolute_end_frame = int(absolute_end_frame) if absolute_end_frame is not None else None
except Exception:
absolute_start_frame = None
absolute_end_frame = None
if absolute_start_frame is not None and absolute_end_frame is not None and absolute_end_frame >= absolute_start_frame:
start_seconds = max(0.0, absolute_start_frame / fps)
end_seconds = max(start_seconds, (absolute_end_frame + 1) / fps)
normalized_action["startFrame"] = absolute_start_frame
normalized_action["endFrame"] = absolute_end_frame
else:
total_frames = int(normalized_action.get("totalFrames") or 0)
start_seconds = parse_video_timecode(normalized_action.get("start"), fps=fps)
if total_frames > 0:
end_seconds = start_seconds + (total_frames / fps)
else:
end_seconds = max(start_seconds, parse_video_timecode(normalized_action.get("end"), fps=fps))
normalized_action["cameraClips"] = normalized_action.get("cameraClips") or build_camera_video_entries(
request, player_id, session_id, camera_map
)
if fallback_camera_map:
normalized_action["sourceCameraClips"] = normalized_action.get("sourceCameraClips") or build_camera_video_entries(
request, player_id, session_id, fallback_camera_map
)
normalized_action["startSeconds"] = round(start_seconds, 6)
normalized_action["endSeconds"] = round(end_seconds, 6)
normalized_actions.append(normalized_action)
normalized_session = dict(session)
normalized_session["actions"] = normalized_actions
return normalized_session
def summarize_action_for_archive(action: dict):
return {
"id": action.get("id"),
"label": action.get("label", "Unknown"),
"start": action.get("start", "00:00:00:00"),
"end": action.get("end", "00:00:00:00"),
"fps": action.get("fps"),
"startFrame": action.get("startFrame"),
"endFrame": action.get("endFrame"),
"startSeconds": action.get("startSeconds", 0),
"endSeconds": action.get("endSeconds", 0),
"activeFoot": action.get("activeFoot"),
"totalFrames": action.get("totalFrames", 0),
"preFrames": action.get("preFrames", 0),
"inFrame": action.get("inFrame", 0),
"postFrames": action.get("postFrames", 0),
"sourceStartFrame": action.get("sourceStartFrame"),
"sourceEndFrame": action.get("sourceEndFrame"),
"sourceStartSeconds": action.get("sourceStartSeconds"),
"sourceEndSeconds": action.get("sourceEndSeconds"),
"cameraClips": [],
"sourceCameraClips": [],
"preMetrics": [],
"preActionMetrics": [],
"inActionMetrics": [],
"postMetrics": [],
"postActionMetrics": [],
"fullIntervalMetrics": [],
"skeleton": [],
}
def build_session_summary_payload(session: dict):
return {
"id": session.get("id"),
"playerId": session.get("playerId"),
"playerName": session.get("playerName"),
"summaryOnly": True,
"createdAt": session.get("createdAt"),
"targetSize": session.get("targetSize"),
"cameraCount": session.get("cameraCount", 0),
"actions": [
summarize_action_for_archive(action)
for action in session.get("actions", [])
if isinstance(action, dict)
],
"failedActions": session.get("failedActions", []),
}
def session_summary_path(session_file: str):
return os.path.join(os.path.dirname(session_file), "session-summary.json")
def write_session_summary(session_file: str, session: dict):
summary = build_session_summary_payload(session)
with open(session_summary_path(session_file), "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2)
return summary
def load_session_summary(session_file: str):
summary_file = session_summary_path(session_file)
if os.path.isfile(summary_file):
with open(summary_file, "r", encoding="utf-8") as f:
return json.load(f)
with open(session_file, "r", encoding="utf-8") as f:
session = json.load(f)
summary = build_session_summary_payload(session)
try:
with open(summary_file, "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2)
except Exception:
pass
return summary
def json_default(value):
if isinstance(value, np.generic):
return value.item()
if isinstance(value, np.ndarray):
return value.tolist()
raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
def make_json_safe(value):
if value is None or isinstance(value, (str, bool, int)):
return value
if isinstance(value, float):
return value if np.isfinite(value) else None
if isinstance(value, np.generic):
return make_json_safe(value.item())
if isinstance(value, np.ndarray):
return make_json_safe(value.tolist())
if isinstance(value, dict):
return {str(key): make_json_safe(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set)):
return [make_json_safe(item) for item in value]
if hasattr(value, "tolist"):
try:
return make_json_safe(value.tolist())
except Exception:
pass
return str(value)
def export_action_clips(camera_map, clips_dir, action_index, start_frame, end_frame, fps):
os.makedirs(clips_dir, exist_ok=True)
frame_count = max(0, end_frame - start_frame + 1)
clip_paths = {}
for camera_id, video_path in sorted(camera_map.items()):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
continue
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
if width <= 0 or height <= 0:
cap.release()
continue
clip_name = f"action_{action_index:02d}_cam_{camera_id}.mp4"
clip_path = os.path.join(clips_dir, clip_name)
writer = cv2.VideoWriter(
clip_path,
cv2.VideoWriter_fourcc(*"mp4v"),
max(1.0, float(fps)),
(width, height),
)
cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
written = 0
while written < frame_count:
ok, frame = cap.read()
if not ok:
break
writer.write(frame)
written += 1
writer.release()
cap.release()
if written > 0 and os.path.exists(clip_path):
clip_paths[camera_id] = clip_path
elif os.path.exists(clip_path):
os.remove(clip_path)
return clip_paths
def load_session_by_id(session_id: str):
target_name = safe_name(session_id)
for session_file in list_session_files():
session_dir = os.path.basename(os.path.dirname(session_file))
if session_dir != target_name:
continue
with open(session_file, "r", encoding="utf-8") as f:
return json.load(f)
return None
def find_session_path(session_id: str):
target_name = safe_name(session_id)
for session_file in list_session_files():
session_dir = os.path.dirname(session_file)
if os.path.basename(session_dir) == target_name:
return session_dir
return None
def player_storage_path(player_id: str):
return os.path.join(STORAGE_ROOT, safe_name(player_id))
def get_cors_origins():
configured = os.environ.get("CORS_ALLOW_ORIGINS", "*").strip()
if not configured or configured == "*":
return ["*"]
return [origin.strip() for origin in configured.split(",") if origin.strip()]
@app.on_event("startup")
def startup_event():
print("[SPORALIZE] Server startup: initializing runtime...", flush=True)
t0 = time.time()
ensure_runtime_ready()
print(f"[SPORALIZE] Runtime ready in {time.time() - t0:.1f}s (pipeline_source={runtime_state.get('pipeline_source')})", flush=True)
t1 = time.time()
sync_storage_from_hf(force=True)
print(f"[SPORALIZE] Storage sync done in {time.time() - t1:.1f}s", flush=True)
print(f"[SPORALIZE] Startup complete in {time.time() - t0:.1f}s total", flush=True)
@app.get("/healthz")
def healthz():
runtime = ensure_runtime_ready()
return {
"status": "ok",
"storageRoot": STORAGE_ROOT,
"pipelineRoot": runtime.get("pipeline_root"),
"pipelineSource": runtime.get("pipeline_source"),
"assetsRepoId": runtime.get("assets_repo_id"),
"assetsRepoType": runtime.get("assets_repo_type"),
"assetsRevision": runtime.get("assets_revision"),
}
@app.post("/api/cancel/{client_id}")
def cancel_processing(client_id: str):
current = current_progress_payload(client_id)
current_status = current.get("status")
if current_status in TERMINAL_PROGRESS_STATUSES:
return {
"status": current_status,
"clientId": client_id,
"sessionId": current.get("sessionId"),
}
cancel_store[client_id] = True
future = get_active_job_future(client_id)
queued_cancelled = bool(future and future.cancel())
set_progress(
client_id,
current.get("progress", 0.0),
"Processing Cancelled" if queued_cancelled else "Cancellation Requested",
current.get("step", 0),
current.get("total", 0),
"cancelled" if queued_cancelled else "cancelling",
)
if queued_cancelled:
session_id = current.get("sessionId")
player_id = current.get("playerId")
if player_id and session_id:
_player_dir, session_dir, _videos_dir = session_storage_paths(player_id, session_id)
if os.path.isdir(session_dir):
shutil.rmtree(session_dir, ignore_errors=True)
unregister_active_job(client_id)
clear_cancel_request(client_id)
return {
"status": "cancelled" if queued_cancelled else "cancelling",
"clientId": client_id,
"sessionId": current.get("sessionId"),
}
@app.get("/api/progress/{client_id}")
def get_progress(client_id: str):
stored_progress = current_progress_payload(client_id)
if stored_progress:
return stored_progress
return {
"progress": 0.0,
"step": 0,
"total": 0,
"phase": "Initializing",
"status": "idle",
"updatedAt": int(time.time() * 1000),
}
@app.get("/api/active-analyses")
def get_active_analyses():
jobs = []
for client_id in active_job_client_ids():
payload = current_progress_payload(client_id)
if not payload:
continue
status = payload.get("status")
if status not in ACTIVE_PROGRESS_STATUSES:
continue
jobs.append(build_active_job_payload(client_id, payload))
jobs.sort(key=lambda item: item.get("updatedAt", 0), reverse=True)
return {"jobs": jobs}
@app.get("/api/sessions/{session_id}")
def get_session(session_id: str, request: Request):
session = load_session_by_id(session_id)
if session is None:
raise HTTPException(status_code=404, detail="Session not found")
return normalize_session_payload(session, request)
@app.get("/api/archive")
def get_archive(request: Request, full: bool = False):
sessions = []
for session_file in list_session_files():
try:
if full:
with open(session_file, "r", encoding="utf-8") as f:
session = json.load(f)
sessions.append(normalize_session_payload(session, request))
else:
sessions.append(load_session_summary(session_file))
except Exception:
continue
return {"sessions": sessions}
@app.delete("/api/sessions/{session_id}")
def delete_session(session_id: str):
session_dir = find_session_path(session_id)
if session_dir is None:
raise HTTPException(status_code=404, detail="Session not found")
player_dir = os.path.dirname(session_dir)
player_id = os.path.basename(player_dir)
shutil.rmtree(session_dir, ignore_errors=True)
try:
delete_session_from_hf(player_id, session_id)
except Exception:
pass
if os.path.isdir(player_dir) and not os.listdir(player_dir):
os.rmdir(player_dir)
return {"status": "deleted", "sessionId": session_id}
@app.delete("/api/players/{player_id}")
def delete_player(player_id: str):
player_dir = player_storage_path(player_id)
if not os.path.isdir(player_dir):
raise HTTPException(status_code=404, detail="Player storage not found")
shutil.rmtree(player_dir, ignore_errors=True)
try:
delete_player_from_hf(player_id)
except Exception:
pass
return {"status": "deleted", "playerId": player_id}
cors_origins = get_cors_origins()
app.add_middleware(
CORSMiddleware,
allow_origins=cors_origins,
allow_credentials=(cors_origins != ["*"]),
allow_methods=["*"],
allow_headers=["*"],
)
def format_metric_series(name, unit, values_list):
return {
"name": name,
"unit": unit,
"values": [
{"frame": i, "value": safe_float(v)}
for i, v in enumerate(values_list)
]
}
def safe_float(value):
try:
number = float(value)
return None if np.isnan(number) else number
except Exception:
return None
def frame_number(value):
try:
if value is None:
return None
return int(float(value))
except Exception:
return None
def relative_frame(value, start_frame=0, fallback=0):
frame = frame_number(value)
if frame is None:
return fallback
start = frame_number(start_frame) or 0
return frame - start if frame >= start else frame
def safe_metric_value(value):
if value is None:
return None
number = safe_float(value)
if number is not None:
return round(number, 3)
if isinstance(value, (str, bool)):
return value
if isinstance(value, (dict, list, tuple)):
return None
return str(value)
def point_to_float_list(point):
if point is None:
return None
if hasattr(point, "tolist"):
point = point.tolist()
try:
values = list(point)
except Exception:
return None
if len(values) < 3:
return None
xyz = []
for component in values[:3]:
number = safe_float(component)
if number is None:
return None
xyz.append(float(number))
return xyz
def map_value(mapping, key):
if not isinstance(mapping, dict):
return None
if key in mapping:
return mapping[key]
str_key = str(key)
if str_key in mapping:
return mapping[str_key]
target = frame_number(key)
for current_key, value in mapping.items():
if frame_number(current_key) == target:
return value
return None
def skeleton_joint(raw_skel, joint_index):
if raw_skel is None:
return None
if hasattr(raw_skel, "tolist") and not isinstance(raw_skel, dict):
raw_skel = raw_skel.tolist()
if isinstance(raw_skel, dict):
if joint_index in raw_skel:
return raw_skel[joint_index]
return raw_skel.get(str(joint_index))
if isinstance(raw_skel, (list, tuple)) and joint_index < len(raw_skel):
return raw_skel[joint_index]
return None
def max_joint_index(raw_skel):
if raw_skel is None:
return 32
if hasattr(raw_skel, "tolist") and not isinstance(raw_skel, dict):
raw_skel = raw_skel.tolist()
if isinstance(raw_skel, dict):
keys = [frame_number(key) for key in raw_skel.keys()]
keys = [key for key in keys if key is not None]
return max(keys, default=32)
if isinstance(raw_skel, (list, tuple)):
return max(32, len(raw_skel) - 1)
return 32
def build_skeleton_frames(rep, analytics, start_frame, end_frame):
tracking_data = analytics.get("tracking_data", {}) if isinstance(analytics, dict) else {}
player_skeletons = tracking_data.get("player_skeletons") if isinstance(tracking_data, dict) else None
ball_positions = tracking_data.get("ball_positions") if isinstance(tracking_data, dict) else None
if not isinstance(player_skeletons, dict):
player_skeletons = rep.get("skel_history", {})
if not isinstance(ball_positions, dict):
ball_positions = rep.get("ball_history", {})
skeleton_frames = []
for f_idx in range(start_frame, end_frame + 1):
raw_skel = map_value(player_skeletons, f_idx)
raw_ball = map_value(ball_positions, f_idx)
n_joints = max(33, max_joint_index(raw_skel) + 1)
joints = []
for joint_index in range(n_joints):
point = point_to_float_list(skeleton_joint(raw_skel, joint_index))
joints.append(point if point is not None else [0.0, 0.0, 0.0])
frame_payload = {"frame": f_idx - start_frame, "joints": joints}
ball_point = point_to_float_list(raw_ball)
if ball_point is not None:
frame_payload["ball"] = ball_point
skeleton_frames.append(frame_payload)
return skeleton_frames
METRIC_DISPLAY_NAMES = {
"stationary_foot_ball_distance_pctw_shoulder": "Support Foot-Ball Distance (% Shoulder Width)",
}
def metric_name(key: str) -> str:
return METRIC_DISPLAY_NAMES.get(key, key.replace("_", " ").title())
FULL_INTERVAL_KEYS = [
"head_angle",
"left_knee_angle",
"right_knee_angle",
"trunk_pitch_angle",
"active_foot_ball_distance",
"stationary_foot_ball_distance_pctw_shoulder",
"foot_anteroposterior_offset",
"foot_inclination_angle",
"left_knee_angles",
"right_knee_angles",
"torso_pitch_angles",
"head_angles",
"mid_foot_ball_distances",
"left_right_foot_distances",
]
ACTION_METRIC_LAYOUTS = {
"Pass": {
"pre": ["body_to_ball_angle"],
"in": [
"foot_region",
"ball_contact_zone",
"head_angle",
"left_knee_angle",
"right_knee_angle",
"trunk_pitch_angle",
"stationary_foot_ball_distance_pctw_shoulder",
"body_to_ball_angle",
"l_r_foot_distance",
"trunc_pitch_angle",
"trunc_roll_angle",
"left_foot_orientation_angle",
"right_foot_orientation_angle",
"difference_in_angles",
"l_knee_angle",
"r_knee_angle",
"head_pitch_angle",
"head_roll_angle",
"stand_foot_angle",
"active_foot_height_pct",
],
"post": ["head_angle", "body_to_ball_angle"],
"top_level_scalars": ["backward_weighted_angle", "forward_weighted_angle"],
},
"Shoot": {
"pre": ["max_backward_swing_distance", "max_backward_swing_angle", "body_to_ball_angle"],
"in": [
"foot_region",
"ball_contact_zone",
"head_angle",
"left_knee_angle",
"right_knee_angle",
"trunk_pitch_angle",
"stationary_foot_ball_distance_pctw_shoulder",
"foot_inclination_angle",
"body_to_ball_angle",
"l_r_foot_distance",
"trunc_pitch_angle",
"trunc_roll_angle",
"left_foot_orientation_angle",
"right_foot_orientation_angle",
"difference_in_angles",
"l_knee_angle",
"r_knee_angle",
"head_pitch_angle",
"head_roll_angle",
"stand_foot_angle",
"l_elbow_shoulder_hip_angle",
"r_elbow_shoulder_hip_angle",
"active_ankle_angle",
],
"post": ["max_forward_swing_distance", "max_forward_swing_angle", "head_angle", "body_to_ball_angle"],
"top_level_scalars": ["backward_weighted_angle", "forward_weighted_angle"],
},
"Receive": {
"pre": ["body_orientation_vs_ball", "head_angle"],
"in": [
"foot_region",
"ball_contact_zone",
"head_angle",
"left_knee_angle",
"right_knee_angle",
"trunk_pitch_angle",
"stationary_foot_ball_distance_pctw_shoulder",
"foot_anteroposterior_offset",
"l_knee_angle",
"r_knee_angle",
"trunc_pitch_angle",
"trunc_roll_angle",
"left_foot_orientation_angle",
"right_foot_orientation_angle",
"difference_in_angles",
"l_r_foot_distance",
"stand_foot_angle",
"body_orientation_vs_ball",
"active_foot_height_pct",
],
"post": ["mid_feet_ball_dist", "ball_height_pct_body"],
"top_level_scalars": [],
},
"Dribble": {
"frames": [
"head_angle",
"left_knee_angle",
"right_knee_angle",
"trunk_pitch_angle",
"left_heel_height",
"right_heel_height",
"active_foot_ball_distance",
"ball_feet_distance",
"trunk_pitch",
"trunk_roll",
"ball_possession_score",
],
"top_level_scalars": [],
},
}
def ordered_metric_keys(observed_keys, preferred_keys=None):
seen = set()
ordered = []
for key in preferred_keys or []:
if key in observed_keys and key not in seen:
seen.add(key)
ordered.append(key)
for key in sorted(observed_keys):
if key not in seen:
seen.add(key)
ordered.append(key)
return ordered
def normalized_metric_identity(name):
return re.sub(r"\s+", " ", str(name or "").strip().lower())
def dedupe_metric_items(items):
deduped = []
seen = set()
for item in items:
if not isinstance(item, dict):
deduped.append(item)
continue
identity = normalized_metric_identity(item.get("name"))
if not identity:
deduped.append(item)
continue
if identity in seen:
continue
seen.add(identity)
deduped.append(item)
return deduped
def is_frame_metric_payload(payload):
if isinstance(payload, list):
return True
if not isinstance(payload, dict) or not payload:
return False
keys_are_frames = all(frame_number(key) is not None for key in payload.keys())
has_metric_dict = any(isinstance(value, dict) for value in payload.values())
return keys_are_frames and has_metric_dict
def entries_from_frame_payload(payload, start_frame=0):
entries = []
if isinstance(payload, list):
for index, item in enumerate(payload):
if not isinstance(item, dict):
continue
entry = dict(item)
entry["frame"] = relative_frame(entry.get("frame", index), start_frame, index)
entries.append(entry)
return entries
if not isinstance(payload, dict):
return entries
def sort_key(item):
frame = frame_number(item[0])
return (frame is None, frame if frame is not None else 0)
for index, (frame_key, frame_payload) in enumerate(sorted(payload.items(), key=sort_key)):
if not isinstance(frame_payload, dict):
continue
entry = dict(frame_payload)
entry["frame"] = relative_frame(frame_key, start_frame, index)
entries.append(entry)
return entries
def build_series_from_entries(entries, unit_for, skip_keys=None, preferred_keys=None):
skip = {"frame"}
if skip_keys:
skip.update(skip_keys)
metric_keys = set()
for entry in entries:
metric_keys.update(
key for key in entry.keys()
if key not in skip and safe_float(entry.get(key)) is not None
)
series = []
for key in ordered_metric_keys(metric_keys, preferred_keys):
series.append({
"name": metric_name(key),
"unit": unit_for(key),
"values": [
{
"frame": relative_frame(entry.get("frame"), 0, index),
"value": safe_float(entry.get(key)),
}
for index, entry in enumerate(entries)
],
})
return dedupe_metric_items(series)
def build_series_from_frame_payload(payload, unit_for, start_frame=0, skip_keys=None, preferred_keys=None):
return build_series_from_entries(
entries_from_frame_payload(payload, start_frame),
unit_for,
skip_keys=skip_keys,
preferred_keys=preferred_keys,
)
def build_scalar_metrics(payload, unit_for, skip_keys=None, preferred_keys=None):
if not isinstance(payload, dict):
return []
skip = set(skip_keys or [])
skip.add("frame")
metrics = []
observed_keys = {
key for key, value in payload.items()
if key not in skip and not isinstance(value, (dict, list, tuple))
}
for key in ordered_metric_keys(observed_keys, preferred_keys):
if key in skip:
continue
value = safe_metric_value(payload.get(key))
metrics.append({
"name": metric_name(key),
"value": value,
"unit": unit_for(key) if isinstance(value, (int, float)) else "",
})
return dedupe_metric_items(metrics)
def build_top_level_interval_metrics(analytics, unit_for, skip_keys=None, preferred_keys=None):
skip = {
"action",
"active_foot",
"touch_frame",
"pre_action",
"action_frame",
"post_action",
"frames",
"in_action_data",
"pre_action_data",
"post_action_data",
"full_interval_data",
"per_frame",
"tracking_data",
}
if skip_keys:
skip.update(skip_keys)
observed_keys = {
key for key, value in analytics.items()
if key not in skip and isinstance(value, list)
}
series = []
for key in ordered_metric_keys(observed_keys, preferred_keys):
if key in skip:
continue
values = analytics.get(key)
if values is None:
values = []
if not isinstance(values, list):
continue
series.append(format_metric_series(metric_name(key), unit_for(key), values))
order_index = {}
for idx, key in enumerate(preferred_keys or []):
name = metric_name(key)
if name not in order_index:
order_index[name] = idx
return dedupe_metric_items(sorted(series, key=lambda item: order_index.get(item["name"], len(order_index))))
async def save_upload_to_path(upload: UploadFile, destination: str):
with open(destination, "wb") as f:
while True:
chunk = await upload.read(1024 * 1024)
if not chunk:
break
f.write(chunk)
def run_analysis_job(
request_base_url: str,
player_id: str,
target_w: float,
target_h: float,
client_id: str,
session_id: str,
session_dir: str,
actions_path: str,
calib_path: str,
camera_map,
):
def ensure_not_cancelled():
if is_cancel_requested(client_id):
raise InterruptedError("Processing cancelled by user")
try:
ensure_not_cancelled()
set_progress(client_id, 10.0, "Preparing AI Models", status="running", sessionId=session_id)
runtime = ensure_runtime_ready()
utils_paths = {
"POSE_PATH": runtime["weights"]["POSE_PATH"],
"YOLO_PATH": runtime["weights"]["YOLO_PATH"],
"CALIBRATION_PATH": calib_path,
"ACTIONS_PATH": actions_path,
}
sizes = {
"TARGET_SIZE": (int(target_w), int(target_h)),
"YOLO_IMGSZ": 960,
}
ensure_not_cancelled()
print(f"[SPORALIZE] Pipeline start: session={session_id} target_size={target_w}x{target_h} cameras={list(camera_map.keys())}", flush=True)
_pipeline_t0 = time.time()
set_progress(client_id, 20.0, "Extracting 3D Kinematics", status="running", sessionId=session_id)
def progress_tracker(current_act, total_act, step, total_frames):
if is_cancel_requested(client_id):
return False
processed_step = min(max(1, total_frames), max(0, step + 1))
base_p = current_act / max(1, total_act)
segment_p = (processed_step / max(1, total_frames)) * (1.0 / max(1, total_act))
pct = 20.0 + round((base_p + segment_p) * 70.0, 1)
set_progress(
client_id,
pct,
f"Processing Action {current_act + 1}/{total_act}",
processed_step,
total_frames,
status="running",
sessionId=session_id,
)
return True
reports = runtime["run_pipeline"](camera_map, utils_paths, sizes, progress_tracker)
print(f"[SPORALIZE] Pipeline done: session={session_id} elapsed={time.time() - _pipeline_t0:.1f}s actions={len(reports)}", flush=True)
ensure_not_cancelled()
set_progress(client_id, 92.0, "Preparing Playback Assets", status="running", sessionId=session_id)
ensure_not_cancelled()
fallback_camera_map = normalize_camera_videos_for_web(camera_map)
ensure_not_cancelled()
set_progress(client_id, 96.0, "Finalizing Results", status="running", sessionId=session_id)
ensure_not_cancelled()
raw_reports_path = os.path.join(session_dir, "raw_reports.json")
with open(raw_reports_path, "w", encoding="utf-8") as f:
json.dump(reports, f, indent=2, default=json_default)
with open(actions_path, "r", encoding="utf-8") as f:
raw_actions = json.load(f).get("actions", [])
formatted_actions = []
failed_actions = []
camera_videos = build_camera_video_entries(request_base_url, player_id, session_id, camera_map)
source_camera_videos = build_camera_video_entries(request_base_url, player_id, session_id, fallback_camera_map)
degree_keys = {
"head_angle",
"l_knee_angle",
"r_knee_angle",
"trunc_pitch_angle",
"trunc_roll_angle",
"trunk_pitch",
"trunk_roll",
"head_pitch_angle",
"head_roll_angle",
"left_foot_orientation_angle",
"right_foot_orientation_angle",
"difference_in_angles",
"body_to_ball_angle",
"body_orientation_vs_ball",
"stand_foot_angle",
"active_ankle_angle",
"l_elbow_shoulder_hip_angle",
"r_elbow_shoulder_hip_angle",
"backward_weighted_angle",
"forward_weighted_angle",
"leg_separation_angle",
"left_knee_angle",
"right_knee_angle",
"trunk_pitch_angle",
"max_backward_swing_angle",
"max_forward_swing_angle",
"foot_inclination_angle",
}
UNITS = {key: "\u00b0" for key in degree_keys}
UNITS.update({
"l_r_foot_distance": "cm",
"l_foot_ball_distance": "cm",
"r_foot_ball_distance": "cm",
"mid_feet_ball_dist": "cm",
"active_foot_height_pct": "%",
"ball_height_pct_body": "%",
"ball_possession_score": "%",
"ball_feet_distance": "cm",
"active_foot_ball_distance": "cm",
"stationary_foot_ball_distance_pctw_shoulder": "%",
"left_heel_height": "cm",
"right_heel_height": "cm",
"foot_anteroposterior_offset": "cm",
"max_backward_swing_distance": "cm",
"max_forward_swing_distance": "cm",
})
def unit_for(key):
return UNITS.get(key, "")
for i, rep in enumerate(reports):
ensure_not_cancelled()
raw = raw_actions[i] if i < len(raw_actions) else {}
if "error" in rep:
failed_actions.append({
"id": f"err-{uuid.uuid4().hex[:6]}",
"label": rep.get("action", raw.get("label", "Unknown")),
"start": raw.get("start", "00:00:00:00"),
"end": raw.get("end", "00:00:00:00"),
"error": rep["error"],
})
continue
an = rep.get("analytics", {})
if not isinstance(an, dict):
an = {}
action_name = rep.get("action", raw.get("label", an.get("action", "Unknown")))
sf = int(rep.get("start_frame", 0))
ef = int(rep.get("end_frame", sf))
fps = float(rep.get("fps", 30))
is_dribble = action_name.lower() == "dribble" or "per_frame" in an
tf = relative_frame(an.get("touch_frame"), sf, (ef - sf) // 2)
skeleton_frames = build_skeleton_frames(rep, an, sf, ef)
action_layout = ACTION_METRIC_LAYOUTS.get(action_name, {})
active_foot = an.get("active_foot")
pre_action_metrics = []
post_action_metrics = []
if is_dribble:
dribble_payload = an.get("per_frame", an.get("frames", []))
pre_metrics = []
in_action_metrics = []
post_metrics = []
full_interval_metrics = build_series_from_frame_payload(
dribble_payload,
unit_for,
start_frame=sf,
preferred_keys=action_layout.get("frames"),
)
else:
pre_payload = an.get("pre_action_data", an.get("pre_action", []))
post_payload = an.get("post_action_data", an.get("post_action", []))
action_frame_data = an.get("in_action_data", an.get("action_frame", {}))
if is_frame_metric_payload(pre_payload):
pre_metrics = build_series_from_frame_payload(
pre_payload,
unit_for,
start_frame=sf,
preferred_keys=action_layout.get("pre"),
)
else:
pre_metrics = []
pre_action_metrics = build_scalar_metrics(
pre_payload,
unit_for,
preferred_keys=action_layout.get("pre"),
)
in_action_metrics = build_scalar_metrics(
action_frame_data,
unit_for,
skip_keys={"active_foot"},
preferred_keys=action_layout.get("in"),
)
if "in_action_data" not in an:
in_action_metrics.extend(
build_scalar_metrics(
an,
unit_for,
skip_keys={
"action",
"active_foot",
"touch_frame",
"pre_action",
"action_frame",
"post_action",
"frames",
"left_knee_angles",
"right_knee_angles",
"torso_pitch_angles",
"head_angles",
"mid_foot_ball_distances",
"left_right_foot_distances",
},
preferred_keys=action_layout.get("top_level_scalars"),
)
)
if is_frame_metric_payload(post_payload):
post_metrics = build_series_from_frame_payload(
post_payload,
unit_for,
start_frame=sf,
preferred_keys=action_layout.get("post"),
)
else:
post_metrics = []
post_action_metrics = build_scalar_metrics(
post_payload,
unit_for,
preferred_keys=action_layout.get("post"),
)
full_payload = an.get("full_interval_data")
if full_payload is not None:
full_interval_metrics = build_series_from_frame_payload(
full_payload,
unit_for,
start_frame=sf,
preferred_keys=FULL_INTERVAL_KEYS,
)
else:
full_interval_metrics = build_top_level_interval_metrics(
an,
unit_for,
preferred_keys=FULL_INTERVAL_KEYS,
)
formatted_actions.append({
"id": f"{action_name.lower()}-{uuid.uuid4().hex[:6]}",
"label": action_name,
"activeFoot": active_foot,
"start": raw.get("start", "00:00:00:00"),
"end": raw.get("end", "00:00:00:00"),
"fps": fps,
"startFrame": sf,
"endFrame": ef,
"startSeconds": max(0.0, sf / max(1.0, fps)),
"endSeconds": max(0.0, (ef + 1) / max(1.0, fps)),
"totalFrames": ef - sf + 1,
"preFrames": max(0, tf),
"inFrame": max(0, tf),
"postFrames": max(0, (ef - sf) - tf),
"cameraClips": camera_videos,
"sourceCameraClips": source_camera_videos,
"preMetrics": dedupe_metric_items(pre_metrics),
"preActionMetrics": dedupe_metric_items(pre_action_metrics),
"inActionMetrics": dedupe_metric_items(in_action_metrics),
"postMetrics": dedupe_metric_items(post_metrics),
"postActionMetrics": dedupe_metric_items(post_action_metrics),
"fullIntervalMetrics": dedupe_metric_items(full_interval_metrics),
"skeleton": skeleton_frames,
"rawAnalytics": an,
})
print(f"Pipeline successful. Session {session_id} saved.")
response_payload = {
"id": session_id,
"playerId": player_id,
"createdAt": int(time.time() * 1000),
"targetSize": [int(target_w), int(target_h)],
"cameraCount": len(camera_map),
"actions": formatted_actions,
"failedActions": failed_actions,
}
response_payload = make_json_safe(response_payload)
ensure_not_cancelled()
session_json_path = os.path.join(session_dir, "session.json")
with open(session_json_path, "w", encoding="utf-8") as f:
json.dump(response_payload, f, indent=2)
write_session_summary(session_json_path, response_payload)
try:
push_session_to_hf(player_id, session_id, session_dir)
except Exception as sync_error:
print("--- STORAGE SYNC WARNING ---")
print(f"Session {session_id} was created locally but could not be pushed to Hugging Face storage: {sync_error}")
set_progress(
client_id,
100.0,
"Completed",
status="completed",
sessionId=session_id,
resultUrl=f"/results/{session_id}",
)
clear_cancel_request(client_id)
return response_payload
except Exception as e:
print("--- PIPELINE ERROR ---")
traceback.print_exc()
current_progress = current_progress_payload(client_id).get("progress", 0.0)
was_cancelled = isinstance(e, InterruptedError) or is_cancel_requested(client_id)
if was_cancelled:
set_progress(
client_id,
current_progress,
"Processing Cancelled",
status="cancelled",
sessionId=session_id,
error=str(e),
)
else:
set_progress(
client_id,
current_progress,
"Failed",
status="failed",
sessionId=session_id,
error=str(e),
)
clear_cancel_request(client_id)
if session_dir and os.path.isdir(session_dir):
shutil.rmtree(session_dir, ignore_errors=True)
return None
@app.post("/api/analyze")
async def analyze_endpoint(
request: Request,
playerId: str = Form(...),
targetW: float = Form(...),
targetH: float = Form(...),
clientId: str = Form(...),
videoOrders: List[int] = Form(...),
actionsJson: UploadFile = File(...),
calibration: UploadFile = File(...),
videos: List[UploadFile] = File(...),
):
session_id = f"session-{int(time.time())}-{uuid.uuid4().hex[:6]}"
_player_dir, session_dir, videos_dir = session_storage_paths(playerId, session_id)
try:
if is_cancel_requested(clientId):
raise InterruptedError("Processing cancelled by user")
set_progress(
clientId,
2.0,
"Uploading & Validating Data",
status="uploading",
sessionId=session_id,
playerId=playerId,
)
if len(videoOrders) != len(videos):
raise ValueError("Each uploaded video must include a matching camera order")
if len(set(videoOrders)) != len(videoOrders):
raise ValueError("Camera order values must be unique")
os.makedirs(videos_dir, exist_ok=True)
actions_path = os.path.join(session_dir, "actions.json")
await save_upload_to_path(actionsJson, actions_path)
calib_path = os.path.join(session_dir, "calibration.npz")
await save_upload_to_path(calibration, calib_path)
camera_map = {}
for idx, (camera_order, video) in enumerate(zip(videoOrders, videos)):
original_name = video.filename or f"camera_{camera_order}.mp4"
video_name = f"{idx:02d}_cam_{camera_order}_{safe_name(os.path.basename(original_name))}"
vid_path = os.path.join(videos_dir, video_name)
await save_upload_to_path(video, vid_path)
camera_map[int(camera_order)] = vid_path
if is_cancel_requested(clientId):
raise InterruptedError("Processing cancelled by user")
request_base_url = request_public_base_url(request)
set_progress(
clientId,
8.0,
"Queued for Processing",
status="queued",
sessionId=session_id,
playerId=playerId,
)
future = analysis_executor.submit(
run_analysis_job,
request_base_url,
playerId,
targetW,
targetH,
clientId,
session_id,
session_dir,
actions_path,
calib_path,
camera_map,
)
register_active_job(clientId, future)
future.add_done_callback(lambda _future, stored_client_id=clientId: unregister_active_job(stored_client_id))
return JSONResponse(
status_code=202,
content={
"accepted": True,
"status": "queued",
"clientId": clientId,
"sessionId": session_id,
},
)
except Exception as e:
print("--- UPLOAD ERROR ---")
traceback.print_exc()
was_cancelled = isinstance(e, InterruptedError) or is_cancel_requested(clientId)
status = "cancelled" if was_cancelled else "failed"
phase = "Processing Cancelled" if was_cancelled else "Failed"
set_progress(
clientId,
current_progress_payload(clientId).get("progress", 0.0),
phase,
status=status,
sessionId=session_id,
error=str(e),
)
if was_cancelled:
clear_cancel_request(clientId)
if session_dir and os.path.isdir(session_dir):
shutil.rmtree(session_dir, ignore_errors=True)
if was_cancelled:
raise HTTPException(status_code=409, detail=str(e))
raise HTTPException(status_code=500, detail=str(e))
async def analyze_endpoint_inline(
request: Request,
playerId: str = Form(...),
targetW: float = Form(...),
targetH: float = Form(...),
clientId: str = Form(...),
videoOrders: List[int] = Form(...),
actionsJson: UploadFile = File(...),
calibration: UploadFile = File(...),
videos: List[UploadFile] = File(...)
):
temp_dir = None
session_id = f"session-{int(time.time())}-{uuid.uuid4().hex[:6]}"
player_dir, session_dir, videos_dir = session_storage_paths(playerId, session_id)
try:
if is_cancel_requested(clientId):
raise InterruptedError("Processing cancelled by user")
set_progress(clientId, 2.0, "Uploading & Validating Data")
os.makedirs(videos_dir, exist_ok=True)
temp_dir = session_dir
# 1. Store incoming payloads
actions_path = os.path.join(session_dir, "actions.json")
with open(actions_path, "wb") as f:
f.write(await actionsJson.read())
calib_path = os.path.join(session_dir, "calibration.npz")
with open(calib_path, "wb") as f:
f.write(await calibration.read())
if len(videoOrders) != len(videos):
raise ValueError("Each uploaded video must include a matching camera order")
if len(set(videoOrders)) != len(videoOrders):
raise ValueError("Camera order values must be unique")
camera_map = {}
for idx, (camera_order, video) in enumerate(zip(videoOrders, videos)):
original_name = video.filename or f"camera_{camera_order}.mp4"
video_name = f"{idx:02d}_cam_{camera_order}_{safe_name(os.path.basename(original_name))}"
vid_path = os.path.join(videos_dir, video_name)
with open(vid_path, "wb") as f:
f.write(await video.read())
camera_id = int(camera_order)
camera_map[camera_id] = vid_path
if is_cancel_requested(clientId):
raise InterruptedError("Processing cancelled by user")
set_progress(clientId, 10.0, "Preparing AI Models")
runtime = ensure_runtime_ready()
utils_paths = {
"POSE_PATH": runtime["weights"]["POSE_PATH"],
"YOLO_PATH": runtime["weights"]["YOLO_PATH"],
"CALIBRATION_PATH": calib_path,
"ACTIONS_PATH": actions_path
}
sizes = {
"TARGET_SIZE": (int(targetW), int(targetH)),
"YOLO_IMGSZ": 960
}
print("Starting physical pipeline execution...")
set_progress(clientId, 20.0, "Extracting 3D Kinematics")
def progress_tracker(current_act, total_act, step, total_frames):
if is_cancel_requested(clientId):
return False # Signal pipeline to abort
processed_step = min(max(1, total_frames), max(0, step + 1))
base_p = current_act / max(1, total_act)
segment_p = (processed_step / max(1, total_frames)) * (1.0 / max(1, total_act))
# Rescale 20% to 90% for processing
pct = 20.0 + round((base_p + segment_p) * 70.0, 1)
set_progress(clientId, pct, f"Processing Action {current_act + 1}/{total_act}", processed_step, total_frames)
return True
# 2. Yield to worker thread to allow concurrent polling from front-end
def execute_pipeline():
return runtime["run_pipeline"](camera_map, utils_paths, sizes, progress_tracker)
reports = await run_in_threadpool(execute_pipeline)
set_progress(clientId, 92.0, "Preparing Playback Assets")
fallback_camera_map = await run_in_threadpool(normalize_camera_videos_for_web, camera_map)
set_progress(clientId, 96.0, "Finalizing Results")
raw_reports_path = os.path.join(session_dir, "raw_reports.json")
with open(raw_reports_path, "w", encoding="utf-8") as f:
json.dump(reports, f, indent=2, default=json_default)
# 3. Format output dict perfectly mapping to the Frontend Types
with open(actions_path, "r") as f:
raw_actions = json.load(f).get("actions", [])
formatted_actions = []
failed_actions = []
camera_videos = build_camera_video_entries(request, playerId, session_id, camera_map)
source_camera_videos = build_camera_video_entries(request, playerId, session_id, fallback_camera_map)
for i, rep in enumerate(reports):
raw = raw_actions[i] if i < len(raw_actions) else {}
if "error" in rep:
failed_actions.append({
"id": f"err-{uuid.uuid4().hex[:6]}",
"label": rep.get("action", raw.get("label", "Unknown")),
"start": raw.get("start", "00:00:00:00"),
"end": raw.get("end", "00:00:00:00"),
"error": rep["error"]
})
continue
an = rep.get("analytics", {})
if not isinstance(an, dict):
an = {}
action_name = rep.get("action", raw.get("label", an.get("action", "Unknown")))
sf = int(rep.get("start_frame", 0))
ef = int(rep.get("end_frame", sf))
fps = float(rep.get("fps", 30))
is_dribble = action_name.lower() == "dribble" or "per_frame" in an
tf = relative_frame(an.get("touch_frame"), sf, (ef - sf) // 2)
# --- Skeleton: support full COCO-25/WB joint range (0–32) ---
skeleton_frames = build_skeleton_frames(rep, an, sf, ef)
# --- Unit dictionary for known metric names ---
DEG = "\u00b0"
UNITS = {
"head_angle": "°", "l_knee_angle": "°", "r_knee_angle": "°",
"trunc_pitch_angle": "°", "trunc_roll_angle": "°",
"trunk_pitch": "°", "trunk_roll": "°",
"head_pitch_angle": "°", "head_roll_angle": "°",
"left_foot_orientation_angle": "°", "right_foot_orientation_angle": "°",
"difference_in_angles": "°", "body_to_ball_angle": "°",
"body_orientation_vs_ball": "°", "stand_foot_angle": "°",
"active_ankle_angle": "°", "l_elbow_shoulder_hip_angle": "°",
"r_elbow_shoulder_hip_angle": "°", "backward_weighted_angle": "°",
"forward_weighted_angle": "°", "leg_separation_angle": "°",
"l_r_foot_distance": "cm", "l_foot_ball_distance": "cm",
"r_foot_ball_distance": "cm", "mid_feet_ball_dist": "cm",
"active_foot_height_pct": "%", "ball_height_pct_body": "%",
"ball_possession_score": "%", "ball_feet_distance": "cm",
}
UNITS.update({
"left_knee_angle": DEG,
"right_knee_angle": DEG,
"trunk_pitch_angle": DEG,
"max_backward_swing_angle": DEG,
"max_forward_swing_angle": DEG,
"foot_inclination_angle": DEG,
"active_foot_ball_distance": "cm",
"stationary_foot_ball_distance_pctw_shoulder": "%",
"left_heel_height": "cm",
"right_heel_height": "cm",
"foot_anteroposterior_offset": "cm",
"max_backward_swing_distance": "cm",
"max_forward_swing_distance": "cm",
})
def unit_for(key):
return UNITS.get(key, "")
action_layout = ACTION_METRIC_LAYOUTS.get(action_name, {})
active_foot = an.get("active_foot")
pre_action_metrics = []
post_action_metrics = []
if is_dribble:
dribble_payload = an.get("per_frame", an.get("frames", []))
pre_metrics = []
in_action_metrics = []
post_metrics = []
full_interval_metrics = build_series_from_frame_payload(
dribble_payload,
unit_for,
start_frame=sf,
preferred_keys=action_layout.get("frames"),
)
else:
pre_payload = an.get("pre_action_data", an.get("pre_action", []))
post_payload = an.get("post_action_data", an.get("post_action", []))
action_frame_data = an.get("in_action_data", an.get("action_frame", {}))
if is_frame_metric_payload(pre_payload):
pre_metrics = build_series_from_frame_payload(
pre_payload,
unit_for,
start_frame=sf,
preferred_keys=action_layout.get("pre"),
)
else:
pre_metrics = []
pre_action_metrics = build_scalar_metrics(
pre_payload,
unit_for,
preferred_keys=action_layout.get("pre"),
)
in_action_metrics = build_scalar_metrics(
action_frame_data,
unit_for,
skip_keys={"active_foot"},
preferred_keys=action_layout.get("in"),
)
if "in_action_data" not in an:
in_action_metrics.extend(
build_scalar_metrics(
an,
unit_for,
skip_keys={
"action",
"active_foot",
"touch_frame",
"pre_action",
"action_frame",
"post_action",
"frames",
"left_knee_angles",
"right_knee_angles",
"torso_pitch_angles",
"head_angles",
"mid_foot_ball_distances",
"left_right_foot_distances",
},
preferred_keys=action_layout.get("top_level_scalars"),
)
)
if is_frame_metric_payload(post_payload):
post_metrics = build_series_from_frame_payload(
post_payload,
unit_for,
start_frame=sf,
preferred_keys=action_layout.get("post"),
)
else:
post_metrics = []
post_action_metrics = build_scalar_metrics(
post_payload,
unit_for,
preferred_keys=action_layout.get("post"),
)
full_payload = an.get("full_interval_data")
if full_payload is not None:
full_interval_metrics = build_series_from_frame_payload(
full_payload,
unit_for,
start_frame=sf,
preferred_keys=FULL_INTERVAL_KEYS,
)
else:
full_interval_metrics = build_top_level_interval_metrics(
an,
unit_for,
preferred_keys=FULL_INTERVAL_KEYS,
)
formatted_actions.append({
"id": f"{action_name.lower()}-{uuid.uuid4().hex[:6]}",
"label": action_name,
"activeFoot": active_foot,
"start": raw.get("start", "00:00:00:00"),
"end": raw.get("end", "00:00:00:00"),
"fps": fps,
"startFrame": sf,
"endFrame": ef,
"startSeconds": max(0.0, sf / max(1.0, fps)),
"endSeconds": max(0.0, (ef + 1) / max(1.0, fps)),
"totalFrames": ef - sf + 1,
"preFrames": max(0, tf),
"inFrame": max(0, tf),
"postFrames": max(0, (ef - sf) - tf),
"cameraClips": camera_videos,
"sourceCameraClips": source_camera_videos,
"preMetrics": dedupe_metric_items(pre_metrics),
"preActionMetrics": dedupe_metric_items(pre_action_metrics),
"inActionMetrics": dedupe_metric_items(in_action_metrics),
"postMetrics": dedupe_metric_items(post_metrics),
"postActionMetrics": dedupe_metric_items(post_action_metrics),
"fullIntervalMetrics": dedupe_metric_items(full_interval_metrics),
"skeleton": skeleton_frames,
"rawAnalytics": an,
})
print("Pipeline successful. Yielding payload payload.")
response_payload = {
"id": session_id,
"playerId": playerId,
"createdAt": int(time.time() * 1000),
"targetSize": [int(targetW), int(targetH)],
"cameraCount": len(camera_map),
"actions": formatted_actions,
"failedActions": failed_actions
}
response_payload = make_json_safe(response_payload)
session_json_path = os.path.join(session_dir, "session.json")
with open(session_json_path, "w", encoding="utf-8") as f:
json.dump(response_payload, f, indent=2)
write_session_summary(session_json_path, response_payload)
try:
push_session_to_hf(playerId, session_id, session_dir)
except Exception as sync_error:
print("--- STORAGE SYNC WARNING ---")
print(f"Session {session_id} was created locally but could not be pushed to Hugging Face storage: {sync_error}")
set_progress(clientId, 100.0, "Completed", status="completed")
return response_payload
except Exception as e:
print("--- PIPELINE ERROR ---")
traceback.print_exc()
was_cancelled = isinstance(e, InterruptedError) or is_cancel_requested(clientId)
if was_cancelled:
set_progress(clientId, current_progress_payload(clientId).get("progress", 0.0), "Processing Cancelled", status="cancelled")
clear_cancel_request(clientId)
else:
set_progress(clientId, current_progress_payload(clientId).get("progress", 0.0), "Failed", status="failed")
if temp_dir and os.path.isdir(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if was_cancelled:
raise HTTPException(status_code=409, detail=str(e))
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
# Start ASGI interface natively mapping locally to the React vite environment
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|