Spaces:
Running on Zero
Running on Zero
DASH Gaming commited on
Commit ·
038b0be
1
Parent(s): 9ac1e0d
fix: register @spaces.GPU on Gradio predict handler and launch with demo.queue().launch
Browse files19 unmodified lines2021222324252627282979 unmodified lines1091101111121131141151161171181191201211221231241251261271281291303 unmodified lines13413513613713813925 unmodified lines16516616716816917017117291 unmodified lines26426526626726826927027127227327427527627727827928028128228328428528628728828929029129214 unmodified lines30730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138219 unmodified linesimport torchfrom PIL import Image, ImageOpsimport gradio as grfrom fastapi import FastAPI, UploadFile, File, Formfrom fastapi.responses import JSONResponsefrom fastapi.middleware.cors import CORSMiddlewareimport uvicorn# ==============================================================================# 1. ENVIRONMENT & MODEL INITIALIZATION79 unmodified lines# ==============================================================================# 2. INFERENCE ENGINE (ZERO-GPU COMPATIBLE)# ==============================================================================@spaces.GPUdef run_model_forward(tensor: torch.Tensor) -> np.ndarray:"""Executes forward pass on GPU worker and transfers heatmaps back."""global GLOBAL_MODELif GLOBAL_MODEL is None:GLOBAL_MODEL = init_global_model()device = next(GLOBAL_MODEL.parameters()).devicetensor = tensor.to(device)with torch.inference_mode():heatmaps = GLOBAL_MODEL(tensor).squeeze(0).cpu().numpy()return heatmapsdef predict_keypoints_core(pil_img: Image.Image, debug: bool = False) -> dict:"""Core landmark prediction engine:3 unmodified lines4. Sub-pixel heatmap peak refinement5. Inverting coordinate transform directly to ORIGINAL image coordinates"""t_start = time.perf_counter()if pil_img is None:25 unmodified linesresized = cv2.resize(img_np, (288, 384)).astype(np.float32) / 255.0tensor = torch.from_numpy(resized.transpose(2, 0, 1)).unsqueeze(0)# 4. Model forward passheatmaps = run_model_forward(tensor)_, hm_h, hm_w = heatmaps.shape# 5. Decode keypoints with sub-pixel refinement91 unmodified lines# ==============================================================================# 3. GRADIO USER INTERFACE & API# ==============================================================================def gradio_predict(image, debug: bool = False):"""Gradio handler matching exact JSON response shape."""return parse_and_predict(image, debug=debug)def gradio_ui_handler(image, debug: bool = False):"""Handler for the interactive Gradio testing UI."""res = parse_and_predict(image, debug=True)annotated_img = Noneif res.get("ok") and "debug_image" in res:# Decode base64 preview for UI displayb64_str = res["debug_image"].split(",")[-1]img_bytes = base64.b64decode(b64_str)annotated_img = Image.open(io.BytesIO(img_bytes))# Return pure response (without bulky debug_image if not requested)clean_res = dict(res)if not debug and "debug_image" in clean_res:del clean_res["debug_image"]return clean_res, annotated_imgwith gr.Blocks(title="HRNet Garment Keypoint Backend") as demo:14 unmodified linesoutput_json = gr.JSON(label="JSON Response")output_debug_preview = gr.Image(label="Visual Keypoints Preview", type="pil")# Interactive UI button clickpredict_btn.click(fn=gradio_ui_handler,inputs=[input_image, debug_checkbox],outputs=[output_json, output_debug_preview],)# Dedicated programmatic API endpoint: api_name="predict"api_trigger = gr.Button("API Trigger", visible=False)api_trigger.click(fn=gradio_predict,inputs=[input_image, debug_checkbox],outputs=[output_json],api_name="predict")# ==============================================================================# 4. FASTAPI DIRECT ENDPOINT WITH CORS# ==============================================================================app = FastAPI(title="HRNet Garment Keypoint Backend")# Add CORS middleware to app (allow all origins for WebXR frontend; restrict to your domain later)app.add_middleware(CORSMiddleware,allow_origins=["*"], # NOTE: Replace with your specific frontend domain in productionallow_credentials=True,allow_methods=["*"],allow_headers=["*"],)@app.post("/predict")async def post_predict(image: UploadFile = File(None),file: UploadFile = File(None),debug: bool = Form(False)):"""Standard HTTP POST endpoint for WebXR frontend:Accepts multipart/form-data with 'image' (or 'file') and optional 'debug' boolean.Returns 2D keypoints in original pixel coordinates."""target = image if image is not None else fileif target is None:return JSONResponse(status_code=400,content={"ok": False, "error": "No file uploaded. Provide 'image' or 'file' in form-data."})try:file_bytes = await target.read()pil_img = Image.open(io.BytesIO(file_bytes))result = predict_keypoints_core(pil_img, debug=debug)status_code = 200 if result.get("ok") else 400return JSONResponse(content=result, status_code=status_code)except Exception as e:return JSONResponse(status_code=400,content={"ok": False, "error": f"Failed to process image: {str(e)}"})# Mount Gradio UI at root /app = gr.mount_gradio_app(app, demo, path="/")# ==============================================================================# 5. LAUNCH SERVER# ==============================================================================if __name__ == "__main__":print("[HRNet Backend] Starting server on 0.0.0.0:7860...", flush=True)uvicorn.run(app, host="0.0.0.0", port=7860)19 unmodified lines202122232425262779 unmodified lines1071081091101111121131143 unmodified lines11811912012112212312425 unmodified lines15015115215315415515615715815916016116216316491 unmodified lines25625725825926026126226326426526626726826927027127227327427527627727827928028114 unmodified lines29629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936019 unmodified linesimport torchfrom PIL import Image, ImageOpsimport gradio as grfrom fastapi import UploadFile, File, Formfrom fastapi.responses import JSONResponse# ==============================================================================# 1. ENVIRONMENT & MODEL INITIALIZATION79 unmodified lines# ==============================================================================# 2. INFERENCE ENGINE# ==============================================================================def predict_keypoints_core(pil_img: Image.Image, debug: bool = False) -> dict:"""Core landmark prediction engine:3 unmodified lines4. Sub-pixel heatmap peak refinement5. Inverting coordinate transform directly to ORIGINAL image coordinates"""global GLOBAL_MODELt_start = time.perf_counter()if pil_img is None:25 unmodified linesresized = cv2.resize(img_np, (288, 384)).astype(np.float32) / 255.0tensor = torch.from_numpy(resized.transpose(2, 0, 1)).unsqueeze(0)# 4. Model forward pass on deviceif GLOBAL_MODEL is None:GLOBAL_MODEL = init_global_model()model_device = next(GLOBAL_MODEL.parameters()).devicetensor = tensor.to(model_device)with torch.inference_mode():heatmaps = GLOBAL_MODEL(tensor).squeeze(0).cpu().numpy()_, hm_h, hm_w = heatmaps.shape# 5. Decode keypoints with sub-pixel refinement91 unmodified lines# ==============================================================================# 3. GRADIO USER INTERFACE & API (DECORATED WITH @spaces.GPU FOR ZEROGPU)# ==============================================================================@spaces.GPUdef predict(image, debug: bool = False):"""Primary API & UI entrypoint.Decorated with @spaces.GPU so Hugging Face ZeroGPU allocates GPU dynamically.Returns: (dict_response, annotated_preview_image)"""res = parse_and_predict(image, debug=debug)annotated_img = Noneif res.get("ok") and "debug_image" in res:try:b64_str = res["debug_image"].split(",")[-1]img_bytes = base64.b64decode(b64_str)annotated_img = Image.open(io.BytesIO(img_bytes))except Exception:passreturn res, annotated_imgwith gr.Blocks(title="HRNet Garment Keypoint Backend") as demo:14 unmodified linesoutput_json = gr.JSON(label="JSON Response")output_debug_preview = gr.Image(label="Visual Keypoints Preview", type="pil")# Hook up Gradio event with api_name="predict"predict_btn.click(fn=predict,inputs=[input_image, debug_checkbox],outputs=[output_json, output_debug_preview],api_name="predict")# ==============================================================================# 4. SERVER LAUNCHER (GRADIO NATIVE LAUNCH + FASTAPI ROUTE & CORS)# ==============================================================================def start_app():print("[HRNet Backend] Launching Gradio queue on 0.0.0.0:7860...", flush=True)# 1. Launch Gradio using official Spaces launch method (CORS enabled by default)demo.queue().launch(server_name="0.0.0.0",server_port=7860,share=False,prevent_thread_lock=True)# 2. Add direct POST /predict endpoint to demo.app@demo.app.post("/predict")async def post_predict(image: UploadFile = File(None),file: UploadFile = File(None),debug: bool = Form(False)):"""Direct HTTP POST endpoint for WebXR frontend:Accepts multipart/form-data with 'image' (or 'file') and optional 'debug' boolean.Returns 2D keypoints in original pixel coordinates."""target = image if image is not None else fileif target is None:return JSONResponse(status_code=400,content={"ok": False, "error": "No file uploaded. Provide 'image' or 'file' in form-data."})try:file_bytes = await target.read()pil_img = Image.open(io.BytesIO(file_bytes))result = predict_keypoints_core(pil_img, debug=debug)status_code = 200 if result.get("ok") else 400return JSONResponse(content=result, status_code=status_code)except Exception as e:return JSONResponse(status_code=400,content={"ok": False, "error": f"Failed to process image: {str(e)}"})print("[HRNet Backend] POST /predict and Gradio endpoints ready at http://0.0.0.0:7860", flush=True)# 3. Keep main thread activedemo.block_thread()if __name__ == "__main__":start_app()
app.py+75-97