"""Hugging Face Spaces entry point (Gradio SDK, free ZeroGPU hardware). ZeroGPU only supports apps started with Gradio's own `launch()`. So we launch a tiny Gradio app, then put KhmerSense's FastAPI routes (the /api endpoints and the prebuilt React UI in frontend/dist) in front of Gradio's routes on the same server. Model inference runs inside a @spaces.GPU function, which borrows a GPU for a few seconds per request. Locally (no ZeroGPU) the same file works on CPU: `python app.py` -> http://127.0.0.1:7860 """ import os import sys from pathlib import Path ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT / "backend")) os.environ.setdefault("SENTIMENT_BACKEND", "hf") if os.getenv("SPACES_ZERO_GPU", "").lower() in ("1", "true"): os.environ.setdefault("PROGRESS_CHUNK", "1000") # each chunk borrows the GPU once try: # must be imported before torch on ZeroGPU import spaces except ImportError: spaces = None import gradio as gr # noqa: E402 from fastapi.responses import FileResponse # noqa: E402 from fastapi.staticfiles import StaticFiles # noqa: E402 from starlette.routing import Mount, Route # noqa: E402 from app import config, sentiment # noqa: E402 from app.main import app as khmersense # noqa: E402 ON_ZERO_GPU = spaces is not None and os.getenv("SPACES_ZERO_GPU", "").lower() in ("1", "true") if ON_ZERO_GPU and isinstance(sentiment.get_analyzer(), sentiment.HFAnalyzer): import logging analyzer = sentiment.get_analyzer() analyzer.load() # model stays on CPU in the main process cpu_predict = analyzer.predict @spaces.GPU(duration=60) def gpu_predict(texts): analyzer.to("cuda") # runs in ZeroGPU's GPU worker return cpu_predict(texts) def predict(texts): """GPU when the visitor has ZeroGPU quota left; otherwise the same model on CPU.""" try: return gpu_predict(texts) except Exception as exc: # noqa: BLE001 if type(exc).__module__.startswith("spaces") or "ZeroGPU" in str(exc) or "GPU" in type(exc).__name__: logging.getLogger("khmersense").warning("ZeroGPU unavailable (%s) - using CPU", str(exc)[:120]) return cpu_predict(texts) raise analyzer.predict = predict def khmersense_routes(): """KhmerSense's API routes plus explicit UI routes (no catch-all, so Gradio's own routes still work).""" routes = [r for r in khmersense.router.routes if getattr(r, "path", "").startswith("/api/")] dist = config.FRONTEND_DIST async def index(_request): return FileResponse(dist / "index.html") async def favicon(_request): return FileResponse(dist / "favicon.svg") routes += [ Route("/", index), Route("/favicon.svg", favicon), Mount("/assets", app=StaticFiles(directory=dist / "assets"), name="ks-assets"), ] return routes with gr.Blocks(title="KhmerSense") as demo: gr.Markdown("KhmerSense is running. Open the main page at `/`.") if __name__ == "__main__": # Routes passed to the FastAPI constructor come before Gradio's own routes, so ours win. demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")), ssr_mode=False, show_error=True, app_kwargs={"routes": khmersense_routes()})