Download utils.py from modventures/room-visualizer-v2: direct link, hf CLI and curl.
- Browser
- Download file 1.76 kB
-
https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/utils.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer-v2/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/utils.py
1.76 kB
| """Shared utility functions used across the floor-visualizer backend.""" | |
| from __future__ import annotations | |
| import time | |
| from contextlib import contextmanager | |
| import numpy as np | |
| def timed_stage(label: str): | |
| """Context manager that measures elapsed time and prints a timing line. | |
| Yields a dict with an ``elapsed_ms`` key that is populated on exit. | |
| Usage:: | |
| with timed_stage("Floor segmentation") as t: | |
| result = run_segmentation(img) | |
| print(t["elapsed_ms"]) | |
| """ | |
| info: dict = {"elapsed_ms": 0.0} | |
| t0 = time.perf_counter() | |
| try: | |
| yield info | |
| finally: | |
| info["elapsed_ms"] = (time.perf_counter() - t0) * 1000 | |
| print(f"[TIMING] {label} took {info['elapsed_ms'] / 1000:.3f} seconds", flush=True) | |
| def to_numpy(value): | |
| """Convert a torch.Tensor or array-like to a numpy array.""" | |
| if value is None: | |
| return None | |
| try: | |
| import torch | |
| if isinstance(value, torch.Tensor): | |
| return value.detach().float().cpu().numpy() | |
| except ImportError: | |
| pass | |
| return np.asarray(value) | |
| def seg_class_mask(seg_map: np.ndarray, class_id_list: list[int]) -> np.ndarray: | |
| """Return a uint8 binary mask for pixels whose seg_map value is in *class_id_list*.""" | |
| return np.isin(seg_map, class_id_list).astype(np.uint8) | |
| def mask_to_indices(mask: np.ndarray) -> np.ndarray: | |
| """Return the flat uint32 indices of non-zero pixels in *mask*.""" | |
| return np.flatnonzero(mask.ravel()).astype(np.uint32) | |
| def encode_b64(arr: np.ndarray | None) -> str | None: | |
| """Base64-encode a numpy array's raw bytes, or return None.""" | |
| if arr is None: | |
| return None | |
| import base64 | |
| return base64.b64encode(arr.tobytes()).decode() | |