Spaces:
Build error
Build error
update
Browse filesFiles changed (4)
58 unmodified lines59606162636431 unmodified lines9697989910010110210358 unmodified linesself,model_path: Optional[str] = None,encoder: str = "vitl16",):super().__init__()self.model_config = dinov3_model_configs[encoder]31 unmodified linesraise FileNotFoundError(f"Model file {model_path} not found")# only for inferenceif torch.cuda.is_available():self.cuda()self.eval()def _init_variant_modules(self):58 unmodified lines5960616263646531 unmodified lines97989910010110210310410510610710810958 unmodified linesself,model_path: Optional[str] = None,encoder: str = "vitl16",device: Optional[str | torch.device] = None,):super().__init__()self.model_config = dinov3_model_configs[encoder]31 unmodified linesraise FileNotFoundError(f"Model file {model_path} not found")# only for inferencetarget_device = Noneif device is not None:target_device = torch.device(device)elif torch.cuda.is_available():target_device = torch.device("cuda")if target_device is not None:self.to(target_device)self.eval()def _init_variant_modules(self):
18 unmodified lines192021222324103 unmodified lines12812913013113213335 unmodified lines169170171172173174175176177178179180181182183184185186212 unmodified lines399400401402403404405145 unmodified lines55155255355455555655755818 unmodified linesfrom .io_utils import depth2pcd, depth_to_disparityfrom .logger import Logfrom .model_utils import build_modelfrom .sampling_utils import make_2d_uniform_coordfrom .vis_utils import clip_outliers_by_percentile, colorize_depth_maps103 unmodified linesresolve_moge2_pretrained()def _report_stage(stage_callback: Optional[Callable[[str], None]], stage: str) -> None:if stage_callback is not None:stage_callback(stage)35 unmodified linesdef __init__(self):self._cache: dict[tuple[str, str], Any] = {}def get(self, model_type: str, model_path: str):key = (model_type, model_path)if key not in self._cache:Log.info(f"Loading model: model_type={model_type}, checkpoint={model_path}")self._cache[key] = build_model(model_type=model_type,model_path=model_path,)else:Log.info(f"Using cached model: model_type={model_type}, checkpoint={model_path}")return self._cache[key]def _parse_image_size(size_text: str) -> tuple[int, int]:try:212 unmodified linesckpt_path = resolve_checkpoint_path(model_type)_report_stage(stage_callback, f"demo:checkpoint_resolved path={ckpt_path}")model_cache = model_cache or ModelCache()model = model_cache.get(model_type=model_type, model_path=ckpt_path)_report_stage(stage_callback, "demo:model_loaded")query_2d_uniform_coord = make_2d_uniform_coord((h_out, w_out)).unsqueeze(0).to(device)145 unmodified linesprompt_mask = prompt > 0ckpt_path = resolve_checkpoint_path(model_type)model_cache = model_cache or ModelCache()model = model_cache.get(model_type=model_type, model_path=ckpt_path)if _debug:torch.cuda.synchronize()Log.info(f"[GPU-DEBUG] model_loaded: GPU mem allocated={torch.cuda.memory_allocated(device) / 1e6:.1f}MB")18 unmodified lines19202122232425103 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015135 unmodified lines187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229212 unmodified lines442443444445446447448145 unmodified lines59459559659759859960060160218 unmodified linesfrom .io_utils import depth2pcd, depth_to_disparityfrom .logger import Logfrom .model_utils import build_modelfrom .moge_utils import preload_moge2_modelfrom .sampling_utils import make_2d_uniform_coordfrom .vis_utils import clip_outliers_by_percentile, colorize_depth_maps103 unmodified linesresolve_moge2_pretrained()def preload_space_runtime_models(model_cache: "ModelCache",default_model_type: str = "InfiniDepth",) -> None:if not SPACE_RUNTIME:returnLog.info(f"Preloading default ZeroGPU runtime models on CPU: default_model_type={default_model_type}")model_cache.preload(model_type=default_model_type,model_path=resolve_checkpoint_path(default_model_type),)preload_moge2_model(resolve_moge2_pretrained())def _report_stage(stage_callback: Optional[Callable[[str], None]], stage: str) -> None:if stage_callback is not None:stage_callback(stage)35 unmodified linesdef __init__(self):self._cache: dict[tuple[str, str], Any] = {}@staticmethoddef _get_model_device(model: Any) -> torch.device:try:return next(model.parameters()).deviceexcept StopIteration:return torch.device("cpu")def get(self, model_type: str, model_path: str, device: Optional[torch.device | str] = None):key = (model_type, model_path)if key not in self._cache:load_device = torch.device(device) if device is not None else torch.device("cpu")Log.info(f"Loading model: model_type={model_type}, checkpoint={model_path}, device={load_device}")self._cache[key] = build_model(model_type=model_type,model_path=model_path,device=load_device,)else:Log.info(f"Using cached model: model_type={model_type}, checkpoint={model_path}")if device is not None:target_device = torch.device(device)current_device = self._get_model_device(self._cache[key])if current_device != target_device:Log.info(f"Moving cached model to device: model_type={model_type}, "f"checkpoint={model_path}, {current_device} -> {target_device}")self._cache[key] = self._cache[key].to(target_device)self._cache[key].eval()return self._cache[key]def preload(self, model_type: str, model_path: str) -> None:self.get(model_type=model_type, model_path=model_path, device=torch.device("cpu"))def _parse_image_size(size_text: str) -> tuple[int, int]:try:212 unmodified linesckpt_path = resolve_checkpoint_path(model_type)_report_stage(stage_callback, f"demo:checkpoint_resolved path={ckpt_path}")model_cache = model_cache or ModelCache()model = model_cache.get(model_type=model_type, model_path=ckpt_path, device=device)_report_stage(stage_callback, "demo:model_loaded")query_2d_uniform_coord = make_2d_uniform_coord((h_out, w_out)).unsqueeze(0).to(device)145 unmodified linesprompt_mask = prompt > 0ckpt_path = resolve_checkpoint_path(model_type)_report_stage(stage_callback, "gpu:loading_model")model_cache = model_cache or ModelCache()model = model_cache.get(model_type=model_type, model_path=ckpt_path, device=device)if _debug:torch.cuda.synchronize()Log.info(f"[GPU-DEBUG] model_loaded: GPU mem allocated={torch.cuda.memory_allocated(device) / 1e6:.1f}MB")
3 unmodified lines45678910111213141516171819202122232425262728293031323 unmodified linesimport torch_MOGE2_MODEL_CACHE: dict[tuple[str, str], torch.nn.Module] = {}def _get_moge2_model(pretrained_model_name_or_path: str, device: torch.device) -> torch.nn.Module:cache_key = (pretrained_model_name_or_path, str(device))if cache_key in _MOGE2_MODEL_CACHE:return _MOGE2_MODEL_CACHE[cache_key]try:from moge.model.v2 import MoGeModelexcept ImportError as exc:raise ImportError("MoGe is not installed. Please install it first: ""`pip install git+https://github.com/microsoft/MoGe.git`") from excmodel = MoGeModel.from_pretrained(pretrained_model_name_or_path).to(device)model.eval()_MOGE2_MODEL_CACHE[cache_key] = modelreturn modeldef _squeeze_hw(tensor: torch.Tensor, name: str) -> torch.Tensor:if tensor.ndim == 2:return tensor3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950513 unmodified linesimport torchfrom .logger import Log_MOGE2_MODEL_CACHE: dict[str, torch.nn.Module] = {}def _get_model_device(model: torch.nn.Module) -> torch.device:try:return next(model.parameters()).deviceexcept StopIteration:return torch.device("cpu")def _get_moge2_model(pretrained_model_name_or_path: str, device: torch.device) -> torch.nn.Module:model = _MOGE2_MODEL_CACHE.get(pretrained_model_name_or_path)if model is None:try:from moge.model.v2 import MoGeModelexcept ImportError as exc:raise ImportError("MoGe is not installed. Please install it first: ""`pip install git+https://github.com/microsoft/MoGe.git`") from excLog.info(f"Loading MoGe-2 model from {pretrained_model_name_or_path} on CPU")model = MoGeModel.from_pretrained(pretrained_model_name_or_path)model.eval()_MOGE2_MODEL_CACHE[pretrained_model_name_or_path] = modelcurrent_device = _get_model_device(model)target_device = torch.device(device)if current_device != target_device:Log.info(f"Moving MoGe-2 model to device: {current_device} -> {target_device}")model = model.to(target_device)model.eval()_MOGE2_MODEL_CACHE[pretrained_model_name_or_path] = modelreturn modeldef preload_moge2_model(pretrained_model_name_or_path: str) -> None:_get_moge2_model(pretrained_model_name_or_path, torch.device("cpu"))def _squeeze_hw(tensor: torch.Tensor, name: str) -> torch.Tensor:if tensor.ndim == 2:return tensor
12345616 unmodified lines232425262728293 unmodified lines333435363738168 unmodified lines207208209210211212213182 unmodified lines39639739839940040125 unmodified lines42742842943043143243327 unmodified lines46146246346446546646754 unmodified lines5225235245255265275281 unmodified line530531532533534535536import osimport shutilimport tempfileimport tracebackimport uuidfrom pathlib import Path16 unmodified linesimport numpy as npfrom PIL import Imagefrom InfiniDepth.utils.hf_demo_utils import ModelCache, prepare_runtime_assets, run_gpu_inference, postprocess_gpu_resultfrom InfiniDepth.utils.logger import Logtry:3 unmodified linesMODEL_CACHE = ModelCache()OUTPUT_ROOT = Path(tempfile.gettempdir()) / "infinidepth_hf_demo"TRACE_ROOT = OUTPUT_ROOT / "trace"EXAMPLE_DATA_ROOT = Path(__file__).resolve().parent / "example_data"168 unmodified linestrace_file = Path(trace_path)trace_file.parent.mkdir(parents=True, exist_ok=True)with trace_file.open("a", encoding="utf-8") as handle:handle.write(f"{stage}\n")handle.flush()182 unmodified linesif os.getenv("INFINIDEPTH_SHOW_TRACEBACK", "0") == "1":error_message = f"{error_message}\n\n{error_trace}"# Always log full traceback to server logs (visible in HF Space Logs tab)Log.error(f"[{request_id}] Full traceback:\n{error_trace}")return None, None, [], error_message25 unmodified lines)input_size = gr.Dropdown(choices=["512x672", "768x1024"],value="768x1024",label="Inference Resolution (HxW)",)output_resolution_mode = gr.Dropdown(27 unmodified linesgr.Markdown("Tips: when a depth map is uploaded it will be used automatically, otherwise the demo falls back to MoGe-2. ""If camera intrinsics are missing, the demo first tries MoGe-2 estimates before image-size defaults. ""Use lower preview points for faster 3D interaction.")with gr.Column(elem_id="right-panel"):54 unmodified linesif __name__ == "__main__":prepare_runtime_assets()server_name = "0.0.0.0" if os.getenv("SPACE_ID") else "127.0.0.1"# Hugging Face Spaces with Gradio typically expects port 7860.# Respect explicit Gradio/PORT env overrides when provided.server_port = int(os.getenv("GRADIO_SERVER_PORT", os.getenv("PORT", "7860")))1 unmodified line"server_name": server_name,"server_port": server_port,}if os.getenv("SPACE_ID"):launch_kwargs["ssr_mode"] = Falseif os.getenv("INFINIDEPTH_SHOW_ERROR", "0") == "1":launch_kwargs["show_error"] = True123456716 unmodified lines242526272829303132333435363 unmodified lines4041424344454647168 unmodified lines216217218219220221222182 unmodified lines40540640740840941041141225 unmodified lines43843944044144244344427 unmodified lines47247347447547647747847954 unmodified lines5345355365375385395405415421 unmodified line544545546547548549550import osimport shutilimport tempfileimport timeimport tracebackimport uuidfrom pathlib import Path16 unmodified linesimport numpy as npfrom PIL import Imagefrom InfiniDepth.utils.hf_demo_utils import (ModelCache,postprocess_gpu_result,prepare_runtime_assets,preload_space_runtime_models,run_gpu_inference,)from InfiniDepth.utils.logger import Logtry:3 unmodified linesMODEL_CACHE = ModelCache()SPACE_RUNTIME = bool(os.getenv("SPACE_ID"))DEFAULT_INPUT_SIZE = "512x672" if SPACE_RUNTIME else "768x1024"OUTPUT_ROOT = Path(tempfile.gettempdir()) / "infinidepth_hf_demo"TRACE_ROOT = OUTPUT_ROOT / "trace"EXAMPLE_DATA_ROOT = Path(__file__).resolve().parent / "example_data"168 unmodified linestrace_file = Path(trace_path)trace_file.parent.mkdir(parents=True, exist_ok=True)with trace_file.open("a", encoding="utf-8") as handle:handle.write(f"{time.strftime('%H:%M:%S')} {stage}\n")handle.flush()182 unmodified linesif os.getenv("INFINIDEPTH_SHOW_TRACEBACK", "0") == "1":error_message = f"{error_message}\n\n{error_trace}"# Always log full traceback to server logs (visible in HF Space Logs tab)Log.error(f"[{request_id}] trace_path={trace_path}")Log.error(f"[{request_id}] Last worker stages:\n{trace_summary or '<none>'}")Log.error(f"[{request_id}] Full traceback:\n{error_trace}")return None, None, [], error_message25 unmodified lines)input_size = gr.Dropdown(choices=["512x672", "768x1024"],value=DEFAULT_INPUT_SIZE,label="Inference Resolution (HxW)",)output_resolution_mode = gr.Dropdown(27 unmodified linesgr.Markdown("Tips: when a depth map is uploaded it will be used automatically, otherwise the demo falls back to MoGe-2. ""If camera intrinsics are missing, the demo first tries MoGe-2 estimates before image-size defaults. ""Use lower preview points for faster 3D interaction. ""On ZeroGPU, `512x672` is the safest default for cold starts.")with gr.Column(elem_id="right-panel"):54 unmodified linesif __name__ == "__main__":prepare_runtime_assets()if os.getenv("INFINIDEPTH_PRELOAD_DEFAULT_MODELS", "1" if SPACE_RUNTIME else "0") == "1":preload_space_runtime_models(model_cache=MODEL_CACHE, default_model_type="InfiniDepth")server_name = "0.0.0.0" if SPACE_RUNTIME else "127.0.0.1"# Hugging Face Spaces with Gradio typically expects port 7860.# Respect explicit Gradio/PORT env overrides when provided.server_port = int(os.getenv("GRADIO_SERVER_PORT", os.getenv("PORT", "7860")))1 unmodified line"server_name": server_name,"server_port": server_port,}if SPACE_RUNTIME:launch_kwargs["ssr_mode"] = Falseif os.getenv("INFINIDEPTH_SHOW_ERROR", "0") == "1":launch_kwargs["show_error"] = True
InfiniDepth/model/model.py+8-2
InfiniDepth/utils/hf_demo_utils.py+48-4
InfiniDepth/utils/moge_utils.py+35-16
app.py+20-6