Spaces:
Running
Running
Download app.py from joshruby/rig-live-relay: direct link, hf CLI and curl.
- Browser
- Download file 3.05 kB
-
https://huggingface.co/spaces/joshruby/rig-live-relay/resolve/main/app.py
- Command line
-
hf download hf://spaces/joshruby/rig-live-relay/app.py
-
curl -L -o app.py https://huggingface.co/spaces/joshruby/rig-live-relay/resolve/main/app.py
3.05 kB
| """Live HLS relay for the field rig — runs as a free Hugging Face Space. | |
| The rig's hls_uploader.py PUTs each new 2 s segment and then the playlist; the | |
| public site's player GETs them from here. Everything lives in RAM: the last | |
| KEEP segments (about 48 s) and the current playlist. Nothing is written to disk | |
| or to any storage service, so the stream costs nothing to host and leaves | |
| nothing behind. | |
| Env (Space secret): RELAY_TOKEN — the shared secret the uploader sends. | |
| Clean-room: original code. | |
| """ | |
| import os | |
| import re | |
| import time | |
| from collections import OrderedDict | |
| from fastapi import FastAPI, HTTPException, Request, Response | |
| TOKEN = os.environ["RELAY_TOKEN"] | |
| KEEP = 24 # segments held: the 6-segment window plus ~36 s for late players | |
| STALE_S = 15.0 # no playlist for this long → the stream is down (404) | |
| MAX_SEGMENT_BYTES = 16 * 1024 * 1024 | |
| MAX_PLAYLIST_BYTES = 64 * 1024 | |
| SEGMENT_NAME = re.compile(r"^[A-Za-z0-9_-]{1,80}\.ts$") | |
| CORS = {"Access-Control-Allow-Origin": "*"} | |
| app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) | |
| segments: "OrderedDict[str, bytes]" = OrderedDict() | |
| playlist: dict[str, object] = {"body": None, "beat": 0.0} | |
| def _check_token(req: Request) -> None: | |
| if req.headers.get("authorization") != f"Bearer {TOKEN}": | |
| raise HTTPException(status_code=401) | |
| def _live() -> bool: | |
| return playlist["body"] is not None and time.monotonic() - float(playlist["beat"]) < STALE_S | |
| def status() -> dict: | |
| return {"service": "rig live HLS relay", "live": _live(), "segments": len(segments)} | |
| async def put_segment(name: str, req: Request) -> dict: | |
| _check_token(req) | |
| if not SEGMENT_NAME.match(name): | |
| raise HTTPException(status_code=400, detail="bad segment name") | |
| body = await req.body() | |
| if not body or len(body) > MAX_SEGMENT_BYTES: | |
| raise HTTPException(status_code=413) | |
| segments[name] = body | |
| segments.move_to_end(name) | |
| while len(segments) > KEEP: | |
| segments.popitem(last=False) | |
| return {"ok": True} | |
| def get_segment(name: str) -> Response: | |
| body = segments.get(name) | |
| if body is None: | |
| return Response(status_code=404, headers=CORS) | |
| # Names are unique per run, so a segment never changes once written. | |
| return Response(body, media_type="video/mp2t", headers={**CORS, "Cache-Control": "public, max-age=60"}) | |
| async def put_playlist(req: Request) -> dict: | |
| _check_token(req) | |
| body = await req.body() | |
| if len(body) > MAX_PLAYLIST_BYTES or not body.startswith(b"#EXTM3U"): | |
| raise HTTPException(status_code=400, detail="not an HLS playlist") | |
| playlist["body"] = body | |
| playlist["beat"] = time.monotonic() | |
| return {"ok": True} | |
| def get_playlist() -> Response: | |
| headers = {**CORS, "Cache-Control": "no-store"} | |
| if not _live(): | |
| return Response(status_code=404, headers=headers) | |
| return Response(playlist["body"], media_type="application/vnd.apple.mpegurl", headers=headers) | |