Spaces:
Sleeping
Sleeping
Launch via Gradio for ZeroGPU
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Hugging Face Spaces entry point (Gradio SDK on free ZeroGPU hardware).The Space runs `python app.py` and expects a web server on port 7860. We serve KhmerSense's ownFastAPI app (API + prebuilt React UI in frontend/dist) with uvicorn. On ZeroGPU, the model isplaced on 'cuda' at startup and inference runs inside a @spaces.GPU function, which borrows a GPUfor a few seconds per request. Locally (no `spaces` package) everything runs on CPU."""import osimport sysfrom pathlib import PathROOT = Path(__file__).resolve().parentsys.path.insert(0, str(ROOT / "backend"))os.environ.setdefault("SENTIMENT_BACKEND", "hf")try: # must be imported before torch on ZeroGPUimport spacesexcept ImportError:spaces = Noneimport uvicorn # noqa: E402from app import sentiment # noqa: E402from app.main import app # noqa: E402ON_ZERO_GPU = spaces is not None and os.getenv("SPACES_ZERO_GPU", "").lower() in ("1", "true")if ON_ZERO_GPU and sentiment.get_analyzer().__class__.__name__ == "HFAnalyzer":analyzer = sentiment.get_analyzer()analyzer.to("cuda") # ZeroGPU: real GPU only inside @spaces.GPU calls_predict_on_gpu_device = analyzer.predict@spaces.GPU(duration=60)def gpu_predict(texts):return _predict_on_gpu_device(texts)analyzer.predict = gpu_predict# ZeroGPU registers its startup hook and per-request context through Gradio's mount helper.import gradio as grwith gr.Blocks(title="KhmerSense API") as _status:gr.Markdown("KhmerSense is running. Open the main page at `/`.")app = gr.mount_gradio_app(app, _status, path="/gradio")if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""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 infrontend/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 osimport sysfrom pathlib import PathROOT = Path(__file__).resolve().parentsys.path.insert(0, str(ROOT / "backend"))os.environ.setdefault("SENTIMENT_BACKEND", "hf")try: # must be imported before torch on ZeroGPUimport spacesexcept ImportError:spaces = Noneimport gradio as gr # noqa: E402from fastapi.responses import FileResponse # noqa: E402from fastapi.staticfiles import StaticFiles # noqa: E402from starlette.routing import Mount, Route # noqa: E402from app import config, sentiment # noqa: E402from app.main import app as khmersense # noqa: E402ON_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):analyzer = sentiment.get_analyzer()analyzer.to("cuda") # real GPU only inside @spaces.GPU calls_predict = analyzer.predict@spaces.GPU(duration=60)def gpu_predict(texts):return _predict(texts)analyzer.predict = gpu_predictdef 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_DISTasync 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 routeswith 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()})
app.py+70-47