| """Unified ASGI entrypoint for API and Gradio UI.""" |
|
|
| from __future__ import annotations |
|
|
| import os |
|
|
| import gradio as gr |
| import uvicorn |
|
|
| from arena.api import app as fastapi_app |
| from arena.api import service |
| from arena.gradio_app import build_app |
|
|
|
|
| demo = build_app(service) |
|
|
|
|
| def create_app(): |
| """Create one FastAPI ASGI app with Gradio mounted at the root.""" |
|
|
| return gr.mount_gradio_app(fastapi_app, demo, path="/") |
|
|
|
|
| app = create_app() |
|
|
|
|
| try: |
| import spaces |
| except Exception: |
| class _SpacesShim: |
| def GPU(self, fn=None, **kwargs): |
| del kwargs |
|
|
| def decorator(inner): |
| return inner |
|
|
| return decorator(fn) if fn else decorator |
|
|
| spaces = _SpacesShim() |
|
|
|
|
| @spaces.GPU |
| def zerogpu_ready_marker() -> str: |
| return "ready" |
|
|
|
|
| def server_config() -> dict[str, int | str]: |
| host = os.getenv("GRADIO_SERVER_NAME", os.getenv("HOST", "0.0.0.0")) |
| port = int(os.getenv("GRADIO_SERVER_PORT") or os.getenv("PORT") or "7860") |
| return {"host": host, "port": port} |
|
|
|
|
| def gradio_launch_config() -> dict[str, bool | int | str]: |
| config = server_config() |
| port = int(os.getenv("GRADIO_SERVER_PORT", "7861")) if os.getenv("SPACE_ID") else int(config["port"]) |
| return {"server_name": str(config["host"]), "server_port": port, "ssr_mode": False} |
|
|
|
|
| def should_launch_gradio_space() -> bool: |
| return bool(os.getenv("SPACE_ID")) and os.getenv("FORCE_SELF_LAUNCH") != "1" |
|
|
|
|
| def should_self_launch() -> bool: |
| if os.getenv("FORCE_SELF_LAUNCH") == "1": |
| return True |
| return not should_launch_gradio_space() |
|
|
|
|
| def _space_sdk() -> str: |
| return os.getenv("SPACE_SDK", os.getenv("HF_SPACE_SDK", "")).strip().lower() |
|
|
|
|
| if __name__ == "__main__": |
| if should_launch_gradio_space(): |
| demo.launch(**gradio_launch_config()) |
| elif should_self_launch(): |
| uvicorn.run(app, **server_config()) |
|
|