"""Hugging Face Space (ZeroGPU) entry of the ViDiHand2 demo. It runs demo_gradio/app.py of the release unchanged, except that the GPU work (ViDiHand2 and the Depth Anything 3 camera estimate) runs inside @spaces.GPU calls, the overlays render on the CPU, and the inputs are capped for the shared GPU.""" import spaces # first: ZeroGPU patches torch's CUDA before anything initialises it import importlib.util from concurrent.futures import ThreadPoolExecutor from contextvars import copy_context from pathlib import Path ROOT = Path(__file__).resolve().parent MAX_FRAMES, MAX_SIDE = 900, 1920 # input limits on the Space: frames, pixels on the long side import torch torch.cuda.reset_peak_memory_stats = lambda *args, **kwargs: None # GPU memory statistics exist only inside the GPU calls torch.cuda.max_memory_reserved = lambda *args, **kwargs: 0 import utils.visualizer from utils.io import checkpoint class CpuMano(utils.visualizer.ManoModel): """The visualizer's MANO model, on the CPU: the overlays render outside the GPU calls.""" def __init__(self, device=None): super().__init__(device="cpu") utils.visualizer.ManoModel = CpuMano spec = importlib.util.spec_from_file_location("demo_app", ROOT / "demo_gradio" / "app.py") demo = importlib.util.module_from_spec(spec) spec.loader.exec_module(demo) class ContextExecutor(ThreadPoolExecutor): """A thread pool whose tasks run in the submitting thread's context, where ZeroGPU finds the user's request.""" def submit(self, fn, /, *args, **kwargs): return super().submit(copy_context().run, fn, *args, **kwargs) for name in ("vidihand_v2/vdm.safetensors", "vidihand_v2/projector.safetensors", "mano/MANO_RIGHT.pkl"): checkpoint(name) # fetched now, not inside the first GPU call model, da3_camera = None, demo.estimate_camera demo.load_estimator() @spaces.GPU(duration=lambda sample, **kwargs: 40 + 0.04 * len(sample["video"])) def reconstruct(sample, **kwargs): """ViDiHand2 on a sample. The model is built inside the GPU worker on its first call and kept there: its constructor precomputes tables on the GPU, which ZeroGPU does not allow outside a GPU call.""" global model if model is None: model = demo.load_model() return model(sample, **kwargs) @spaces.GPU(duration=60) def estimate_camera(frames, fps): """The Depth Anything 3 camera of a video.""" return da3_camera(frames, fps) demo.ThreadPoolExecutor = ContextExecutor demo.model, demo.estimate_camera, demo.visualizer = reconstruct, estimate_camera, demo.Visualizer(backend="cpu") demo.MAX_FRAMES, demo.MAX_SIDE = MAX_FRAMES, MAX_SIDE if __name__ == "__main__": demo.expire() demo.show_time_left() demo.build().queue(default_concurrency_limit=1).launch(show_error=True, allowed_paths=[str(demo.OUTPUTS), str(ROOT / "datasets" / "sample")])