anttiluode commited on
Commit
16f2c5c
·
1 Parent(s): 5481594

Fix ZeroGPU startup by launching through Gradio

Browse files

Serve game routes through launch app_kwargs while preserving the Gradio API and disabling SSR. Add HTTP regression coverage for the startup hook, game assets, narration stream, and image response.

Files changed (3) hide show
  1. README.md +20 -1
  2. app.py +15 -14
  3. tests/test_startup.py +111 -0
README.md CHANGED
@@ -46,7 +46,7 @@ The AI settings in the game still offer the player's own Ollama, an OpenAI-compa
46
  ## How it fits together
47
 
48
  ```
49
- app.py FastAPI: serves game/ at /, the Space's config at /space-config,
50
  and a Gradio API at the root (/gradio_api) with two endpoints:
51
  narrate(sheet_json, prev_json, seed) -> streamed text
52
  paint(prompt, seed) -> JPEG data URL
@@ -67,6 +67,25 @@ The page asks `space-config` when it loads. If the answer comes, the page offers
67
 
68
  To run it locally: `pip install -r requirements.txt gradio==6.32.0`, then `python app.py`, then open http://localhost:7860. `LIFE2_MOCK=1 python app.py` uses stand-in models with no downloads.
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  ## Honest notes
71
 
72
  - **Tested here:** the whole path in mock mode, end to end in a headless browser. That covers the page finding the Space, streamed narration, pictures, the test buttons, two generations, the endpoints refusing a foreign prompt and a malformed fact sheet, and the vocabulary check on 1,110 real prompts. **Not tested here:** the real models. This machine has no GPU and can't download from Hugging Face. The model code is the standard transformers and diffusers path, but expect to fix small things on the first real start.
 
46
  ## How it fits together
47
 
48
  ```
49
+ app.py Gradio launch: serves game/ at /, the Space's config at /space-config,
50
  and a Gradio API at the root (/gradio_api) with two endpoints:
51
  narrate(sheet_json, prev_json, seed) -> streamed text
52
  paint(prompt, seed) -> JPEG data URL
 
67
 
68
  To run it locally: `pip install -r requirements.txt gradio==6.32.0`, then `python app.py`, then open http://localhost:7860. `LIFE2_MOCK=1 python app.py` uses stand-in models with no downloads.
69
 
70
+ ### Startup regression checks
71
+
72
+ The server uses `api.launch()` so the `spaces` package's ZeroGPU startup hooks run.
73
+ The game routes are passed through `app_kwargs` ahead of Gradio's own routes;
74
+ SSR is explicitly disabled. Keep this launch path when changing the server.
75
+ A separate `uvicorn.run()` can bypass ZeroGPU registration on some package versions.
76
+
77
+ Run the lightweight checks without downloading model weights:
78
+
79
+ ```bash
80
+ pip install gradio==6.32.0 pillow pytest
81
+ python -m pytest -q
82
+ ```
83
+
84
+ These checks start the real Gradio server with stand-in models, observe the server
85
+ startup hook, and exercise the game files, configuration, streamed narration and
86
+ JPEG response over HTTP. They do not verify GPU allocation or real-model inference;
87
+ those still require a successful run on the deployed Space.
88
+
89
  ## Honest notes
90
 
91
  - **Tested here:** the whole path in mock mode, end to end in a headless browser. That covers the page finding the Space, streamed narration, pictures, the test buttons, two generations, the endpoints refusing a foreign prompt and a malformed fact sheet, and the vocabulary check on 1,110 real prompts. **Not tested here:** the real models. This machine has no GPU and can't download from Hugging Face. The model code is the standard transformers and diffusers path, but expect to fix small things on the first real start.
app.py CHANGED
@@ -37,7 +37,7 @@ from collections.abc import Iterator
37
  from pathlib import Path
38
 
39
  import gradio as gr
40
- from fastapi import FastAPI
41
  from fastapi.responses import FileResponse, JSONResponse
42
 
43
  HERE = Path(__file__).parent
@@ -202,10 +202,10 @@ with gr.Blocks(title="Life² API") as api:
202
  gr.api(paint, api_name="paint", concurrency_limit=1)
203
  api.queue(max_size=64)
204
 
205
- app = FastAPI()
206
 
207
 
208
- @app.get("/space-config")
209
  def space_config():
210
  """The page asks this first; if it answers, the page offers the Space's own narrator and painter."""
211
  where = "ZeroGPU" if ZERO else DEVICE
@@ -213,22 +213,23 @@ def space_config():
213
  "api": "gradio", "slow": DEVICE == "cpu"})
214
 
215
 
216
- # The game's files are served by plain routes registered BEFORE Gradio is mounted at the root, so they
217
- # win over Gradio's own page. Gradio sits at "/" (not under a sub-path) because Hugging Face's ZeroGPU
218
- # looks for the @spaces.GPU functions through the Space's root Gradio app; mounted under /gradio it
219
- # reported "No @spaces.GPU function detected during startup".
220
  def _serve(path: Path):
221
  return lambda: FileResponse(path)
222
 
223
 
224
  for _f in GAME.iterdir():
225
  if _f.is_file():
226
- app.add_api_route("/" if _f.name == "index.html" else "/" + _f.name, _serve(_f), methods=["GET"], include_in_schema=False)
227
-
228
- # ssr_mode=False: Hugging Face sets GRADIO_SSR_MODE=true, which would start Gradio's Node server on
229
- # port 7860 itself, and then this server could not bind there ("address already in use").
230
- app = gr.mount_gradio_app(app, api, path="/", ssr_mode=False)
231
 
232
  if __name__ == "__main__":
233
- import uvicorn
234
- uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("GRADIO_SERVER_PORT") or os.environ.get("PORT") or 7860))
 
 
 
 
 
 
 
 
37
  from pathlib import Path
38
 
39
  import gradio as gr
40
+ from fastapi import APIRouter
41
  from fastapi.responses import FileResponse, JSONResponse
42
 
43
  HERE = Path(__file__).parent
 
202
  gr.api(paint, api_name="paint", concurrency_limit=1)
203
  api.queue(max_size=64)
204
 
205
+ game_routes = APIRouter()
206
 
207
 
208
+ @game_routes.get("/space-config")
209
  def space_config():
210
  """The page asks this first; if it answers, the page offers the Space's own narrator and painter."""
211
  where = "ZeroGPU" if ZERO else DEVICE
 
213
  "api": "gradio", "slow": DEVICE == "cpu"})
214
 
215
 
216
+ # Pass the game's routes into Gradio's FastAPI app at construction time, before
217
+ # Gradio registers its own root page. Its config, queue and API routes stay intact.
 
 
218
  def _serve(path: Path):
219
  return lambda: FileResponse(path)
220
 
221
 
222
  for _f in GAME.iterdir():
223
  if _f.is_file():
224
+ game_routes.add_api_route("/" if _f.name == "index.html" else "/" + _f.name, _serve(_f), methods=["GET"], include_in_schema=False)
 
 
 
 
225
 
226
  if __name__ == "__main__":
227
+ # Use Gradio's launch lifecycle so spaces can send its ZeroGPU startup report.
228
+ # A standalone uvicorn.run() bypasses the launch/start_server hooks used by
229
+ # some spaces versions, even when @spaces.GPU functions are registered.
230
+ api.launch(
231
+ server_name="0.0.0.0",
232
+ server_port=int(os.environ.get("GRADIO_SERVER_PORT") or 7860),
233
+ ssr_mode=False,
234
+ app_kwargs={"routes": game_routes.routes},
235
+ )
tests/test_startup.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exercise the real web server without downloading models or allocating a GPU."""
2
+ import base64
3
+ import io
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ import time
11
+
12
+ import httpx
13
+ from PIL import Image
14
+ import pytest
15
+
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+
19
+
20
+ @pytest.fixture(scope="module")
21
+ def server(tmp_path_factory):
22
+ # Observe the same Gradio server-start boundary used by ZeroGPU. Keep the
23
+ # real launch/server implementation; only the expensive models are mocked.
24
+ bootstrap = """
25
+ import runpy
26
+ from gradio import http_server
27
+ original = http_server.start_server
28
+ def observed_start(*args, **kwargs):
29
+ print('GRADIO_SERVER_START_HOOK', flush=True)
30
+ return original(*args, **kwargs)
31
+ http_server.start_server = observed_start
32
+ runpy.run_path('app.py', run_name='__main__')
33
+ """
34
+ with socket.socket() as sock:
35
+ sock.bind(("127.0.0.1", 0))
36
+ port = sock.getsockname()[1]
37
+ env = dict(os.environ, LIFE2_MOCK="1", GRADIO_SERVER_PORT=str(port),
38
+ GRADIO_SSR_MODE="true", GRADIO_ANALYTICS_ENABLED="false")
39
+ env.pop("SPACES_ZERO_GPU", None)
40
+ log_path = tmp_path_factory.mktemp("server") / "startup.log"
41
+ with log_path.open("w") as log:
42
+ process = subprocess.Popen([sys.executable, "-u", "-c", bootstrap],
43
+ cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT)
44
+ try:
45
+ with httpx.Client(base_url=f"http://127.0.0.1:{port}", timeout=15,
46
+ trust_env=False) as client:
47
+ deadline = time.monotonic() + 30
48
+ while time.monotonic() < deadline:
49
+ if process.poll() is not None:
50
+ pytest.fail(log_path.read_text())
51
+ try:
52
+ if client.get("/space-config").status_code == 200:
53
+ break
54
+ except httpx.TransportError:
55
+ pass
56
+ time.sleep(0.1)
57
+ else:
58
+ pytest.fail("Server did not start:\n" + log_path.read_text())
59
+ yield client, log_path
60
+ finally:
61
+ process.terminate()
62
+ try:
63
+ process.wait(timeout=10)
64
+ except subprocess.TimeoutExpired:
65
+ process.kill()
66
+ process.wait()
67
+
68
+
69
+ def test_startup_reaches_gradio_server_hook(server):
70
+ _, log_path = server
71
+ assert "GRADIO_SERVER_START_HOOK" in log_path.read_text(), (
72
+ "Startup bypassed Gradio's server hook used by ZeroGPU registration"
73
+ )
74
+
75
+
76
+ def test_game_routes_and_gradio_config_coexist(server):
77
+ client, _ = server
78
+ assert client.get("/").content == (ROOT / "game/index.html").read_bytes()
79
+ for name in ("ai.js", "app.js", "engine.js", "history.js", "style.css"):
80
+ assert client.get("/" + name).content == (ROOT / "game" / name).read_bytes()
81
+ assert client.get("/space-config").json()["space"] is True
82
+ config = client.get("/config").json()
83
+ assert {"narrate", "paint"} <= {d["api_name"] for d in config["dependencies"]}
84
+
85
+
86
+ def call(client, name, data):
87
+ response = client.post(f"/gradio_api/call/{name}", json={"data": data})
88
+ response.raise_for_status()
89
+ event_id = response.json()["event_id"]
90
+ result = client.get(f"/gradio_api/call/{name}/{event_id}")
91
+ result.raise_for_status()
92
+ return result.text
93
+
94
+
95
+ def test_narration_streams_through_game_api(server):
96
+ client, _ = server
97
+ stream = call(client, "narrate", [json.dumps({"year": 1901}), "[]", 1])
98
+ assert "event: generating" in stream
99
+ assert "event: complete" in stream
100
+ assert "The stove ticks as it cools." in stream
101
+
102
+
103
+ def test_painter_returns_image_through_game_api(server):
104
+ client, _ = server
105
+ stream = call(client, "paint", ["a family in a small house", 1])
106
+ assert "event: complete" in stream, stream
107
+ payload = stream.split("event: complete\n", 1)[1].split("data: ", 1)[1].split("\n", 1)[0]
108
+ data_url = json.loads(payload)[0]
109
+ assert data_url.startswith("data:image/jpeg;base64,")
110
+ img = Image.open(io.BytesIO(base64.b64decode(data_url.split(",", 1)[1])))
111
+ assert img.size == (576, 384)