Spaces:
Sleeping
Sleeping
File size: 75,382 Bytes
26cad64 09463d1 084b23f 26cad64 7219507 26cad64 09463d1 26cad64 09463d1 26cad64 09463d1 26cad64 09463d1 26cad64 7219507 26cad64 09463d1 26cad64 09463d1 26cad64 09463d1 26cad64 09463d1 26cad64 7e220d2 084b23f 7e220d2 26cad64 7e220d2 26cad64 7e220d2 084b23f 26cad64 084b23f 26cad64 084b23f 7e220d2 26cad64 7e220d2 084b23f 26cad64 7e220d2 084b23f 7e220d2 26cad64 7e220d2 26cad64 084b23f 26cad64 084b23f 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 09463d1 26cad64 7219507 26cad64 09463d1 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 09463d1 26cad64 09463d1 26cad64 7219507 09463d1 7219507 09463d1 7219507 09463d1 26cad64 09463d1 26cad64 530dcd4 26cad64 09463d1 26cad64 7219507 26cad64 09463d1 7e220d2 09463d1 26cad64 09463d1 084b23f 09463d1 084b23f 09463d1 084b23f 09463d1 084b23f 09463d1 084b23f 09463d1 084b23f 09463d1 26cad64 09463d1 26cad64 09463d1 26cad64 09463d1 26cad64 7219507 09463d1 7219507 26cad64 7219507 09463d1 26cad64 09463d1 26cad64 09463d1 26cad64 7219507 09463d1 7219507 26cad64 7219507 09463d1 26cad64 530dcd4 09463d1 26cad64 7219507 09463d1 26cad64 09463d1 26cad64 09463d1 084b23f 7e220d2 084b23f 7e220d2 26cad64 084b23f 26cad64 084b23f 26cad64 7219507 26cad64 7219507 26cad64 7219507 26cad64 09463d1 26cad64 7219507 26cad64 | 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 | """Public CPU login gateway for the private AutoML GPU Space."""
from __future__ import annotations
import os
import shutil
import tempfile
import time
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Mapping
import gradio as gr
import pandas as pd
import auth_storage
from ui_design import (
APP_CSS,
APP_HEADER_HTML,
AUTOMATIC_SELECTION,
EXISTING_DATA_GUIDE_HTML,
INFERENCE_GUIDE_HTML,
QUALITY_PRESET_CHOICES,
RESEARCH_NOTICE_HTML,
RESPONSIVE_HEAD_HTML,
UPLOAD_DATA_GUIDE_HTML,
professional_theme,
)
from gateway_auth import (
AuthResult,
change_password,
handle_denied_request,
login,
request_signup,
requester_key,
)
from gateway_client import BackendResult, BackendUnavailable, GatewayBackendClient
from gateway_contract import (
PROTOCOL_VERSION,
ContractError,
check_upload_size,
inspect_package_manifest,
load_gateway_catalog,
predictions_frame,
)
from gateway_jobs import ROUTED_JOB_ADMISSION, JobRejected
from gateway_routing import (
VALID_ROUTING_MODES,
RouteDecision,
RoutingError,
declare_route,
route_existing,
route_prediction,
route_uploaded,
)
GATEWAY_CATALOG_PATH = Path(__file__).with_name("gateway_catalog.json")
AUTO_CHOICE = "Auto"
AUTO_DEVICE = "auto - GPU if available"
IMAGE_DEVICE_CHOICES = [AUTO_DEVICE, "cpu", "cuda - requires GPU hardware"]
IMAGE_TASK_CHOICES = [
"classification",
"object_detection",
"instance_segmentation",
"semantic_segmentation",
]
IMAGE_BACKEND_CHOICES = [
"Auto",
"Existing classification pipeline",
"Medical image agent",
"AutoGluon AutoMM",
"YOLO",
"Benchmark backends",
]
IMAGE_FORMAT_CHOICES = ["auto", "folder", "csv", "coco", "yolo", "semantic-mask"]
IMAGE_BACKBONE_CHOICES = [
AUTO_CHOICE,
"raw_pixels",
"mobilenet_v3_small",
"resnet18",
"resnet50",
"densenet121",
"efficientnet_b0",
]
IMAGE_CLASSIFIER_CHOICES = [
AUTO_CHOICE,
"logistic_regression",
"random_forest",
"autogluon",
]
IMAGE_SIZE_CHOICES = [AUTO_CHOICE, "32", "48", "64", "96", "128", "224"]
CANCER_PRESET_CHOICES = [
"Auto - agent decides",
"lc25000_densenet121",
"lc25000_resnet50",
"breakhis_efficientnet_b0",
"ham10000_efficientnet_b0",
"ham10000_mobilenet_v3",
"pcam_resnet18",
]
FEATURE_SELECTION_CHOICES = [
AUTOMATIC_SELECTION,
"no_feature_selection_tool",
"t_test_feature_selection_tool",
]
TRANSFORM_CHOICES = [
AUTOMATIC_SELECTION,
"no_transform_tool",
"pca_transform_tool",
"subspace_transform_tool",
"cluster_undersample_transform_tool",
]
ML_CHOICES = [AUTOMATIC_SELECTION, "autogluon_tool"]
QUALITY_PRESETS = QUALITY_PRESET_CHOICES
def _catalog() -> dict[str, Any]:
if GATEWAY_CATALOG_PATH.is_file():
return load_gateway_catalog(GATEWAY_CATALOG_PATH)
return {
"schema_version": 1,
"datasets": {
"No datasets configured": {"targets": [], "image": False}
},
}
def _dataset_metadata(dataset_name: str) -> dict[str, Any]:
return dict(_catalog()["datasets"].get(dataset_name) or {})
def routing_mode_from_env() -> str:
mode = os.getenv("AUTOML_ROUTING_MODE", "dual").strip().lower()
if mode not in VALID_ROUTING_MODES:
raise RuntimeError(
"AUTOML_ROUTING_MODE must be dual or single-gpu."
)
return mode
def format_route_preview(decision: RouteDecision) -> str:
label = "CPU" if decision.profile == "cpu" else "GPU"
return f"**Compute route: Private {label}** — {decision.explanation}"
def _route_preview_error(exc: Exception) -> str:
return f"**Compute route unavailable** — {exc}"
def existing_route_preview(
dataset: Any,
image_backbone: Any,
image_device: Any,
image_task: Any,
image_backend: Any,
image_benchmark_backends: Any,
cancer_preset: Any,
) -> str:
payload = {
"image_backbone": image_backbone,
"image_device": image_device,
"image_task": image_task,
"image_backend": image_backend,
"image_benchmark_backends": image_benchmark_backends,
"cancer_preset": cancer_preset,
}
try:
decision = route_existing(
payload,
dataset_is_image=bool(_dataset_metadata(str(dataset)).get("image")),
routing_mode=routing_mode_from_env(),
)
return format_route_preview(decision)
except (RoutingError, RuntimeError) as exc:
return _route_preview_error(exc)
def uploaded_route_preview(
data_type: Any,
image_backbone: Any,
image_device: Any,
uploaded_image_backend: Any,
cancer_preset: Any,
) -> str:
payload = {
"data_type": data_type,
"image_backbone": image_backbone,
"image_device": image_device,
"uploaded_image_backend": uploaded_image_backend,
"cancer_preset": cancer_preset,
}
try:
return format_route_preview(
route_uploaded(payload, routing_mode=routing_mode_from_env())
)
except (RoutingError, RuntimeError) as exc:
return _route_preview_error(exc)
def replay_route_preview(manifest: Mapping[str, Any] | None, image_device: Any) -> str:
try:
return format_route_preview(
route_prediction(
{"image_device": image_device},
dict(manifest or {}),
routing_mode=routing_mode_from_env(),
)
)
except (RoutingError, RuntimeError) as exc:
return _route_preview_error(exc)
def _normalize_token(value: Any) -> str:
return str(value or "").strip().lower().replace("-", "_").replace(" ", "_")
def normalize_image_task(value: Any) -> str:
token = _normalize_token(value)
aliases = {
"classification": "classification",
"object_detection": "object_detection",
"detection": "object_detection",
"instance_segmentation": "instance_segmentation",
"semantic_segmentation": "semantic_segmentation",
}
return aliases.get(token, "classification")
def normalize_image_backend(value: Any) -> str:
aliases = {
"auto": "auto",
"existing_classification_pipeline": "existing",
"existing": "existing",
"medical_image_agent": "medical_agent",
"medical_agent": "medical_agent",
"autogluon_automm": "automm",
"automm": "automm",
"yolo": "yolo",
"benchmark_backends": "benchmark",
"benchmark": "benchmark",
}
return aliases.get(_normalize_token(value), "auto")
def get_image_task_ui_state(image_task: Any, image_backend: Any) -> dict[str, Any]:
task = normalize_image_task(image_task)
backend = normalize_image_backend(image_backend)
effective = backend
if backend == "auto":
effective = "existing" if task == "classification" else (
"automm" if task == "semantic_segmentation" else "yolo"
)
notes = {
"classification": "Classification supports the existing classifier, Medical Image Agent, AutoMM, and benchmark mode.",
"object_detection": "Object detection uses the managed COCO dataset for an existing image dataset.",
"instance_segmentation": "Instance segmentation uses managed COCO polygon/RLE annotations.",
"semantic_segmentation": "Semantic segmentation requires a managed image/mask manifest.",
}
return {
"classification": task == "classification" and effective == "existing",
"medical": task == "classification" and effective == "medical_agent",
"detection": task == "object_detection",
"instance": task == "instance_segmentation",
"semantic": task == "semantic_segmentation",
"benchmark": backend == "benchmark",
"optional": effective in {"automm", "yolo", "benchmark"},
"note": notes[task],
}
def image_task_ui_updates(image_task: Any, image_backend: Any):
state = get_image_task_ui_state(image_task, image_backend)
return (
gr.update(visible=state["classification"]),
gr.update(visible=state["medical"]),
gr.update(visible=state["detection"]),
gr.update(visible=state["instance"]),
gr.update(visible=state["semantic"]),
gr.update(visible=state["benchmark"]),
gr.update(visible=state["optional"]),
gr.update(value=state["note"]),
)
def uploaded_image_backend_updates(image_backend: Any):
backend = normalize_image_backend(image_backend)
return gr.update(visible=backend == "existing"), gr.update(visible=backend == "medical_agent")
def update_existing_dataset_controls(dataset_name: str):
metadata = _dataset_metadata(dataset_name)
targets = list(metadata.get("targets") or [])
image = bool(metadata.get("image"))
return (
gr.update(choices=targets, value=targets[0] if targets else None),
gr.update(visible=not image, value=False if image else False),
gr.update(label="Validation holdout" if image else "Test holdout"),
gr.update(visible=not image),
gr.update(visible=image),
)
def update_uploaded_type_controls(data_type: str):
image = data_type == "Image Dataset"
return (
gr.update(
label="Training data (image ZIP or CSV manifest)" if image else "Training data (CSV)",
file_types=[".zip", ".csv"] if image else [".csv"],
),
gr.update(
label="Test data (image ZIP or CSV manifest, optional)" if image else "Test data (CSV, optional)",
file_types=[".zip", ".csv"] if image else [".csv"],
),
gr.update(visible=not image),
gr.update(visible=not image),
gr.update(label="Validation holdout" if image else "Test holdout"),
gr.update(visible=not image),
gr.update(visible=image),
)
def _file_path(value: Any) -> str:
if value is None:
return ""
if isinstance(value, (str, os.PathLike)):
return str(value)
for attribute in ("path", "name"):
candidate = getattr(value, attribute, None)
if candidate:
return str(candidate)
if isinstance(value, Mapping):
for key in ("path", "name"):
if value.get(key):
return str(value[key])
return ""
def update_uploaded_targets(data_type: str, train_file: Any = None):
if data_type == "Image Dataset":
return gr.update(choices=["label"], value="label")
path = _file_path(train_file)
if not path:
return gr.update(choices=[], value=None)
try:
columns = pd.read_csv(path, nrows=1).columns.tolist()
except Exception:
return gr.update(choices=[], value=None)
return gr.update(choices=columns, value=columns[0] if columns else None)
def _saved_model_choices(
session_token: str | None, request: gr.Request | None = None
) -> list[tuple[str, str]]:
username = auth_storage.current_username(request, session_token)
if not username:
return []
choices = []
for record in auth_storage.list_saved_models(username):
task = str(record.get("task_type") or "").strip()
artifact = str(record.get("artifact_type") or "model")
detail = f"{artifact}/{task}" if task else artifact
created = str(record.get("created_at") or "")[:10] or "unknown date"
target = str(record.get("target_column") or "unknown target")
label = f"{record.get('display_name') or 'AutoML model'} - {detail} - {target} - {created}"
choices.append((label, str(record["model_id"])))
return choices
def refresh_saved_model_choices(
selected: str | None = None,
session_token: str | None = None,
request: gr.Request | None = None,
):
choices = _saved_model_choices(session_token, request)
values = {value for _, value in choices}
return gr.update(
choices=choices,
value=selected if selected in values else None,
interactive=bool(choices),
label="Saved Cloud Model",
)
def _auth_controls(signed_in: bool):
return (
gr.update(interactive=signed_in),
gr.update(interactive=signed_in),
gr.update(interactive=signed_in),
gr.update(interactive=False),
)
def _neutral_replay_outputs(signed_in: bool):
return (
"Choose a saved cloud model or upload a trained model package."
if signed_in
else "Sign in before loading a model package.",
"",
"",
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False, value=AUTO_DEVICE),
gr.update(visible=False, value=16),
{},
"Choose a model to inspect its compute route."
if signed_in
else "Sign in to inspect the model compute route.",
"Status: _idle_",
"",
pd.DataFrame(),
)
def _pending_account_controls():
requests = auth_storage.list_pending_account_requests()
rows = [
[str(record.get("username") or ""), str(record.get("requested_at") or "")]
for record in requests
]
choices = [row[0] for row in rows]
return rows, choices
def _admin_ui_outputs(username: str):
if not auth_storage.is_admin(username):
return (
gr.update(visible=False),
gr.update(value=[]),
gr.update(choices=[], value=None),
"",
)
rows, choices = _pending_account_controls()
return (
gr.update(visible=True),
gr.update(value=rows),
gr.update(choices=choices, value=choices[0] if choices else None),
f"{len(choices)} pending account request(s).",
)
def _auth_outputs(
result: AuthResult,
request: gr.Request | None = None,
):
if result.ok:
return (
result.message,
result.session_token,
gr.update(visible=False),
gr.update(visible=True),
gr.update(visible=True),
f"Signed in as **{result.username}**",
refresh_saved_model_choices(
None,
result.session_token,
request,
),
"",
*_auth_controls(True),
*_neutral_replay_outputs(True),
gr.update(visible=False),
"",
"",
None,
*_admin_ui_outputs(result.username),
)
denied = result.account_status == auth_storage.ACCOUNT_STATUS_DENIED
return (
result.message,
"",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
"Sign in or create an account to continue.",
refresh_saved_model_choices(None, "", request),
"",
*_auth_controls(False),
*_neutral_replay_outputs(False),
gr.update(visible=denied),
result.username if denied else "",
"",
None,
*_admin_ui_outputs(""),
)
def restore_auth_ui(
session_token: str | None = None,
request: gr.Request | None = None,
):
token = str(session_token or "").strip()
username = auth_storage.current_username(request, token)
if username:
return _auth_outputs(
AuthResult(
True,
f"Signed in as {username}.",
session_token=token,
username=username,
),
request,
)
message = (
"Your session expired. Sign in again."
if token
else "Sign in or create an account to continue."
)
return _auth_outputs(AuthResult(False, message), request)
def handle_login_ui(
username: str, password: str, request: gr.Request | None = None
):
return _auth_outputs(
login(username, password, requester_key(request)),
request,
)
def handle_signup_ui(
username: str,
password: str,
confirm_password: str,
request: gr.Request | None = None,
):
return _auth_outputs(
request_signup(
username,
password,
confirm_password,
requester_key(request),
),
request,
)
def handle_denied_request_ui(
username: str,
password: str,
choice: str,
):
result = handle_denied_request(username, password, choice)
denied = result.account_status == auth_storage.ACCOUNT_STATUS_DENIED
return (
result.message,
gr.update(visible=denied),
result.username if denied else "",
"",
None,
)
def handle_logout_ui():
return _auth_outputs(AuthResult(False, "Signed out."))
def handle_password_change_ui(
username: str,
old_password: str,
new_password: str,
confirm_password: str,
):
return change_password(
username, old_password, new_password, confirm_password
).message
def refresh_pending_account_requests(
session_token: str | None = None,
request: gr.Request | None = None,
):
admin_username = auth_storage.current_username(request, session_token)
admin = auth_storage.get_user(admin_username)
if (
not auth_storage.is_admin(admin_username)
or admin is None
or str(admin.get("account_status") or "")
!= auth_storage.ACCOUNT_STATUS_APPROVED
):
return (
gr.update(value=[]),
gr.update(choices=[], value=None),
"Only an approved administrator can view account requests.",
)
rows, choices = _pending_account_controls()
return (
gr.update(value=rows),
gr.update(choices=choices, value=choices[0] if choices else None),
f"{len(choices)} pending account request(s).",
)
def handle_admin_account_review(
session_token: str,
pending_username: str,
decision: str,
request: gr.Request | None = None,
):
admin_username = ""
try:
admin_username = auth_storage.require_authenticated_username(
request,
session_token,
)
reviewed = auth_storage.review_account_request(
admin_username,
pending_username,
decision,
)
message = (
f"Account request for {reviewed['username']} was "
f"{reviewed['account_status']} by {admin_username}."
)
except (PermissionError, ValueError) as exc:
message = f"Could not review account request: {exc}"
except Exception:
message = "Could not review the account request. Try again later."
rows, choices = (
_pending_account_controls()
if auth_storage.is_admin(admin_username)
else ([], [])
)
return (
gr.update(value=rows),
gr.update(choices=choices, value=choices[0] if choices else None),
message,
)
def handle_admin_account_approval(
session_token: str,
pending_username: str,
request: gr.Request | None = None,
):
return handle_admin_account_review(
session_token,
pending_username,
auth_storage.ACCOUNT_STATUS_APPROVED,
request,
)
def handle_admin_account_denial(
session_token: str,
pending_username: str,
request: gr.Request | None = None,
):
return handle_admin_account_review(
session_token,
pending_username,
auth_storage.ACCOUNT_STATUS_DENIED,
request,
)
def _model_info(manifest: Mapping[str, Any], artifact_type: str):
target = str(
manifest.get("target_column") or manifest.get("label_column") or "Unknown"
)
if artifact_type == "image":
task = normalize_image_task(manifest.get("task_type") or "classification")
names = {
"classification": ("Image classifier", "class label"),
"object_detection": ("Object detection model", "bounding boxes"),
"instance_segmentation": ("Instance segmentation model", "masks and bounding boxes"),
"semantic_segmentation": ("Semantic segmentation model", "segmentation masks"),
}
model_type, output = names[task]
info = f"### Loaded Model\n\n**Model type:** {model_type}\n\n**Output:** {output}\n\n**Prediction target:** `{target}`\n\n**Required input:** one image file"
cpu_decision = route_prediction(
{"image_device": "cpu"},
manifest,
routing_mode=routing_mode_from_env(),
)
default_device = (
"cpu"
if cpu_decision.profile == "cpu"
else "cuda - requires GPU hardware"
)
return (
info,
gr.update(visible=False),
gr.update(visible=True),
gr.update(visible=True, value=default_device),
gr.update(visible=True),
gr.update(interactive=True),
dict(manifest),
replay_route_preview(manifest, default_device),
)
protected = "enabled" if manifest.get("input_schema_file") else "legacy package"
info = f"### Loaded Model\n\n**Model type:** Tabular model\n\n**Prediction target:** `{target}`\n\n**Input schema protection:** {protected}\n\n**Required input:** one CSV containing one row"
return (
info,
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False, value="cpu"),
gr.update(visible=False),
gr.update(interactive=True),
dict(manifest),
replay_route_preview(manifest, "cpu"),
)
def update_single_input_controls(
model_file: Any,
saved_model_id: str | None,
session_token: str | None,
request: gr.Request | None = None,
):
username = auth_storage.current_username(request, session_token)
if not username:
return (
"Sign in before loading a model package.",
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(interactive=False),
{},
"Sign in to inspect the model compute route.",
)
if not saved_model_id and not model_file:
return (
"Choose a saved cloud model or upload a trained model package.",
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(interactive=False),
{},
"Choose a model to inspect its compute route.",
)
try:
if saved_model_id:
record = auth_storage.get_saved_model(username, saved_model_id)
if record is None:
raise PermissionError("Saved model not found for this account.")
manifest = auth_storage.manifest_from_record(record)
artifact_type = str(
record.get("artifact_type")
or manifest.get("artifact_type")
or "tabular"
)
return _model_info(manifest, artifact_type)
package_path = _file_path(model_file)
if not package_path:
raise ValueError("Choose a saved cloud model or upload a package.")
manifest, artifact_type = inspect_package_manifest(package_path)
return _model_info(manifest, artifact_type)
except Exception as exc:
return (
f"Could not inspect the model package: {exc}",
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(interactive=False),
{},
_route_preview_error(exc),
)
def _training_outputs(
status: str,
metrics: str = "",
predictions: pd.DataFrame | None = None,
summary: str = "",
tools: str = "",
reasoning: str = "",
package: str | None = None,
):
return status, metrics, predictions if predictions is not None else pd.DataFrame(), summary, tools, reasoning, package
def _training_error(message: str):
safe = str(message or "The request failed.")
if not safe.lower().startswith("training could not"):
safe = f"Training could not be completed: {safe}"
return _training_outputs(safe)
def _gateway_egress_root() -> Path:
return Path(
os.getenv("AUTOML_GATEWAY_EGRESS_DIR", "/tmp/automl_gateway_egress")
).expanduser()
def _gateway_egress_max_age() -> int:
try:
return max(
60,
int(os.getenv("AUTOML_GATEWAY_EGRESS_MAX_AGE_SECONDS", "3600")),
)
except ValueError:
return 3600
def prune_gateway_egress(
root: str | Path | None = None,
*,
max_age_seconds: int | None = None,
now: float | None = None,
) -> int:
base = Path(root) if root is not None else _gateway_egress_root()
if not base.exists():
return 0
current = float(now if now is not None else time.time())
maximum = max(60, int(max_age_seconds or _gateway_egress_max_age()))
removed = 0
for child in list(base.iterdir()):
try:
expired = current - child.stat().st_mtime > maximum
except OSError:
continue
if not expired:
continue
try:
shutil.rmtree(child) if child.is_dir() else child.unlink()
removed += 1
except OSError:
continue
return removed
def _copy_to_gateway_egress(source_path: str) -> str:
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError("The backend model package was not downloaded.")
root = _gateway_egress_root()
root.mkdir(parents=True, exist_ok=True)
request_dir = root / uuid.uuid4().hex
request_dir.mkdir(mode=0o700)
destination = request_dir / (source.name or "automl_model.zip")
shutil.copy2(source, destination)
os.utime(request_dir, None)
return str(destination)
def _cleanup_files(paths: tuple[str, ...] | list[str]) -> None:
for value in paths:
try:
path = Path(value)
if path.is_file():
path.unlink()
except OSError:
continue
def _display_name(payload: Mapping[str, Any]) -> str:
source = str(payload.get("dataset") or payload.get("data_type") or "AutoML model")
target = str(payload.get("target_column") or "").strip()
stamp = datetime.now().strftime("%Y-%m-%d %H:%M")
return f"{source} ({target}) {stamp}" if target else f"{source} {stamp}"
def render_training_result(
username: str,
envelope: Mapping[str, Any],
package_path: str | None,
display_name: str,
):
if envelope.get("ok") is not True:
error = envelope.get("error") or {}
return _training_error(str(error.get("message") or "The backend job failed."))
summary = str(envelope.get("summary") or "")
download = None
if package_path:
try:
manifest, artifact_type = inspect_package_manifest(package_path)
download = _copy_to_gateway_egress(package_path)
try:
record = auth_storage.save_model_for_user(
username,
download,
display_name=display_name,
manifest=manifest,
artifact_type=artifact_type,
)
summary += f"\n\nSaved cloud model: `{record.get('display_name')}` (encrypted, id `{record.get('model_id')}`)."
except Exception:
summary += "\n\nSaved cloud model: cloud save failed; use the immediate download instead."
except Exception as exc:
summary += f"\n\nModel package rejected by the gateway: {exc}"
download = None
return _training_outputs(
str(envelope.get("status") or "Complete"),
str(envelope.get("metrics_markdown") or ""),
predictions_frame(envelope),
summary,
str(envelope.get("tools_used") or ""),
str(envelope.get("reasoning") or ""),
download,
)
def run_existing_remote(
payload: Mapping[str, Any],
session_token: str | None,
request: gr.Request | None = None,
):
"""Authenticated generator for one existing-dataset backend job."""
try:
username = auth_storage.require_authenticated_username(request, session_token)
except PermissionError:
yield _training_error("Sign in before starting an analysis.")
return
result: BackendResult | None = None
decision: RouteDecision | None = None
try:
routed_payload = dict(payload)
metadata = _dataset_metadata(str(routed_payload.get("dataset") or ""))
dataset_is_image = bool(metadata.get("image"))
routed_payload["data_type"] = (
"Image Dataset" if dataset_is_image else "Tabular CSV"
)
mode = routing_mode_from_env()
decision = route_existing(
routed_payload,
dataset_is_image=dataset_is_image,
routing_mode=mode,
)
request_payload = declare_route(routed_payload, decision, mode)
profile_label = decision.profile.upper()
yield _training_outputs(
f"Queued for the private {profile_label} backend…"
)
with ROUTED_JOB_ADMISSION.lease(
decision.profile, username, timeout=30
):
yield _training_outputs(f"{profile_label} backend is waking up…")
client = GatewayBackendClient.from_env(decision.profile)
result = client.run_existing(request_payload)
prune_gateway_egress()
yield render_training_result(
username,
result.envelope,
result.package_path,
_display_name(request_payload),
)
except BackendUnavailable as exc:
if decision is not None and decision.profile == "cpu":
yield _training_error(
"The private CPU backend is unavailable; GPU fallback was not attempted."
)
else:
yield _training_error(str(exc))
except (ContractError, RoutingError, JobRejected) as exc:
yield _training_error(str(exc))
except Exception:
yield _training_error("The gateway could not complete the request.")
finally:
if result is not None:
_cleanup_files(result.cleanup_files)
def run_uploaded_remote(
payload: Mapping[str, Any],
train_file: Any,
test_file: Any,
session_token: str | None,
request: gr.Request | None = None,
):
"""Authenticated generator for one uploaded-dataset backend job."""
try:
username = auth_storage.require_authenticated_username(request, session_token)
except PermissionError:
yield _training_error("Sign in before starting an analysis.")
return
train_path = _file_path(train_file)
test_path = _file_path(test_file)
result: BackendResult | None = None
decision: RouteDecision | None = None
try:
if not train_path:
raise ContractError("Upload a training dataset first.")
check_upload_size(train_path)
if test_path:
check_upload_size(test_path)
mode = routing_mode_from_env()
decision = route_uploaded(payload, routing_mode=mode)
request_payload = declare_route(payload, decision, mode)
profile_label = decision.profile.upper()
yield _training_outputs(
f"Queued for the private {profile_label} backend…"
)
with ROUTED_JOB_ADMISSION.lease(
decision.profile, username, timeout=30
):
yield _training_outputs(f"{profile_label} backend is waking up…")
client = GatewayBackendClient.from_env(decision.profile)
result = client.run_uploaded(
request_payload, train_path, test_path or None
)
prune_gateway_egress()
yield render_training_result(
username,
result.envelope,
result.package_path,
_display_name(request_payload),
)
except BackendUnavailable as exc:
if decision is not None and decision.profile == "cpu":
yield _training_error(
"The private CPU backend is unavailable; GPU fallback was not attempted."
)
else:
yield _training_error(str(exc))
except (ContractError, RoutingError, JobRejected) as exc:
yield _training_error(str(exc))
except Exception:
yield _training_error("The gateway could not complete the request.")
finally:
if result is not None:
_cleanup_files(result.cleanup_files)
def predict_remote(
model_file: Any,
tabular_text: str,
tabular_file: Any,
image_file: Any,
image_device: str,
image_batch_size: int,
saved_model_id: str | None,
session_token: str | None,
request: gr.Request | None = None,
):
"""Authenticate, materialize one package, and replay it privately."""
cleanup_root = ""
decision: RouteDecision | None = None
try:
username = auth_storage.require_authenticated_username(request, session_token)
if saved_model_id:
package_path, cleanup_root = auth_storage.materialize_saved_model(
username, saved_model_id
)
else:
package_path = _file_path(model_file)
if not package_path:
raise ContractError("Choose a saved model or upload a package first.")
manifest, artifact_type = inspect_package_manifest(package_path)
if not manifest.get("artifact_type"):
manifest = {**manifest, "artifact_type": artifact_type}
tabular_path = _file_path(tabular_file)
image_path = _file_path(image_file)
if artifact_type == "image" and not image_path:
raise ContractError("Upload one image for this model.")
if artifact_type != "image" and not tabular_path and not str(tabular_text or "").strip():
raise ContractError("Upload one tabular CSV row for this model.")
if tabular_path:
check_upload_size(tabular_path)
if image_path:
check_upload_size(image_path)
payload = {
"protocol_version": PROTOCOL_VERSION,
"tabular_text": str(tabular_text or ""),
"image_device": image_device or AUTO_DEVICE,
"image_batch_size": int(image_batch_size or 16),
}
mode = routing_mode_from_env()
decision = route_prediction(payload, manifest, routing_mode=mode)
request_payload = declare_route(payload, decision, mode)
with ROUTED_JOB_ADMISSION.lease(
decision.profile, username, timeout=30
):
client = GatewayBackendClient.from_env(decision.profile)
result = client.predict_package(
request_payload,
package_path,
tabular_path=tabular_path or None,
image_path=image_path or None,
)
if result.envelope.get("ok") is not True:
error = result.envelope.get("error") or {}
return f"Prediction could not be completed: {error.get('message') or 'Prediction failed.'}", "", pd.DataFrame()
return (
str(result.envelope.get("status") or "Prediction complete."),
str(result.envelope.get("summary") or ""),
predictions_frame(result.envelope),
)
except BackendUnavailable as exc:
if decision is not None and decision.profile == "cpu":
return (
"Prediction could not be completed: The private CPU backend is unavailable; GPU fallback was not attempted.",
"",
pd.DataFrame(),
)
return f"Prediction could not be completed: {exc}", "", pd.DataFrame()
except (ContractError, RoutingError, JobRejected, PermissionError) as exc:
return f"Prediction could not be completed: {exc}", "", pd.DataFrame()
except Exception:
return "Prediction could not be completed: The gateway could not complete the prediction.", "", pd.DataFrame()
finally:
if cleanup_root:
shutil.rmtree(cleanup_root, ignore_errors=True)
def _existing_payload(
dataset,
target_column,
split_training_data,
test_size,
preset,
time_limit,
trials,
feature_selection_tool,
transform_tool,
ml_tool,
image_backbone,
image_classifier,
image_size,
image_device,
image_batch_size,
image_pretrained,
image_task,
image_backend,
image_dataset_format,
image_epochs,
image_imgsz,
image_benchmark_backends,
cancer_preset,
):
return {
"protocol_version": PROTOCOL_VERSION,
"dataset": dataset,
"target_column": target_column,
"split_training_data": bool(split_training_data),
"test_size": float(test_size),
"preset": preset,
"time_limit": int(time_limit),
"trials": int(trials),
"feature_selection_tool": feature_selection_tool,
"transform_tool": transform_tool,
"ml_tool": ml_tool,
"image_backbone": image_backbone,
"image_classifier": image_classifier,
"image_size": image_size,
"image_device": image_device,
"image_batch_size": int(image_batch_size),
"image_pretrained": bool(image_pretrained),
"image_task": image_task,
"image_backend": image_backend,
"image_dataset_format": image_dataset_format,
"image_data_path": "",
"image_epochs": int(image_epochs),
"image_imgsz": int(image_imgsz),
"image_benchmark_backends": image_benchmark_backends,
"cancer_preset": cancer_preset,
}
def existing_ui_handler(
dataset,
target_column,
split_training_data,
test_size,
preset,
time_limit,
trials,
feature_selection_tool,
transform_tool,
ml_tool,
image_backbone,
image_classifier,
image_size,
image_device,
image_batch_size,
image_pretrained,
image_task,
image_backend,
image_dataset_format,
image_epochs,
image_imgsz,
image_benchmark_backends,
cancer_preset,
session_token,
request: gr.Request | None = None,
):
payload = _existing_payload(
dataset,
target_column,
split_training_data,
test_size,
preset,
time_limit,
trials,
feature_selection_tool,
transform_tool,
ml_tool,
image_backbone,
image_classifier,
image_size,
image_device,
image_batch_size,
image_pretrained,
image_task,
image_backend,
image_dataset_format,
image_epochs,
image_imgsz,
image_benchmark_backends,
cancer_preset,
)
yield from run_existing_remote(payload, session_token, request)
def _uploaded_payload(
data_type,
target_column,
split_training_data,
test_size,
preset,
time_limit,
trials,
feature_selection_tool,
transform_tool,
ml_tool,
image_backbone,
image_classifier,
image_size,
image_device,
image_batch_size,
image_pretrained,
uploaded_image_backend,
cancer_preset,
):
return {
"protocol_version": PROTOCOL_VERSION,
"data_type": data_type,
"target_column": target_column,
"split_training_data": bool(split_training_data),
"test_size": float(test_size),
"preset": preset,
"time_limit": int(time_limit),
"trials": int(trials),
"feature_selection_tool": feature_selection_tool,
"transform_tool": transform_tool,
"ml_tool": ml_tool,
"image_backbone": image_backbone,
"image_classifier": image_classifier,
"image_size": image_size,
"image_device": image_device,
"image_batch_size": int(image_batch_size),
"image_pretrained": bool(image_pretrained),
"uploaded_image_backend": uploaded_image_backend,
"cancer_preset": cancer_preset,
"image_epochs": 1,
"image_imgsz": 64,
}
def uploaded_ui_handler(
data_type,
target_column,
split_training_data,
test_size,
preset,
time_limit,
trials,
feature_selection_tool,
transform_tool,
ml_tool,
image_backbone,
image_classifier,
image_size,
image_device,
image_batch_size,
image_pretrained,
uploaded_image_backend,
cancer_preset,
train_file,
test_file,
session_token,
request: gr.Request | None = None,
):
payload = _uploaded_payload(
data_type,
target_column,
split_training_data,
test_size,
preset,
time_limit,
trials,
feature_selection_tool,
transform_tool,
ml_tool,
image_backbone,
image_classifier,
image_size,
image_device,
image_batch_size,
image_pretrained,
uploaded_image_backend,
cancer_preset,
)
yield from run_uploaded_remote(
payload, train_file, test_file, session_token, request
)
def _parallel_target_update(dataset_name: str):
metadata = _dataset_metadata(dataset_name)
targets = list(metadata.get("targets") or [])
return gr.update(choices=targets, value=targets[0] if targets else None)
def parallel_existing_ui_handler(
dataset,
target,
trials,
preset,
time_limit,
image_backend,
session_token,
request: gr.Request | None = None,
):
payload = _existing_payload(
dataset,
target or "",
False,
0.2,
preset,
time_limit,
trials,
AUTOMATIC_SELECTION,
AUTOMATIC_SELECTION,
AUTOMATIC_SELECTION,
AUTO_CHOICE,
AUTO_CHOICE,
AUTO_CHOICE,
AUTO_DEVICE,
64,
True,
"classification",
image_backend,
"auto",
1,
64,
"",
"Auto - agent decides",
)
yield from run_existing_remote(payload, session_token, request)
def _add_results_section():
with gr.Group(elem_classes=["results-shell"]):
gr.HTML(
"""
<div class="results-heading">
<h2>Training results</h2>
<p>The selected model and primary evaluation results appear first; technical details remain available below.</p>
</div>
"""
)
status = gr.Markdown("Ready to train.", elem_classes=["run-status"])
metrics = gr.Markdown(
"### Performance summary\n\n_Run training to view evaluation metrics and the selected model._",
elem_classes=["performance-summary"],
)
with gr.Row(equal_height=False):
with gr.Column(scale=3):
predictions = gr.DataFrame(
label="Prediction sample",
interactive=False,
elem_classes=["prediction-table"],
)
with gr.Column(scale=1, elem_classes=["artifact-panel"]):
gr.HTML(
'<p class="artifact-note">Download the complete fitted pipeline for governed reuse and independent validation.</p>'
)
package = gr.File(label="Exported model package", interactive=False)
with gr.Accordion(
"Dataset and run details",
open=False,
elem_classes=["detail-accordion"],
):
summary = gr.Markdown(
"_Run details will appear here._",
elem_classes=["detail-markdown"],
)
with gr.Accordion(
"Pipeline decisions",
open=False,
elem_classes=["detail-accordion"],
):
tools = gr.Markdown(
"_The selected pipeline will appear here._",
elem_classes=["detail-markdown"],
)
reasoning = gr.Markdown("", elem_classes=["detail-markdown"])
return status, metrics, predictions, summary, tools, reasoning, package
def create_interface() -> gr.Blocks:
"""Build the public frontend without importing or contacting ML code."""
routing_mode_from_env()
catalog = _catalog()["datasets"]
dataset_choices = list(catalog) or ["No datasets configured"]
default_dataset = "titanic" if "titanic" in catalog else dataset_choices[0]
metadata = dict(catalog.get(default_dataset) or {})
targets = list(metadata.get("targets") or [])
default_target = targets[0] if targets else None
initial_image = bool(metadata.get("image"))
initial_state = get_image_task_ui_state("classification", "Auto")
with gr.Blocks(title="AutoML Studio | Research Analytics") as demo:
session_token = gr.BrowserState(
"",
storage_key="automl-auth-session-v1",
secret=auth_storage.browser_state_secret(),
)
gr.HTML(APP_HEADER_HTML)
gr.HTML(RESEARCH_NOTICE_HTML)
with gr.Group(visible=True, elem_classes=["account-card"]) as auth_panel:
gr.Markdown("## Secure access")
auth_status = gr.Markdown(
"Sign in with an approved account or submit an account request."
)
with gr.Tabs():
with gr.TabItem("Sign in"):
login_username = gr.Textbox(label="Username")
login_password = gr.Textbox(label="Password", type="password")
login_button = gr.Button("Sign in", variant="primary")
with gr.TabItem(
"Request account",
visible=auth_storage.signups_allowed(),
):
signup_username = gr.Textbox(label="Username")
signup_password = gr.Textbox(label="Password", type="password")
signup_confirm_password = gr.Textbox(
label="Confirm Password",
type="password",
)
signup_button = gr.Button("Submit account request", variant="primary")
with gr.TabItem("Change password"):
password_username = gr.Textbox(label="Username")
old_password = gr.Textbox(label="Current Password", type="password")
new_password = gr.Textbox(label="New Password", type="password")
confirm_password = gr.Textbox(label="Confirm New Password", type="password")
password_button = gr.Button("Update password", variant="primary")
password_status = gr.Markdown("")
denied_username_state = gr.State("")
with gr.Group(visible=False) as denied_request_group:
gr.Markdown(
"### Denied account request\n"
"Re-enter the password used for signup, then choose whether to "
"submit the request for another review or permanently delete it."
)
denied_password = gr.Textbox(
label="Signup Password",
type="password",
)
denied_request_choice = gr.Radio(
choices=[
"Re-send request",
"Do not re-send; delete my account request",
],
label="What would you like to do?",
)
denied_request_button = gr.Button("Submit choice", variant="primary")
with gr.Row(visible=False, elem_classes=["account-strip"]) as account_row:
account_status = gr.Markdown("Account: _signed out_")
logout_button = gr.Button("Sign out", min_width=100)
with gr.Tabs(visible=False, elem_id="workspace-tabs") as main_tabs:
with gr.TabItem("Existing datasets"):
with gr.Row(equal_height=False):
with gr.Column(scale=3, elem_classes=["panel-card"]):
gr.HTML(
"""
<div class="configuration-heading">
<h2>Configure training</h2>
<p>Select the data, evaluation design, and compute budget for this run.</p>
</div>
"""
)
dataset = gr.Dropdown(dataset_choices, value=default_dataset, label="Dataset")
target = gr.Dropdown(targets, value=default_target, label="Outcome to predict", allow_custom_value=True)
split = gr.Checkbox(False, label="Create a test split from the training data", visible=not initial_image)
test_size = gr.Slider(0.1, 0.5, value=0.2, step=0.05, label="Validation holdout" if initial_image else "Test holdout")
preset = gr.Dropdown(QUALITY_PRESETS, value="medium_quality", label="Quality profile")
time_limit = gr.Slider(60, 3600, value=300, step=60, label="Total training time budget (seconds)")
trials = gr.Dropdown(["1", "2", "3", "4"], value="1", label="Candidate runs")
with gr.Accordion(
"Advanced tabular pipeline options",
open=False,
visible=not initial_image,
elem_classes=["advanced-options"],
) as tabular_group:
feature = gr.Dropdown(FEATURE_SELECTION_CHOICES, value=AUTOMATIC_SELECTION, label="Feature selection")
transform = gr.Dropdown(TRANSFORM_CHOICES, value=AUTOMATIC_SELECTION, label="Data transformation")
ml_tool = gr.Dropdown(ML_CHOICES, value=AUTOMATIC_SELECTION, label="Training engine")
with gr.Accordion(
"Advanced image pipeline options",
open=False,
visible=initial_image,
elem_classes=["advanced-options"],
) as image_group:
image_task = gr.Dropdown(IMAGE_TASK_CHOICES, value="classification", label="Image Task")
image_backend = gr.Dropdown(IMAGE_BACKEND_CHOICES, value="Auto", label="Image Backend")
image_format = gr.Dropdown(IMAGE_FORMAT_CHOICES, value="auto", label="Dataset Format")
gr.Textbox(value="Managed existing-dataset source", label="Dataset Source", interactive=False)
image_note = gr.Markdown(initial_state["note"])
image_device = gr.Dropdown(IMAGE_DEVICE_CHOICES, value=AUTO_DEVICE, label="Image Device")
image_batch = gr.Slider(1, 128, value=64, step=1, label="Image Batch Size")
with gr.Group(visible=initial_state["classification"]) as classification_group:
image_backbone = gr.Dropdown(IMAGE_BACKBONE_CHOICES, value=AUTO_CHOICE, label="Image Backbone")
image_classifier = gr.Dropdown(IMAGE_CLASSIFIER_CHOICES, value=AUTO_CHOICE, label="Image Classifier")
image_size = gr.Dropdown(IMAGE_SIZE_CHOICES, value=AUTO_CHOICE, label="Image Size")
image_pretrained = gr.Checkbox(True, label="Use Pretrained CNN Weights")
with gr.Group(visible=initial_state["medical"]) as medical_group:
cancer_preset = gr.Dropdown(CANCER_PRESET_CHOICES, value="Auto - agent decides", label="Cancer Feature Preset")
with gr.Group(visible=initial_state["detection"]) as detection_group:
gr.Markdown("### Detection Controls\nCOCO annotations use backend defaults.")
with gr.Group(visible=initial_state["instance"]) as instance_group:
gr.Markdown("### Instance Segmentation Controls\nCOCO polygons/RLE are preserved.")
with gr.Group(visible=initial_state["semantic"]) as semantic_group:
gr.Markdown("### Semantic Segmentation Controls\nUses a managed image/mask manifest.")
with gr.Group(visible=initial_state["optional"]) as optional_group:
image_epochs = gr.Slider(1, 100, value=1, step=1, label="Backend Epochs")
image_imgsz = gr.Slider(32, 1024, value=64, step=32, label="Backend Image Size")
with gr.Group(visible=initial_state["benchmark"]) as benchmark_group:
benchmark_backends = gr.Textbox("", label="Benchmark Backends", placeholder="yolo,automm")
existing_route = gr.Markdown(
existing_route_preview(
default_dataset,
AUTO_CHOICE,
AUTO_DEVICE,
"classification",
"Auto",
"",
"Auto - agent decides",
),
elem_classes=["route-summary"],
)
run_button = gr.Button(
"Run training",
variant="primary",
interactive=False,
elem_classes=["run-button"],
)
dataset.change(
update_existing_dataset_controls,
dataset,
[target, split, test_size, tabular_group, image_group],
api_name=False,
)
for selector in (image_task, image_backend):
selector.change(
image_task_ui_updates,
[image_task, image_backend],
[classification_group, medical_group, detection_group, instance_group, semantic_group, benchmark_group, optional_group, image_note],
api_name=False,
)
existing_route_inputs = [
dataset,
image_backbone,
image_device,
image_task,
image_backend,
benchmark_backends,
cancer_preset,
]
for selector in (
dataset,
image_backbone,
image_device,
image_task,
image_backend,
benchmark_backends,
cancer_preset,
):
selector.change(
existing_route_preview,
existing_route_inputs,
existing_route,
api_name=False,
)
with gr.Column(scale=1):
gr.HTML(EXISTING_DATA_GUIDE_HTML)
existing_outputs = _add_results_section()
with gr.TabItem("Upload data"):
with gr.Row(equal_height=False):
with gr.Column(scale=3, elem_classes=["panel-card"]):
gr.HTML(
"""
<div class="configuration-heading">
<h2>Upload and configure</h2>
<p>Provide a research-ready dataset, then define the outcome and evaluation design.</p>
</div>
"""
)
upload_type = gr.Dropdown(["Tabular CSV", "Image Dataset"], value="Tabular CSV", label="Data Type")
train_upload = gr.File(label="Training data (CSV)", file_types=[".csv"])
test_upload = gr.File(label="Test data (CSV, optional)", file_types=[".csv"])
upload_target = gr.Dropdown([], label="Outcome to predict", allow_custom_value=True)
upload_split = gr.Checkbox(True, label="Create a test split from the training data")
upload_test_size = gr.Slider(0.1, 0.5, value=0.2, step=0.05, label="Test holdout")
upload_preset = gr.Dropdown(QUALITY_PRESETS, value="medium_quality", label="Quality profile")
upload_time = gr.Slider(60, 3600, value=300, step=60, label="Total training time budget (seconds)")
upload_trials = gr.Dropdown(["1", "2", "3", "4"], value="1", label="Candidate runs")
with gr.Accordion(
"Advanced tabular pipeline options",
open=False,
visible=True,
elem_classes=["advanced-options"],
) as upload_tabular_group:
upload_feature = gr.Dropdown(FEATURE_SELECTION_CHOICES, value=AUTOMATIC_SELECTION, label="Feature selection")
upload_transform = gr.Dropdown(TRANSFORM_CHOICES, value=AUTOMATIC_SELECTION, label="Data transformation")
upload_ml = gr.Dropdown(ML_CHOICES, value=AUTOMATIC_SELECTION, label="Training engine")
with gr.Accordion(
"Advanced image pipeline options",
open=False,
visible=False,
elem_classes=["advanced-options"],
) as upload_image_group:
upload_image_backend = gr.Dropdown(["Existing classification pipeline", "Medical image agent"], value="Existing classification pipeline", label="Image Backend")
with gr.Group(visible=True) as upload_existing_group:
upload_backbone = gr.Dropdown(IMAGE_BACKBONE_CHOICES, value=AUTO_CHOICE, label="Image Backbone")
upload_classifier = gr.Dropdown(IMAGE_CLASSIFIER_CHOICES, value=AUTO_CHOICE, label="Image Classifier")
upload_size = gr.Dropdown(IMAGE_SIZE_CHOICES, value=AUTO_CHOICE, label="Image Size")
with gr.Group(visible=False) as upload_medical_group:
upload_cancer_preset = gr.Dropdown(CANCER_PRESET_CHOICES, value="Auto - agent decides", label="Cancer Feature Preset")
upload_device = gr.Dropdown(IMAGE_DEVICE_CHOICES, value=AUTO_DEVICE, label="Image Device")
upload_batch = gr.Slider(8, 128, value=64, step=8, label="Image Batch Size")
upload_pretrained = gr.Checkbox(True, label="Use Pretrained CNN Weights")
uploaded_route = gr.Markdown(
uploaded_route_preview(
"Tabular CSV",
AUTO_CHOICE,
AUTO_DEVICE,
"Existing classification pipeline",
"Auto - agent decides",
),
elem_classes=["route-summary"],
)
upload_run_button = gr.Button(
"Run training",
variant="primary",
interactive=False,
elem_classes=["run-button"],
)
upload_type.change(
update_uploaded_type_controls,
upload_type,
[train_upload, test_upload, upload_target, upload_split, upload_test_size, upload_tabular_group, upload_image_group],
api_name=False,
).then(update_uploaded_targets, [upload_type, train_upload], upload_target, api_name=False)
train_upload.change(update_uploaded_targets, [upload_type, train_upload], upload_target, api_name=False)
upload_image_backend.change(uploaded_image_backend_updates, upload_image_backend, [upload_existing_group, upload_medical_group], api_name=False)
uploaded_route_inputs = [
upload_type,
upload_backbone,
upload_device,
upload_image_backend,
upload_cancer_preset,
]
for selector in (
upload_type,
upload_backbone,
upload_device,
upload_image_backend,
upload_cancer_preset,
):
selector.change(
uploaded_route_preview,
uploaded_route_inputs,
uploaded_route,
api_name=False,
)
with gr.Column(scale=1):
gr.HTML(UPLOAD_DATA_GUIDE_HTML)
uploaded_outputs = _add_results_section()
with gr.TabItem("Parallel training"):
gr.HTML(
"""
<div class="configuration-heading">
<h2>Parallel training</h2>
<p>Launch two independent training jobs simultaneously from the same page. Click both buttons to run them at the same time.</p>
</div>
"""
)
with gr.Row(equal_height=False):
with gr.Column(scale=1):
with gr.Group(elem_classes=["panel-card"]):
gr.HTML("<h3 style='margin:0 0 12px'>Job 1</h3>")
p1_dataset = gr.Dropdown(choices=dataset_choices, value=default_dataset, label="Dataset")
p1_target = gr.Dropdown(choices=targets, value=default_target, label="Outcome to predict", allow_custom_value=True)
p1_trials = gr.Dropdown(["1", "2", "3", "4"], value="1", label="Candidate runs")
p1_preset = gr.Dropdown(QUALITY_PRESETS, value="medium_quality", label="Quality profile")
p1_time = gr.Slider(60, 3600, value=300, step=60, label="Time budget (seconds)")
p1_backend = gr.Dropdown(IMAGE_BACKEND_CHOICES, value="Auto", label="Image backend")
p1_btn = gr.Button("Train Job 1", variant="primary", elem_classes=["run-button"])
p1_outputs = _add_results_section()
with gr.Column(scale=1):
with gr.Group(elem_classes=["panel-card"]):
gr.HTML("<h3 style='margin:0 0 12px'>Job 2</h3>")
p2_dataset = gr.Dropdown(choices=dataset_choices, value=default_dataset, label="Dataset")
p2_target = gr.Dropdown(choices=targets, value=default_target, label="Outcome to predict", allow_custom_value=True)
p2_trials = gr.Dropdown(["1", "2", "3", "4"], value="1", label="Candidate runs")
p2_preset = gr.Dropdown(QUALITY_PRESETS, value="medium_quality", label="Quality profile")
p2_time = gr.Slider(60, 3600, value=300, step=60, label="Time budget (seconds)")
p2_backend = gr.Dropdown(IMAGE_BACKEND_CHOICES, value="Auto", label="Image backend")
p2_btn = gr.Button("Train Job 2", variant="primary", elem_classes=["run-button"])
p2_outputs = _add_results_section()
p1_dataset.change(_parallel_target_update, p1_dataset, p1_target, api_name=False)
p2_dataset.change(_parallel_target_update, p2_dataset, p2_target, api_name=False)
p1_btn.click(
parallel_existing_ui_handler,
[p1_dataset, p1_target, p1_trials, p1_preset, p1_time, p1_backend, session_token],
list(p1_outputs),
api_name=False,
concurrency_limit=2,
)
p2_btn.click(
parallel_existing_ui_handler,
[p2_dataset, p2_target, p2_trials, p2_preset, p2_time, p2_backend, session_token],
list(p2_outputs),
api_name=False,
concurrency_limit=2,
)
with gr.TabItem("Use a trained model") as replay_tab:
with gr.Row(equal_height=False):
with gr.Column(scale=2, elem_classes=["panel-card"]):
gr.HTML(
"""
<div class="configuration-heading">
<h2>Select a model</h2>
<p>Load a governed model package and provide one compatible input.</p>
</div>
"""
)
saved_models = gr.Dropdown([], label="Saved Cloud Model", interactive=False)
refresh_models = gr.Button("Refresh Saved Models", interactive=False)
model_upload = gr.File(label="Trained Model Package (.zip)", file_types=[".zip"])
model_info = gr.Markdown("Choose a saved model or upload a package.")
tabular_text = gr.Textbox("", visible=False)
with gr.Group(visible=False) as tabular_input_group:
tabular_input = gr.File(label="Single Tabular Input (CSV, one row)", file_types=[".csv"])
with gr.Group(visible=False) as image_input_group:
image_input = gr.File(
label="Single Image Input",
file_types=[".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"],
)
replay_device = gr.Dropdown(IMAGE_DEVICE_CHOICES, value=AUTO_DEVICE, label="Image Device", visible=False)
replay_batch = gr.Slider(1, 128, value=16, step=1, label="Image Batch Size", visible=False)
replay_manifest_state = gr.State({})
replay_route = gr.Markdown("Choose a model to inspect its compute route.")
predict_button = gr.Button("Run prediction", variant="primary", interactive=False)
with gr.Column(scale=3, elem_classes=["inference-output"]):
predict_status = gr.Markdown("Ready for a model.", elem_classes=["run-status"])
predict_summary = gr.Markdown("")
predict_frame = gr.DataFrame(label="Prediction", interactive=False)
with gr.Column(scale=1):
gr.HTML(INFERENCE_GUIDE_HTML)
with gr.TabItem("Account administration", visible=False) as admin_tab:
gr.Markdown(
"## Pending account requests\n"
"Approve a request to let that user log in, or deny it to let "
"the user choose whether to re-submit or remove their information."
)
pending_requests_df = gr.Dataframe(
headers=["Username", "Requested At (UTC)"],
datatype=["str", "str"],
value=[],
interactive=False,
label="Pending Requests",
)
pending_username = gr.Dropdown(
choices=[],
value=None,
label="Account Request",
)
with gr.Row():
approve_account_button = gr.Button("Approve", variant="primary")
deny_account_button = gr.Button("Deny", variant="stop")
refresh_accounts_button = gr.Button("Refresh")
admin_status = gr.Markdown("")
auth_outputs = [
auth_status,
session_token,
auth_panel,
account_row,
main_tabs,
account_status,
saved_models,
password_status,
run_button,
upload_run_button,
refresh_models,
predict_button,
model_info,
login_username,
login_password,
tabular_input_group,
image_input_group,
replay_device,
replay_batch,
replay_manifest_state,
replay_route,
predict_status,
predict_summary,
predict_frame,
denied_request_group,
denied_username_state,
denied_password,
denied_request_choice,
admin_tab,
pending_requests_df,
pending_username,
admin_status,
]
demo.load(
restore_auth_ui,
session_token,
auth_outputs,
api_name=False,
)
login_button.click(handle_login_ui, [login_username, login_password], auth_outputs, api_name=False)
signup_button.click(
handle_signup_ui,
[signup_username, signup_password, signup_confirm_password],
auth_outputs,
api_name=False,
)
denied_request_button.click(
handle_denied_request_ui,
[
denied_username_state,
denied_password,
denied_request_choice,
],
[
auth_status,
denied_request_group,
denied_username_state,
denied_password,
denied_request_choice,
],
api_name=False,
)
logout_button.click(handle_logout_ui, None, auth_outputs, api_name=False)
password_button.click(handle_password_change_ui, [password_username, old_password, new_password, confirm_password], password_status, api_name=False)
refresh_accounts_button.click(
refresh_pending_account_requests,
session_token,
[pending_requests_df, pending_username, admin_status],
api_name=False,
)
approve_account_button.click(
handle_admin_account_approval,
[session_token, pending_username],
[pending_requests_df, pending_username, admin_status],
api_name=False,
)
deny_account_button.click(
handle_admin_account_denial,
[session_token, pending_username],
[pending_requests_df, pending_username, admin_status],
api_name=False,
)
inspect_outputs = [model_info, tabular_input_group, image_input_group, replay_device, replay_batch, predict_button, replay_manifest_state, replay_route]
model_upload.change(update_single_input_controls, [model_upload, saved_models, session_token], inspect_outputs, api_name=False)
saved_models.change(update_single_input_controls, [model_upload, saved_models, session_token], inspect_outputs, api_name=False)
refresh_models.click(refresh_saved_model_choices, [saved_models, session_token], saved_models, api_name=False)
replay_tab.select(refresh_saved_model_choices, [saved_models, session_token], saved_models, api_name=False)
replay_device.change(
replay_route_preview,
[replay_manifest_state, replay_device],
replay_route,
api_name=False,
)
existing_inputs = [dataset, target, split, test_size, preset, time_limit, trials, feature, transform, ml_tool, image_backbone, image_classifier, image_size, image_device, image_batch, image_pretrained, image_task, image_backend, image_format, image_epochs, image_imgsz, benchmark_backends, cancer_preset, session_token]
run_button.click(existing_ui_handler, existing_inputs, list(existing_outputs), api_name=False)
uploaded_inputs = [upload_type, upload_target, upload_split, upload_test_size, upload_preset, upload_time, upload_trials, upload_feature, upload_transform, upload_ml, upload_backbone, upload_classifier, upload_size, upload_device, upload_batch, upload_pretrained, upload_image_backend, upload_cancer_preset, train_upload, test_upload, session_token]
upload_run_button.click(uploaded_ui_handler, uploaded_inputs, list(uploaded_outputs), api_name=False)
predict_button.click(predict_remote, [model_upload, tabular_text, tabular_input, image_input, replay_device, replay_batch, saved_models, session_token], [predict_status, predict_summary, predict_frame], api_name=False)
return demo
def validate_gateway_security_config() -> None:
"""Fail closed when the public deployment weakens its security boundary."""
routing_mode_from_env()
if auth_storage.env_truthy("AUTOML_AUTH_DISABLED", False):
raise RuntimeError("Public gateway does not permit AUTOML_AUTH_DISABLED=1.")
if not auth_storage.app_auth_required():
raise RuntimeError("Public gateway requires AUTOML_REQUIRE_AUTH=1.")
if not auth_storage.encryption_enabled():
raise RuntimeError(
"Public gateway requires AUTOML_MODEL_STORAGE_KEY for encrypted model storage."
)
if __name__ == "__main__":
validate_gateway_security_config()
create_interface().queue(default_concurrency_limit=4).launch(
server_name="0.0.0.0",
server_port=7860,
show_error=False,
theme=professional_theme(),
css=APP_CSS,
head=RESPONSIVE_HEAD_HTML,
)
__all__ = [
"GATEWAY_CATALOG_PATH",
"create_interface",
"run_existing_remote",
"run_uploaded_remote",
"predict_remote",
"render_training_result",
"prune_gateway_egress",
"routing_mode_from_env",
"format_route_preview",
"existing_route_preview",
"uploaded_route_preview",
"replay_route_preview",
"validate_gateway_security_config",
]
|