Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/lingbot-map-v2-streaming: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/spaces/hugging-apps/lingbot-map-v2-streaming/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/lingbot-map-v2-streaming/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/lingbot-map-v2-streaming/resolve/main/app.py
18.5 kB
| import os | |
| os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| import spaces # must come before torch | |
| import json | |
| import math | |
| import re | |
| import shutil | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| import cv2 | |
| import gradio as gr | |
| import imageio.v2 as iio | |
| import matplotlib | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| import trimesh | |
| from huggingface_hub import hf_hub_download | |
| import lingbot_map2.aggregator.stream as stream_mod | |
| from lingbot_map2.layers.flashinfer_cache import PagedKVCache | |
| from lingbot_map2.models.gcr_base import NativeModel | |
| from lingbot_map2.models.gcr_stream import GCRStream | |
| from lingbot_map2.utils.checkpoint import CheckpointConfig | |
| from lingbot_map2.utils.load_fn import uniform_keyframe_ids | |
| from lingbot_map2.vis.glb_export import ( | |
| _extract_c2w_and_w2c, | |
| _unproject_depth_to_world, | |
| apply_scene_alignment, | |
| integrate_camera_into_scene, | |
| ) | |
| from lingbot_map2.utils.load_fn import load_images | |
| from onnx2torch import convert as onnx_to_torch | |
| MODEL_ID = "robbyant/lingbot-map-v2-base-streaming" | |
| MAX_FRAMES_HARD = 320 | |
| MAX_POINTS = 1_500_000 | |
| MAX_FRUSTUMS = 120 | |
| # --------------------------------------------------------------------------- | |
| # Paged KV cache: the reference implementation uses FlashInfer's paged FA2 | |
| # prefill kernel (JIT-compiled). This drop-in keeps the exact same page | |
| # bookkeeping and replaces only the attention call with PyTorch SDPA over the | |
| # gathered pages (non-causal, default 1/sqrt(d) scale) — mathematically the | |
| # same attention, without needing a CUDA toolchain at runtime. | |
| # --------------------------------------------------------------------------- | |
| class TorchPagedKVCache(PagedKVCache): | |
| def __init__(self, *, layers, heads, dim, patches, special=5, scale=8, | |
| window=64, capacity=1024, device="cuda", dtype=torch.bfloat16, | |
| offload_kv=False): | |
| self.layers, self.heads, self.dim = layers, heads, dim | |
| self.patches, self.special, self.scale, self.window = ( | |
| patches, special, scale, window) | |
| self.capacity = capacity | |
| self.device = torch.device(device) | |
| self.dtype = dtype | |
| self.offload_kv = False | |
| self.patch_pages = min(scale + window, capacity) + 1 | |
| self.special_pages = math.ceil((capacity + 1) * special / patches) | |
| layer_shape = (self.patch_pages + self.special_pages, 2, patches, heads, dim) | |
| self.cpu_pool = None | |
| self.gpu_buf = None | |
| self.pool = [torch.empty(layer_shape, device=device, dtype=dtype) | |
| for _ in range(layers)] | |
| import collections | |
| self.active = collections.deque() | |
| self.free = list(range(self.patch_pages - 1, -1, -1)) | |
| self.count = 0 | |
| self.pending = None | |
| self._index = None | |
| self._length = 0 | |
| def begin(self): | |
| if self.pending is not None: | |
| raise RuntimeError("nested append") | |
| if self.count >= self.capacity: | |
| raise ValueError("keyframe capacity reached") | |
| page = self.free[-1] | |
| active = list(self.active) + [(self.count, page)] | |
| active = [ | |
| (i, p) for i, p in active | |
| if i < self.scale or i >= max(self.scale, self.count + 1 - self.window) | |
| ] | |
| tokens = (self.count + 1) * self.special | |
| special_pages = math.ceil(tokens / self.patches) | |
| pages = [p for _, p in active] + list( | |
| range(self.patch_pages, self.patch_pages + special_pages)) | |
| last_len = tokens % self.patches or self.patches | |
| self.pending = {"page": page, "active": active, "written": set()} | |
| self._index = torch.tensor(pages, dtype=torch.long, device=self.device) | |
| self._length = (len(pages) - 1) * self.patches + last_len | |
| def run(self, layer, q): | |
| if layer not in self.pending["written"]: | |
| raise RuntimeError("query before write") | |
| kv = self.pool[layer].index_select(0, self._index) # [P, 2, patches, H, D] | |
| k = kv[:, 0].reshape(-1, self.heads, self.dim)[: self._length] | |
| v = kv[:, 1].reshape(-1, self.heads, self.dim)[: self._length] | |
| out = F.scaled_dot_product_attention( | |
| q.transpose(0, 1)[None], k.transpose(0, 1)[None], v.transpose(0, 1)[None]) | |
| return out[0].transpose(0, 1).contiguous() | |
| stream_mod.PagedKVCache = TorchPagedKVCache | |
| # --------------------------------------------------------------------------- | |
| # Model loading (module scope, eager .to("cuda")) | |
| # --------------------------------------------------------------------------- | |
| config_path = hf_hub_download(MODEL_ID, "config.json") | |
| weights_path = hf_hub_download(MODEL_ID, "model_weights.pt") | |
| SPEC = CheckpointConfig.read(config_path) | |
| SKYSEG_PATH = hf_hub_download("JianyuanWang/skyseg", "skyseg.onnx") | |
| native = NativeModel(SPEC.spatial_rope, max_frames=SPEC.max_frames) | |
| _state = torch.load(weights_path, map_location="cpu", mmap=True, weights_only=True) | |
| _state = _state.get("model", _state) | |
| native.load_state_dict(_state, strict=True) | |
| del _state | |
| native.eval().to("cuda") | |
| MODEL = GCRStream(native, SPEC, {"compile": False}) # eager: torch.compile is unsupported on ZeroGPU | |
| # Sky segmentation (same ONNX model as the reference --mask-sky), converted to torch so | |
| # it runs on the GPU inside the same ZeroGPU call instead of on the shared CPUs. | |
| SKY_NET = onnx_to_torch(SKYSEG_PATH).eval().to("cuda") | |
| SKY_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32) | |
| SKY_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32) | |
| print(f"Loaded {SPEC.name}: {SPEC.width}x{SPEC.height}, prefix={SPEC.scale_frames}, " | |
| f"window={SPEC.sliding_window}") | |
| # --------------------------------------------------------------------------- | |
| # Input handling | |
| # --------------------------------------------------------------------------- | |
| def _natural_key(name): | |
| return [(1, int(p)) if p.isdigit() else (0, p.lower()) | |
| for p in re.split(r"(\d+)", os.path.basename(name))] | |
| def _frames_from_video(video_path, fps, out_dir): | |
| cap = cv2.VideoCapture(video_path) | |
| if not cap.isOpened(): | |
| raise gr.Error("Could not read the video.") | |
| src_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 | |
| step = max(1, int(round(src_fps / max(fps, 0.1)))) | |
| paths, i = [], 0 | |
| while True: | |
| ok, frame = cap.read() | |
| if not ok: | |
| break | |
| if i % step == 0: | |
| p = os.path.join(out_dir, f"{len(paths):06d}.png") | |
| cv2.imwrite(p, frame) | |
| paths.append(p) | |
| i += 1 | |
| cap.release() | |
| return paths | |
| def _gather_paths(video, images, fps, max_frames, out_dir): | |
| if images: | |
| files = [f if isinstance(f, str) else f.name for f in images] | |
| files = [f for f in files | |
| if Path(f).suffix.lower() in {".png", ".jpg", ".jpeg", ".webp", ".bmp"}] | |
| paths = sorted(files, key=_natural_key) | |
| source = "images" | |
| elif video: | |
| paths = _frames_from_video(video, fps, out_dir) | |
| source = "video" | |
| else: | |
| raise gr.Error("Upload a video or an ordered image sequence first.") | |
| total = len(paths) | |
| if total > max_frames: # uniform subsample, keep first/last | |
| idx = np.linspace(0, total - 1, int(max_frames)).round().astype(int) | |
| paths = [paths[i] for i in idx] | |
| if len(paths) <= SPEC.scale_frames: | |
| raise gr.Error(f"Need more than {SPEC.scale_frames} frames " | |
| f"(got {len(paths)}). Raise the sampling FPS or use a longer clip.") | |
| return paths, total, source | |
| # --------------------------------------------------------------------------- | |
| # GPU inference | |
| # --------------------------------------------------------------------------- | |
| def _gpu_duration(paths, *args, **kwargs): | |
| # Measured on ZeroGPU: ~0.10-0.125 s/frame (stream + sky mask, warm vs cold) + ~4 s overhead; +15%. | |
| return int(math.ceil(1.15 * (6 + 0.13 * len(paths)))) | |
| def _sky_non_sky_conf(images_u8, batch=32): | |
| """Reference skyseg preprocessing (cv2 linear resize to 320x320, ImageNet norm, | |
| per-image min-max), batched on GPU. Returns [N,H,W] non-sky confidence in [0,1].""" | |
| n, h, w = images_u8.shape[:3] | |
| out = np.empty((n, h, w), np.float32) | |
| for s0 in range(0, n, batch): | |
| chunk = images_u8[s0:s0 + batch] | |
| x = np.stack([cv2.resize(im, (320, 320)) for im in chunk]).astype(np.float32) | |
| x = ((x / 255.0 - SKY_MEAN) / SKY_STD).transpose(0, 3, 1, 2) | |
| y = SKY_NET(torch.from_numpy(np.ascontiguousarray(x)).to("cuda")) | |
| y = (y[0] if isinstance(y, (list, tuple)) else y)[:, 0].float().cpu().numpy() | |
| for j, r in enumerate(y): | |
| r = (r - r.min()) / max(r.max() - r.min(), 1e-8) * 255.0 | |
| r = cv2.resize(r.astype(np.uint8), (w, h), interpolation=cv2.INTER_LINEAR) | |
| out[s0 + j] = 1.0 - r.astype(np.float32) / 255.0 | |
| return out | |
| def run_stream(paths, mask_sky=True): | |
| """Causal streaming inference over an ordered list of image paths.""" | |
| torch.manual_seed(42) | |
| t0 = time.perf_counter() | |
| # Same preprocessing as stream.online(path): float32 AREA cover-resize, center crop, /255. | |
| images = load_images(paths, SPEC.width, SPEC.height)[0] # [N,3,H,W] | |
| keyframes = set(uniform_keyframe_ids(len(paths), prefix=SPEC.scale_frames)) | |
| preds = [] | |
| with MODEL.create_stream(output_device="cpu") as stream: | |
| for raw_id in range(len(paths)): | |
| p = stream.online(images[raw_id], persistent=raw_id in keyframes) | |
| if p is not None: | |
| preds.append(p) | |
| torch.cuda.synchronize() | |
| t_model = time.perf_counter() - t0 | |
| out = { | |
| k: np.concatenate([p[k] for p in preds], axis=0).astype(np.float32) | |
| for k in ("poses_c2w", "intrinsics", "depth", "depth_conf") | |
| } | |
| out["images"] = (images.permute(0, 2, 3, 1).numpy() * 255).round().astype(np.uint8) | |
| out["non_sky"] = _sky_non_sky_conf(out["images"]) if mask_sky else None | |
| out["t_model"] = t_model | |
| out["t_gpu"] = time.perf_counter() - t0 | |
| return out | |
| # --------------------------------------------------------------------------- | |
| # Post-processing (CPU) | |
| # --------------------------------------------------------------------------- | |
| def _build_glb(pred, conf_percentile, show_cam, out_path): | |
| c2w, w2c = _extract_c2w_and_w2c(pred) | |
| world = _unproject_depth_to_world(pred["depth"], c2w, pred["intrinsics"]) | |
| conf = pred["depth_conf"].copy() | |
| if pred.get("non_sky") is not None: # reference threshold: keep non-sky > 0.875 | |
| conf[pred["non_sky"] <= 0.875] = 0.0 | |
| pts = world.reshape(-1, 3) | |
| cols = pred["images"].reshape(-1, 3) | |
| c = conf.reshape(-1) | |
| valid = np.isfinite(pts).all(axis=1) & np.isfinite(c) & (c > 1e-5) | |
| thr = np.percentile(c[valid], conf_percentile) if conf_percentile > 0 and valid.any() else 0.0 | |
| keep = np.flatnonzero(valid & (c >= thr)) | |
| if keep.size > MAX_POINTS: | |
| rng = np.random.default_rng(0) | |
| keep = np.sort(rng.choice(keep, MAX_POINTS, replace=False)) | |
| pts, cols = pts[keep], cols[keep] | |
| if pts.size == 0: | |
| pts = np.zeros((1, 3), np.float32) | |
| cols = np.full((1, 3), 255, np.uint8) | |
| scale = 1.0 | |
| else: | |
| lo, hi = np.percentile(pts, 5, axis=0), np.percentile(pts, 95, axis=0) | |
| scale = max(float(np.linalg.norm(hi - lo)), 0.1) | |
| scene = trimesh.Scene() | |
| scene.add_geometry(trimesh.PointCloud(vertices=pts, colors=cols)) | |
| if show_cam: | |
| cmap = matplotlib.colormaps["gist_rainbow"] | |
| n = len(c2w) | |
| for i in np.unique(np.linspace(0, n - 1, min(n, MAX_FRUSTUMS)).round().astype(int)): | |
| color = tuple(int(255 * x) for x in cmap(i / max(n, 1))[:3]) | |
| integrate_camera_into_scene(scene, c2w[i], color, scale) | |
| scene = apply_scene_alignment(scene, w2c) | |
| scene.export(out_path) | |
| return int(len(pts)) | |
| def _depth_video(images, depth, out_path, fps=10): | |
| d = depth[..., 0] if depth.ndim == 4 else depth | |
| cmap = matplotlib.colormaps["turbo"] | |
| writer = iio.get_writer(out_path, fps=fps, codec="libx264", quality=7, | |
| macro_block_size=1, pixelformat="yuv420p") | |
| for img, dm in zip(images, d): | |
| inv = 1.0 / np.clip(dm, 1e-6, None) | |
| lo, hi = np.percentile(inv, 2), np.percentile(inv, 98) | |
| norm = np.clip((inv - lo) / max(hi - lo, 1e-8), 0, 1) | |
| col = (cmap(norm)[..., :3] * 255).astype(np.uint8) | |
| writer.append_data(np.concatenate([img, col], axis=1)) | |
| writer.close() | |
| def reconstruct( | |
| video: str | None, | |
| images: list | None = None, | |
| fps: float = 10.0, | |
| max_frames: int = 160, | |
| conf_percentile: float = 40.0, | |
| mask_sky: bool = True, | |
| show_cam: bool = True, | |
| ): | |
| """Streaming 3D reconstruction from a video or an ordered image sequence. | |
| Frames are fed one by one to LingBot-Map 2.0 (causal streaming base model), | |
| which predicts a camera pose, intrinsics and dense depth for every frame. | |
| Args: | |
| video: path to an input video (used when no images are given). | |
| images: optional ordered list of RGB image files (natural filename order). | |
| fps: frame sampling rate used when extracting frames from the video. | |
| max_frames: maximum number of frames fed to the model (uniformly subsampled). | |
| conf_percentile: drop points below this depth-confidence percentile. | |
| mask_sky: remove sky points with an ONNX sky segmenter. | |
| show_cam: draw predicted camera frustums in the 3D scene. | |
| Returns: | |
| GLB point cloud with cameras, RGB|depth preview video, NPZ with poses/intrinsics/depth, status text. | |
| """ | |
| work = tempfile.mkdtemp(prefix="lingbot_") | |
| frames_dir = os.path.join(work, "frames") | |
| os.makedirs(frames_dir) | |
| paths, total, source = _gather_paths(video, images, fps, int(max_frames), frames_dir) | |
| t_call = time.perf_counter() | |
| pred = run_stream(paths, bool(mask_sky)) | |
| t1 = time.perf_counter() | |
| t_inf = pred["t_model"] | |
| glb_path = os.path.join(work, "reconstruction.glb") | |
| n_pts = _build_glb(pred, float(conf_percentile), bool(show_cam), glb_path) | |
| t2 = time.perf_counter() | |
| vid_path = os.path.join(work, "depth.mp4") | |
| _depth_video(pred["images"], pred["depth"], vid_path) | |
| t3 = time.perf_counter() | |
| npz_path = os.path.join(work, "predictions.npz") | |
| np.savez_compressed( | |
| npz_path, | |
| poses_c2w=pred["poses_c2w"].astype(np.float32), | |
| intrinsics=pred["intrinsics"].astype(np.float32), | |
| depth=pred["depth"][..., 0].astype(np.float16), | |
| depth_conf=pred["depth_conf"].astype(np.float16), | |
| ) | |
| shutil.rmtree(frames_dir, ignore_errors=True) | |
| print(f"[timing] gpu_call={t1 - t_call:.1f}s (in-gpu {pred['t_gpu']:.1f}s, model {t_inf:.1f}s) " | |
| f"glb={t2 - t1:.1f}s video={t3 - t2:.1f}s npz={time.perf_counter() - t3:.1f}s", flush=True) | |
| n = len(paths) | |
| status = ( | |
| f"**{n} frames** ({source}, {total} available) at {SPEC.width}×{SPEC.height} · " | |
| f"streaming inference **{t_inf:.1f}s** ({n / max(t_inf, 1e-6):.1f} FPS) · " | |
| f"post-processing {time.perf_counter() - t1:.1f}s · {n_pts:,} points" | |
| ) | |
| print(status, flush=True) | |
| return glb_path, vid_path, npz_path, status | |
| # --------------------------------------------------------------------------- | |
| # UI | |
| # --------------------------------------------------------------------------- | |
| CSS = """ | |
| #col-container { max-width: 1280px; margin: 0 auto; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| INTRO = """ | |
| # LingBot-Map 2.0 · Streaming 3D Reconstruction | |
| Feed a video (or an ordered photo sequence) and the **geometric streaming base model** reconstructs the scene | |
| causally, one frame at a time — predicting camera poses, intrinsics and dense depth, fused here into a colored | |
| point cloud with the camera trajectory. | |
| [Model](https://huggingface.co/robbyant/lingbot-map-v2-base-streaming) · | |
| [Code](https://github.com/Robbyant/lingbot-map-v2) · | |
| [Project](https://technology.robbyant.com/lingbot-map-v2) · | |
| [Paper](https://arxiv.org/abs/2611.36099) · License: CC BY-NC 4.0 (non-commercial) | |
| """ | |
| with gr.Blocks(title="LingBot-Map 2.0 Streaming") as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown(INTRO) | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| video_in = gr.Video(label="Input video") | |
| with gr.Accordion("…or upload an ordered image sequence", open=False): | |
| images_in = gr.File(label="Images (sorted by filename)", | |
| file_count="multiple", file_types=["image"]) | |
| run_btn = gr.Button("Reconstruct", variant="primary") | |
| with gr.Accordion("Advanced settings", open=False): | |
| fps_in = gr.Slider(1, 30, value=10, step=1, label="Video sampling FPS") | |
| max_frames_in = gr.Slider(16, MAX_FRAMES_HARD, value=160, step=8, | |
| label="Max frames (uniformly subsampled)") | |
| conf_in = gr.Slider(0, 95, value=40, step=5, | |
| label="Confidence filter (percentile of points dropped)") | |
| sky_in = gr.Checkbox(value=True, label="Mask sky") | |
| cam_in = gr.Checkbox(value=True, label="Show cameras") | |
| with gr.Column(scale=3): | |
| model_out = gr.Model3D(label="Point cloud + camera trajectory", | |
| height=520) | |
| status_out = gr.Markdown() | |
| depth_out = gr.Video(label="Input | predicted depth", autoplay=True, loop=True) | |
| npz_out = gr.File(label="Predictions (.npz: poses_c2w, intrinsics, depth, depth_conf)") | |
| outputs = [model_out, depth_out, npz_out, status_out] | |
| run_btn.click( | |
| reconstruct, | |
| inputs=[video_in, images_in, fps_in, max_frames_in, conf_in, sky_in, cam_in], | |
| outputs=outputs, | |
| api_name="reconstruct", | |
| ) | |
| gr.Examples( | |
| examples=[["examples/courthouse.mp4"], ["examples/university.mp4"], | |
| ["examples/loop.mp4"]], | |
| inputs=[video_in], | |
| outputs=outputs, | |
| fn=reconstruct, | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| label="Examples (sequences from the LingBot-Map repository)", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True) | |