Download code/tt_depthpro2/streaming.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 9.38 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/streaming.py
- Command line
-
hf download hf://changh95/DepthPro2/code/tt_depthpro2/streaming.py
-
curl -L -o streaming.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/streaming.py
9.38 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| # The streaming logic of this module follows the structure of Apple's streaming.py from | |
| # apple-aiml-research/ml-depth-pro-2 (Copyright (C) 2026 Apple Inc. All Rights Reserved.), used under Apple's | |
| # software licence, a copy of which is ../licenses/APPLE_SOFTWARE_LICENSE.txt (tt_depthpro2/licenses/). | |
| """Video streaming of DepthPro2 on the host: the official ``DepthStream`` (ml-depth-pro-2 @ aa389cbb, ``streaming.py``), | |
| whose structure this module follows, over the device engine's ``inverse_depth`` / ``fov_logits`` (and, for the | |
| unbuffered mode, the designed KV-cache step). | |
| A stream is a session over one video. Every frame's prediction is returned once, in order, and never revised. | |
| * **buffered** -- clips of ``window`` frames overlapping by ``overlap``: as soon as ``window`` frames are pending | |
| (the ``overlap`` frames predicted by the previous clip but held back, plus the new ones), the clip is predicted; | |
| the held frames are cross-faded with the new clip's prediction of the same frames by a linear ramp (weights from 1 | |
| to 0 across the held frames, endpoints excluded, no scale fit) and everything but the last ``overlap`` frames is | |
| returned. ``flush`` predicts the rest: with an overlap the last clip is pulled back to a full window over frames | |
| already returned (they are predicted again but not returned again), without one it is just the new frames. | |
| * **unbuffered** -- clips of one frame, each attending the ``window - 1`` frames before it through a key-value | |
| cache (``engine.inverse_depth_step``); predictions are returned at once. | |
| Focal length: the one given, else the median estimate over the frames predicted so far (each predicted clip runs | |
| the FOV estimator on its frames), kept once at least ``window`` estimates are in. A whole video known in advance | |
| (``DepthPro2.infer_video``) instead estimates it once over the first ``window`` frames and passes it in, as the | |
| official ``infer_video`` does. | |
| """ | |
| from __future__ import annotations | |
| from collections import deque | |
| from dataclasses import dataclass | |
| from typing import Any, Callable, Deque, List, Optional | |
| import torch | |
| __all__ = ["StreamPrediction", "DepthStream", "blend_weights"] | |
| class StreamPrediction: | |
| """One finished frame: ``inverse_depth`` ``(H, W)`` float32 at the stream's size, ``f_px`` (0-d tensor in the | |
| stream's pixels, or None) and the frame's index in the video.""" | |
| index: int | |
| inverse_depth: torch.Tensor | |
| f_px: Optional[torch.Tensor] | |
| def blend_weights(n: int, like: torch.Tensor) -> torch.Tensor: | |
| """``n`` weights from 1 down to 0 with both endpoints excluded, shaped ``(n, 1, 1)``: the weight of the earlier | |
| clip's prediction of each held frame (the new clip gets one minus it).""" | |
| return torch.linspace(1.0, 0.0, n + 2, dtype=like.dtype, device=like.device)[1:-1].reshape(n, 1, 1) | |
| class DepthStream: | |
| """A session over one video (see the module docstring). Frames are normalized ``(3, H, W)`` float32 tensors of | |
| one size (the engine's bucket size); open one stream per video.""" | |
| def __init__(self, predict_clip: Callable[[torch.Tensor], torch.Tensor], *, window: int, overlap: int, | |
| f_px: Any = None, mode: str = "buffered", | |
| fov_deg: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, | |
| focal_from_fov: Optional[Callable[[torch.Tensor, int, int], torch.Tensor]] = None, | |
| predict_step: Optional[Callable[[torch.Tensor, Any], torch.Tensor]] = None, | |
| open_cache: Optional[Callable[[], Any]] = None): | |
| """``predict_clip``: ``(T, 3, H, W) -> (T, H, W)`` inverse depth of a clip whose frames attend each other. | |
| ``fov_deg``: ``(T, 3, H, W) -> (T, 2)`` FoV in degrees (None: no focal estimate). ``focal_from_fov``: | |
| ``(fov_deg (n, 2), H, W) -> f_px`` (the median focal length). Unbuffered mode needs ``predict_step`` | |
| (``(1, 3, H, W), cache -> (1, H, W)``) and ``open_cache`` (``() -> cache``).""" | |
| if mode not in ("buffered", "unbuffered"): | |
| raise ValueError(f"mode must be 'buffered' or 'unbuffered', got {mode!r}") | |
| if window < 1: | |
| raise ValueError(f"window must be at least 1, got {window}") | |
| if mode == "buffered" and not 0 <= overlap < window: | |
| raise ValueError(f"overlap must be from 0 to window - 1 = {window - 1}, got {overlap}") | |
| if mode == "unbuffered" and (predict_step is None or open_cache is None): | |
| raise NotImplementedError("unbuffered video needs the engine's key-value cache step " | |
| "(inverse_depth_step / kv_cache), which this engine does not have") | |
| self.mode = mode | |
| self.window = int(window) | |
| self._predict_clip = predict_clip | |
| self._predict_step = predict_step | |
| self._fov_deg = fov_deg | |
| self._focal_from_fov = focal_from_fov | |
| self._f_px = None if f_px is None else torch.as_tensor(f_px, dtype=torch.float32).reshape(()) | |
| self._fovs: List[torch.Tensor] = [] | |
| self._cache = open_cache() if mode == "unbuffered" else None | |
| self._clip = self.window if mode == "buffered" else 1 | |
| self._overlap = int(overlap) if mode == "buffered" else 0 | |
| self._recent: Deque[torch.Tensor] = deque(maxlen=self._clip) # the last frames (a clip's worth) | |
| self._held: List[torch.Tensor] = [] # predicted, not returned yet (the overlap) | |
| self._new = 0 # frames added since the last prediction | |
| self._emitted = 0 # frames returned so far | |
| self._shape: Optional[torch.Size] = None | |
| self.closed = False | |
| def f_px(self) -> Optional[torch.Tensor]: | |
| """The focal length in use once fixed (given, or the estimate over ``window`` frames), else None.""" | |
| return self._f_px | |
| def pending(self) -> int: | |
| """Frames added but not returned yet.""" | |
| return len(self._held) + self._new | |
| def step(self, frame: torch.Tensor) -> List[StreamPrediction]: | |
| """Add the next frame ``(3, H, W)``; return the predictions it finishes (possibly none).""" | |
| if self.closed: | |
| raise RuntimeError("the stream is closed") | |
| if frame.ndim != 3 or frame.shape[0] != 3: | |
| raise ValueError(f"step takes one frame (3, H, W), got {tuple(frame.shape)}") | |
| if self._shape is not None and frame.shape != self._shape: | |
| raise ValueError(f"step takes frames of one size, got {tuple(frame.shape)} after {tuple(self._shape)}; " | |
| "open a new stream for frames of another size") | |
| self._shape = frame.shape | |
| self._recent.append(frame) | |
| self._new += 1 | |
| if self.pending < self._clip: | |
| return [] | |
| return self._run(len(self._recent), keep=self._overlap) | |
| def flush(self) -> List[StreamPrediction]: | |
| """End the video; return every prediction not returned yet. The stream stays usable (a later ``step`` | |
| continues the same video: its recent frames and focal length carry over).""" | |
| if self.closed: | |
| raise RuntimeError("the stream is closed") | |
| if not self._new: # only held frames: they come from a full clip, so the focal length is fixed | |
| return self._emit(len(self._held), self._f_px) | |
| length = len(self._recent) if self._overlap else self._new | |
| return self._run(length, keep=0) | |
| def close(self) -> None: | |
| if self._cache is not None and hasattr(self._cache, "close"): | |
| self._cache.close() | |
| self._cache = None | |
| self._recent.clear() | |
| self._held.clear() | |
| self.closed = True | |
| # -- internals | |
| def _run(self, length: int, keep: int) -> List[StreamPrediction]: | |
| """Predict the last ``length`` frames; return the finished ones, all but the last ``keep``.""" | |
| frames = list(self._recent)[-length:] | |
| clip = torch.stack(frames) | |
| if self._cache is not None: | |
| inv = self._predict_step(clip, self._cache) | |
| else: | |
| inv = self._predict_clip(clip) | |
| f_px = self._focal(clip) | |
| # frames of this clip that were already returned are not returned again | |
| inv = inv[length - self.pending:] | |
| n_held = len(self._held) | |
| self._new = 0 | |
| if n_held: | |
| prev = torch.stack(self._held) | |
| w = blend_weights(n_held, prev) | |
| self._held = list(w * prev + (1 - w) * inv[:n_held]) | |
| self._held.extend(inv[n_held:]) | |
| return self._emit(len(self._held) - keep, f_px) | |
| def _focal(self, clip: torch.Tensor) -> Optional[torch.Tensor]: | |
| if self._f_px is not None or self._fov_deg is None or self._focal_from_fov is None: | |
| return self._f_px | |
| self._fovs.append(self._fov_deg(clip).float()) | |
| fovs = torch.cat(self._fovs) | |
| f = self._focal_from_fov(fovs, int(clip.shape[-2]), int(clip.shape[-1])).reshape(()) | |
| if fovs.shape[0] >= self.window: | |
| self._f_px = f | |
| return f | |
| def _emit(self, count: int, f_px: Optional[torch.Tensor]) -> List[StreamPrediction]: | |
| done, self._held = self._held[:count], self._held[count:] | |
| out = [StreamPrediction(self._emitted + i, inv, f_px) for i, inv in enumerate(done)] | |
| self._emitted += len(done) | |
| return out | |