Files
microduck/spaces/hello/app.py
T
Pierre Rouanet 4e3506b8d4 vision-demo receives the frames instead of pulling them, and six findings about Spaces
The Space is the other half of `media.stream`: FastAPI owns the server, the robot
dials `wss://…/frames`, `av` decodes the access units and OpenCV runs over each
picture — **on Hugging Face hardware**, which was the point of the whole exercise.
The browser only ever receives the processed frame as an image.

Its WebRTC consumer is gone, and with it `aiortc`, the DTLS cipher shim over one
of their private methods, and the ICE stack that could never complete from a data
centre. What is left is `gradio`, `fastapi`, `opencv`, `requests` and `av` — a
decoder rather than a transport.

Frames are filed per account: the endpoint is public, so the robot presents its
own token and this resolves it through `whoami-v2`, exactly as the rendezvous
does. Without that anybody could push frames into the demo and, worse, a visitor
could be shown a stranger's camera.

`fake_duck.py` is the robot's whole side in Python — registers as a producer,
answers `rpc` envelopes, pushes H.264 from the webcam — which is what makes a
deployed Space testable with no board. Verified from a phone on 4G: duck at home,
Space in a data centre, viewer on mobile data, no network in common.

**Six things about Docker Spaces that each cost a round trip**, written down
because none is guessable and every one presented as something else:

- **`SYSTEM=spaces` is what Gradio checks**, not `SPACE_ID`. `get_space()` is
  `os.getenv("SYSTEM") == "spaces"`, Hugging Face sets it for gradio-SDK Spaces
  and not for Docker ones, so Gradio installs its *mocked* OAuth routes and the
  mock raises without a local `hf auth login`. The module then fails at import.
- **`git` must be installed.** Their builder appends `git config --global` to
  every Docker Space; a `-slim` base dies with exit 127 *after* the image built
  fine, reported as a page of cache-miss noise naming one of their own steps.
- **The user must be `user` at `/home/user`.** Their appended layers assume it.
- **`gradio[oauth]`, not `gradio`** — the extra is what carries `itsdangerous`
  and `authlib`, and without them a Space with `hf_oauth: true` fails at import.
- **A crash reports one truncated line, and reading a Space's logs needs write
  access to it.** So `boot.py` imports the app in a `try` and *serves the
  traceback* on the expected port when it cannot; `/env` reports which platform
  variables arrived. Those two are what ended four rounds of blaming the port for
  an import error.
- **Safari drops the OAuth session cookie** as third-party, because a Space runs
  in an iframe. The token box is therefore always offered, and the Space's own
  `.hf.space` URL works too.

`spaces/hello` is the baseline that proved the platform rather than the app:
Docker, FastAPI, one WebSocket route, Gradio mounted, no OAuth. Publish it into a
Space that will not start and it says which of the four is at fault.

One efficiency fix that was mistaken for a Safari bug: the timer polled ten times
a second for a five-frame-a-second stream and re-shipped four hundred log lines
every second, so half the responses re-encoded a picture the page already had.
`render` returns `gr.skip()` when the frame has not changed — 19 of 20 idle polls
now send nothing.

Assisted-by: Claude:claude-opus-5[1m]
2026-09-08 18:21:09 +02:00

77 lines
2.4 KiB
Python

"""The smallest thing that is still the shape of the real Space.
FastAPI owns the server, one WebSocket route of our own, Gradio mounted at `/`. **No OAuth**,
because that is where the real app died: a `gr.LoginButton` makes Gradio call `attach_oauth` while
the Blocks is built, which mocks when `SPACE_ID` is absent, and the mock raises without a local
`hf auth login`. A container has none.
"""
import os
import gradio as gr
from fastapi import FastAPI, WebSocket
app = FastAPI()
print(
"environment: SPACE_ID=%s SPACE_HOST=%s OAUTH_CLIENT_ID=%s"
% (
os.environ.get("SPACE_ID") or "absent",
os.environ.get("SPACE_HOST") or "absent",
"set" if os.environ.get("OAUTH_CLIENT_ID") else "absent",
),
flush=True,
)
@app.get("/env")
def env() -> dict:
"""Which of the platform's variables actually arrived.
An endpoint rather than a log line, because reading a Space's logs needs write access to the
Space and every question about them has cost a round trip through somebody pasting one. This
reports presence, never a value — `OAUTH_CLIENT_SECRET` is in this environment too.
"""
watched = (
"SPACE_ID",
"SPACE_HOST",
"SPACE_AUTHOR_NAME",
"OAUTH_CLIENT_ID",
"OAUTH_SCOPES",
"OPENID_PROVIDER_URL",
"HF_TOKEN",
"GRADIO_SSR_MODE",
"PORT",
)
return {
name: (os.environ[name] if name in ("SPACE_ID", "SPACE_HOST", "GRADIO_SSR_MODE", "PORT")
else "set")
if name in os.environ
else "absent"
for name in watched
}
@app.websocket("/frames")
async def frames(socket: WebSocket) -> None:
"""A route of our own, which is the whole reason this is Docker and not the gradio SDK."""
await socket.accept()
await socket.send_text("hello from /frames")
await socket.close()
with gr.Blocks(title="hello duck") as demo:
gr.Markdown(
"""
# hello duck
A Docker Space where FastAPI owns the server and Gradio is mounted at `/`.
`wss://<this space>/frames` is a WebSocket route of our own — it answers with one line
and hangs up.
"""
)
gr.Textbox(value="it runs", label="status", interactive=False)
# `ssr_mode=False`: server-side rendering starts a Node server and this image has no Node.
app = gr.mount_gradio_app(app, demo, path="/", ssr_mode=False)