Spaces:
Paused
Paused
File size: 2,837 Bytes
34771dc | 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 | """Hugging Face Space entry point: the whole Preprocessing Lab (app + API) at one URL.
Free accounts can only run Python Spaces on ZeroGPU hardware, which needs the Gradio SDK and at least one
@spaces.GPU function. The lab itself runs on CPU (both models are fast enough), so the one GPU function below is a
no-op that is never called: visitors never spend any GPU quota.
deploy_space.py uploads this file next to backend/server.py, the notebook, the data, the weights, and the built
frontend (static/), so the Space runs exactly the code in this repository.
"""
import spaces # must be imported before torch
import os
import subprocess
import sys
import threading
from pathlib import Path
HERE = Path(__file__).resolve().parent
os.environ.setdefault("TORCH_HOME", str(HERE / "weights" / "torch"))
os.environ.setdefault("YOLO_CONFIG_DIR", "/tmp/Ultralytics") # the home folder is read-only on Spaces
# Images and weights are uploaded with the Space; download them only if they are missing.
if not (HERE / "data" / "manifest.json").exists():
subprocess.run([sys.executable, "scripts/fetch_data.py"], cwd=HERE, check=True)
if not (HERE / "weights" / "yolo11s-seg.pt").exists():
subprocess.run([sys.executable, "scripts/fetch_models.py"], cwd=HERE, check=True)
os.environ["YOLO_OFFLINE"] = "1"
import server # noqa: E402 (runs image_lab.ipynb)
from fastapi.middleware.cors import CORSMiddleware # noqa: E402
from fastapi.middleware.gzip import GZipMiddleware # noqa: E402
from fastapi.responses import FileResponse # noqa: E402
from gradio import Server # noqa: E402
from starlette.staticfiles import StaticFiles # noqa: E402
app = Server(title="Preprocessing Lab")
app.add_middleware(CORSMiddleware, allow_origins=[o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "*").split(",")],
allow_methods=["GET", "POST"], allow_headers=["*"])
app.add_middleware(GZipMiddleware, minimum_size=1024) # the app bundle and JSON shrink about 3x
app.include_router(server.app.router) # every /api/... route from server.py
app.add_exception_handler(Exception, server.crash)
STATIC = HERE / "static"
if STATIC.exists(): # the built frontend: the page students open
app.mount("/assets", StaticFiles(directory=STATIC / "assets"), name="assets")
@app.get("/", include_in_schema=False)
def index():
return FileResponse(STATIC / "index.html")
threading.Thread(target=server.warm_up, daemon=True).start()
spaces.GPU(lambda: None) # ZeroGPU needs one GPU function; the lab runs on CPU and never calls it
if __name__ == "__main__":
# No server-side rendering: its Node proxy sat in front of every request and made downloads ~15x slower.
app.launch(server_name="0.0.0.0", server_port=7860, show_error=True, ssr_mode=False)
|