Download utils/io.py from WANG-XIXI/ViDiHand2: direct link, hf CLI and curl.
- Browser
- Download file 9.61 kB
-
https://huggingface.co/spaces/WANG-XIXI/ViDiHand2/resolve/main/utils/io.py
- Command line
-
hf download hf://spaces/WANG-XIXI/ViDiHand2/utils/io.py
-
curl -L -o io.py https://huggingface.co/spaces/WANG-XIXI/ViDiHand2/resolve/main/utils/io.py
9.61 kB
| """Checkpoints, video and camera I/O, and the model canvas shared by ViDiHand, ViDiHand2 and the demos.""" | |
| import itertools | |
| import json | |
| import os | |
| import tempfile | |
| from concurrent.futures import ThreadPoolExecutor | |
| from contextlib import contextmanager | |
| from pathlib import Path | |
| import cv2 | |
| import imageio_ffmpeg | |
| import numpy as np | |
| import torch | |
| from huggingface_hub import hf_hub_download | |
| from tqdm import tqdm | |
| CHECKPOINTS = Path(__file__).resolve().parents[1] / "checkpoints" | |
| FRAME_SLACK = 8 # spare rows allocated beyond the container's frame count estimate | |
| HUB_FILES = { # the checkpoints that download on first use: name in checkpoints/ -> (Hugging Face repository, its type, path in it) | |
| "mano/MANO_RIGHT.pkl": ("WANG-XIXI/EgoHandBench", "dataset", "baselines/wilor/official/checkpoints/mano/MANO_RIGHT.pkl"), | |
| **{f"{model}/{name}": ("WANG-XIXI/ViDiHand", "model", f"{model}/{name}") | |
| for model in ("vidihand_v1", "vidihand_v2") for name in ("vdm.safetensors", "projector.safetensors")}, | |
| } | |
| def checkpoint(name): | |
| """The path of checkpoints/<name>, downloaded first if it is missing and listed in HUB_FILES.""" | |
| path = CHECKPOINTS / name | |
| if not path.is_file(): | |
| if name not in HUB_FILES: | |
| raise FileNotFoundError(f"{path} is missing: download it (see the README) and put it there") | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.TemporaryDirectory(prefix=".download_", dir=CHECKPOINTS) as staging: | |
| repo, kind, remote = HUB_FILES[name] | |
| os.replace(hf_hub_download(repo, remote, repo_type=kind, local_dir=staging), path) | |
| return path | |
| def tf32(enabled): | |
| """Context manager / decorator that sets TF32 for CUDA matmuls and cuDNN, restoring the previous setting afterwards.""" | |
| old = torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 | |
| torch.backends.cuda.matmul.allow_tf32 = torch.backends.cudnn.allow_tf32 = enabled | |
| try: | |
| yield | |
| finally: | |
| torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = old | |
| def load_video(path, bar=None): | |
| """All frames of a video file as uint8 RGB [T, H, W, 3] (every decoded frame, no frame-rate conversion).""" | |
| stream = imageio_ffmpeg.read_frames(str(path), pix_fmt="rgb24", output_params=["-fps_mode", "passthrough"]) | |
| meta = next(stream) | |
| width, height = meta["size"] | |
| video = np.empty((round(meta["duration"] * meta["fps"]) + FRAME_SLACK, height, width, 3), np.uint8) | |
| n, own = 0, bar is None | |
| if own: | |
| bar = tqdm(desc="Loading the video", total=len(video) - FRAME_SLACK, unit="frame", leave=False) | |
| for frame in stream: | |
| if n == len(video): | |
| video = np.concatenate([video, np.empty_like(video[: len(video) // 2 + 1])]) | |
| video[n] = np.frombuffer(frame, np.uint8).reshape(height, width, 3) | |
| n += 1 | |
| bar.update() | |
| if own: | |
| bar.close() | |
| return video[:n] | |
| def matrix(intrinsics): | |
| """A 3 x 3 intrinsics matrix from a camera JSON entry ({fx, fy, cx, cy} or the matrix itself).""" | |
| if isinstance(intrinsics, dict): | |
| return [[intrinsics["fx"], 0.0, intrinsics["cx"]], [0.0, intrinsics["fy"], intrinsics["cy"]], [0.0, 0.0, 1.0]] | |
| return intrinsics | |
| def per_frame(K, n): | |
| """Intrinsics [n, 3, 3] from one 3 x 3 matrix or a per-frame stack.""" | |
| return np.repeat(np.asarray(K, np.float64)[None], n, 0) if np.ndim(K) == 2 else K | |
| def load_camera(path): | |
| """A camera JSON (the format of datasets/sample/*_camera.json) as K [T, 3, 3], E [T, 4, 4] (NaN without extrinsics), | |
| source_frame_ids, fps and size (width, height), validated.""" | |
| data = json.loads(Path(path).read_text()) | |
| nan = np.full((4, 4), np.nan) | |
| camera = dict(K=np.asarray([matrix(frame["intrinsics"]) for frame in data["frames"]], np.float64), | |
| E=np.asarray([frame.get("extrinsics", nan) for frame in data["frames"]], np.float64), | |
| source_frame_ids=np.asarray([frame["source_frame_id"] for frame in data["frames"]], np.int64), | |
| fps=float(data["fps"]), size=(int(data["image_width"]), int(data["image_height"]))) | |
| K = camera["K"] | |
| if K.ndim != 3 or K.shape[1:] != (3, 3) or not len(K) or not np.isfinite(K).all() or (K[:, [0, 1], [0, 1]] <= 0).any(): | |
| raise ValueError("every frame needs a finite 3 x 3 pinhole intrinsics matrix with positive focal lengths") | |
| if not np.allclose(K[:, [0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1]): | |
| raise ValueError("intrinsics must be [[fx, 0, cx], [0, fy, cy], [0, 0, 1]] (no skew)") | |
| if camera["E"].shape != (len(K), 4, 4): | |
| raise ValueError("extrinsics must be 4 x 4 world-to-camera matrices") | |
| if not (np.isfinite(camera["fps"]) and camera["fps"] > 0 and min(camera["size"]) > 0): | |
| raise ValueError("fps, image_width and image_height must be positive") | |
| return camera | |
| def save_camera(path, camera): | |
| """Writes a camera dict as a camera JSON (extrinsics only for the frames that have them).""" | |
| width, height = camera["size"] | |
| frames = [dict(source_frame_id=int(i), intrinsics=np.asarray(k, float).tolist()) | |
| for i, k in zip(camera["source_frame_ids"], camera["K"])] | |
| for frame, e in zip(frames, camera.get("E", [])): | |
| if np.isfinite(e).all(): | |
| frame["extrinsics"] = np.asarray(e, float).tolist() | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(dict(image_width=width, image_height=height, fps=camera["fps"], frames=frames), indent=1)) | |
| def load_sample(video, camera, name=None): | |
| """A model input: the video (a path or frames [T, H, W, 3]) with its camera (a JSON path or a camera dict), checked for agreement.""" | |
| path = isinstance(video, (str, Path)) | |
| name = name or (Path(video).stem if path else "video") | |
| frames = load_video(video) if path else video | |
| camera = load_camera(camera) if isinstance(camera, (str, Path)) else camera | |
| K = per_frame(camera["K"], len(frames)) | |
| if len(K) != len(frames): | |
| raise ValueError(f"{name}: {len(frames)} frames but {len(K)} camera rows") | |
| if camera["size"] != (frames.shape[2], frames.shape[1]): | |
| raise ValueError(f"{name}: {frames.shape[2]}x{frames.shape[1]} frames but a {camera['size'][0]}x{camera['size'][1]} camera") | |
| return dict(name=name, video=frames, K=K, source_frame_ids=camera["source_frame_ids"], fps=camera["fps"]) | |
| def model_size(width, height, short=480): | |
| """The model canvas (width, height) for a video, every side a multiple of 32 (at least 32): with `short`, the short side is `short` | |
| rounded to a multiple of 32 and the long side that rounded side times the aspect ratio, rounded; with `short=None`, each input side is | |
| rounded on its own.""" | |
| if not (width > 0 and height > 0): | |
| raise ValueError(f"the video size must be positive, got {width} x {height}") | |
| to32 = lambda v: max(32, round(v / 32) * 32) | |
| if short is None: | |
| return to32(width), to32(height) | |
| if isinstance(short, (bool, np.bool_)) or not isinstance(short, (int, np.integer)) or short <= 0: | |
| raise ValueError(f"the short side is a positive number of pixels or None, got {short!r}") | |
| short = to32(int(short)) | |
| long = to32(max(width, height) * (short / min(width, height))) | |
| return (long, short) if width >= height else (short, long) | |
| def resize(video, K, size): | |
| """Frames resized to `size` (area filter when shrinking) and the intrinsics mapped to it (pixel centres preserved).""" | |
| K = per_frame(K, len(video)) | |
| height, width = video.shape[1:3] | |
| if (width, height) == tuple(size): | |
| return video, K | |
| sx, sy = size[0] / width, size[1] / height | |
| interpolation = cv2.INTER_AREA if sx * sy < 1 else cv2.INTER_LINEAR | |
| with ThreadPoolExecutor(min(8, os.cpu_count() or 1)) as pool: | |
| frames = pool.map(lambda frame: cv2.resize(frame, tuple(size), interpolation=interpolation), video) | |
| video = np.stack(list(tqdm(frames, total=len(video), desc="Resizing to the model canvas", unit="frame", leave=False))) | |
| K = np.array(K, np.float64) | |
| K[:, 0] *= sx | |
| K[:, 1] *= sy | |
| K[:, 0, 2] += 0.5 * sx - 0.5 | |
| K[:, 1, 2] += 0.5 * sy - 0.5 | |
| return video, K | |
| def even_pad(width, height): | |
| """ffmpeg arguments that pad odd frame sizes to even ones (required by yuv420p).""" | |
| return [] if width % 2 == height % 2 == 0 else ["-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2"] | |
| def save_video(path, frames, fps, crf=18): | |
| """Writes RGB frames (any iterable) as an H.264 mp4 at the x264 constant rate factor `crf` (higher: smaller file, lower quality).""" | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| frames = iter(frames) | |
| first = next(frames, None) | |
| if first is None: | |
| raise ValueError(f"{path}: no frames to write") | |
| height, width = first.shape[:2] | |
| stream = imageio_ffmpeg.write_frames( | |
| str(path), (width, height), pix_fmt_in="rgb24", pix_fmt_out="yuv420p", fps=fps, quality=None, codec="libx264", macro_block_size=1, | |
| ffmpeg_log_level="error", input_params=["-r", str(fps)], output_params=even_pad(width, height) + ["-crf", str(crf), "-movflags", "+faststart"]) | |
| stream.send(None) | |
| try: | |
| for frame in itertools.chain([first], frames): | |
| stream.send(np.ascontiguousarray(frame)) | |
| finally: | |
| stream.close() | |
| def save_npz(path, data): | |
| """Writes a dict of arrays as a compressed npz, creating the folder.""" | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| np.savez_compressed(path, **data) | |