Download visualize.py from MingruiYu/HUGS-Human: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/datasets/MingruiYu/HUGS-Human/resolve/main/visualize.py
- Command line
-
hf download hf://datasets/MingruiYu/HUGS-Human/visualize.py
-
curl -L -o visualize.py https://huggingface.co/datasets/MingruiYu/HUGS-Human/resolve/main/visualize.py
19.4 kB
| #!/usr/bin/env python3 | |
| """Browse trusted, extracted HUGS-Human formatted records using Viser.""" | |
| from __future__ import annotations | |
| import argparse | |
| from collections import OrderedDict | |
| import csv | |
| from functools import lru_cache | |
| import logging | |
| from pathlib import Path | |
| import random | |
| import re | |
| import threading | |
| import numpy as np | |
| import torch | |
| import trimesh | |
| import viser | |
| from manopth.manolayer import ManoLayer | |
| LOG = logging.getLogger("hugs-human") | |
| MODES = ("Single grasp", "Same object", "Random batch") | |
| TIPS = (4, 8, 12, 16, 20) | |
| def natural_key(value): | |
| return tuple(int(x) if x.isdigit() else x for x in re.split(r"(\d+)", str(value))) | |
| def object_transform(info, source_mesh): | |
| scale = float(info.get("rel_scale", 1.0)) | |
| if not np.isfinite(scale) or scale <= 0: | |
| raise ValueError("object.rel_scale must be finite and positive") | |
| transform = np.asarray(info["pose"], dtype=np.float64) @ np.diag([scale] * 3 + [1]) | |
| if source_mesh: | |
| # Registration translation must be scaled with the canonical vertices. | |
| transform = transform @ np.asarray(info["mesh_to_canonical"], dtype=np.float64) | |
| if transform.shape != (4, 4) or not np.isfinite(transform).all(): | |
| raise ValueError("Invalid object transformation") | |
| return transform | |
| class Dataset: | |
| def __init__(self, formatted_root, source_root, mano_root, cache_size=8): | |
| self.formatted_root = Path(formatted_root).resolve() | |
| self.source_root = Path(source_root).resolve() if source_root else None | |
| paths = sorted((self.formatted_root / "grasp").glob("*/*.npy"), key=natural_key) | |
| if not paths: | |
| raise FileNotFoundError(f"No grasp/*/*.npy under {self.formatted_root}") | |
| self.by_object = {} | |
| for path in paths: | |
| self.by_object.setdefault(path.parent.name, []).append(path) | |
| self.paths = paths | |
| self.metadata = {} | |
| metadata = self.formatted_root / "metadata.csv" | |
| if metadata.is_file(): | |
| with metadata.open(newline="") as stream: | |
| self.metadata = {row["scene"]: row for row in csv.DictReader(stream)} | |
| self.mesh_cache = OrderedDict() | |
| self.cache_size = cache_size | |
| self.layers = {} | |
| for side in ("left", "right"): | |
| model = Path(mano_root) / f"MANO_{side.upper()}.pkl" | |
| if not model.is_file(): | |
| raise FileNotFoundError( | |
| f"Missing {model}. Obtain licensed MANO models from " | |
| "https://mano.is.tue.mpg.de/ and pass --mano-root (directory containing both PKLs)." | |
| ) | |
| self.layers[side] = ManoLayer( | |
| mano_root=str(mano_root), side=side, center_idx=0, | |
| use_pca=False, flat_hand_mean=True, ncomps=45, | |
| root_rot_mode="axisang", joint_rot_mode="axisang", | |
| ).cpu().eval() | |
| def record(self, path): | |
| return np.load(path, allow_pickle=True).item() | |
| def row(self, path): | |
| return self.metadata.get(f"{path.parent.name}_{path.stem}", {}) | |
| def grasp_type(self, path): | |
| row = self.row(path) | |
| if row.get("has_left_hand") == "1" and row.get("has_right_hand") == "1": | |
| return "4_both_three" if row.get("right_finger_count") == "3" else "5_both_full" | |
| return {"2": "1_right_two", "3": "2_right_three", "5": "3_right_full"}.get( | |
| row.get("right_finger_count"), "unknown" | |
| ) | |
| def mesh_path(self, info): | |
| relative = Path(info["path"]) | |
| formatted = (self.formatted_root / relative).resolve() | |
| if not relative.is_absolute() and formatted.is_relative_to(self.formatted_root) and formatted.is_file(): | |
| return formatted, False | |
| if self.source_root is not None: | |
| source = (self.source_root / "collected_results" / info["source_scene"] / "mesh/textured.obj").resolve() | |
| if source.is_relative_to(self.source_root) and source.is_file(): | |
| if "mesh_to_canonical" not in info: | |
| raise ValueError("Source mesh fallback requires object.mesh_to_canonical") | |
| return source, True | |
| raise FileNotFoundError( | |
| f"Mesh unavailable for {info.get('source_scene', info['name'])}. " | |
| "Extract source/v1 and pass --source-root /path/to/OurHumanGrasp, " | |
| "or supply the optional formatted canonical meshes." | |
| ) | |
| def object_meshes(self, info): | |
| path, is_source = self.mesh_path(info) | |
| if path not in self.mesh_cache: | |
| loaded = trimesh.load(path, process=False) | |
| if isinstance(loaded, trimesh.Trimesh): | |
| meshes = [loaded] | |
| elif isinstance(loaded, trimesh.Scene): | |
| # Bake each scene-graph instance transform; preserve materials/UVs. | |
| meshes = [] | |
| for node in loaded.graph.nodes_geometry: | |
| transform, geometry = loaded.graph[node] | |
| mesh = loaded.geometry[geometry].copy() | |
| mesh.apply_transform(transform) | |
| meshes.append(mesh) | |
| else: | |
| raise ValueError(f"Unsupported mesh: {path}") | |
| if not meshes or any(not len(m.faces) for m in meshes): | |
| raise ValueError(f"Empty mesh: {path}") | |
| self.mesh_cache[path] = meshes | |
| while len(self.mesh_cache) > self.cache_size: | |
| self.mesh_cache.popitem(last=False) | |
| self.mesh_cache.move_to_end(path) | |
| transform = object_transform(info, is_source) | |
| result = [] | |
| for cached in self.mesh_cache[path]: | |
| mesh = cached.copy() | |
| mesh.apply_transform(transform) | |
| result.append(mesh) | |
| return result | |
| def hand(self, side, info): | |
| def tensor(key, count): | |
| return torch.tensor(np.asarray(info[key]).reshape(1, count), dtype=torch.float32) | |
| scale = float(info["scale"]) | |
| if not np.isfinite(scale) or scale <= 0: | |
| raise ValueError("hand.scale must be finite and positive") | |
| with torch.no_grad(): | |
| vertices, joints = self.layers[side]( | |
| torch.cat((tensor("rot", 3), tensor("mano_pose", 45)), dim=1), | |
| th_betas=tensor("mano_betas", 10), | |
| ) | |
| translation = tensor("trans", 3) | |
| vertices = (vertices / scale + translation)[0].numpy() | |
| joints = (joints / scale + translation)[0].numpy() | |
| if not np.isfinite(vertices).all(): | |
| raise ValueError("Non-finite MANO vertices") | |
| return vertices, self.layers[side].th_faces.numpy(), joints | |
| class Viewer: | |
| def __init__(self, dataset, host, port, initial_object=None): | |
| self.data = dataset | |
| self.server = viser.ViserServer(host=host, port=port, label="HUGS-Human") | |
| self.server.scene.set_up_direction("+z") | |
| self.server.gui.configure_theme(control_layout="collapsible", control_width="medium", show_logo=False, show_share_button=False) | |
| self.changed = threading.Event() | |
| self.lock = threading.RLock() | |
| self.rng = random.Random(0) | |
| self.random_paths = [] | |
| self.page_index = 0 | |
| self.roots = [] | |
| self.visibility_nodes = [] | |
| self.center = np.zeros(3) | |
| self.span = 0.5 | |
| objects = list(dataset.by_object) | |
| if initial_object and initial_object not in objects: | |
| raise ValueError(f"Unknown object {initial_object}") | |
| with self.server.gui.add_folder("HUGS-Human"): | |
| self.mode = self.server.gui.add_dropdown("View", MODES) | |
| self.obj = self.server.gui.add_dropdown("Object", objects, initial_value=initial_object or objects[0]) | |
| self.seq = self.server.gui.add_dropdown("Sequence", [p.stem for p in dataset.by_object[self.obj.value]]) | |
| self.previous = self.server.gui.add_button("", icon=viser.Icon.ARROW_LEFT, hint="Previous grasp or page") | |
| self.next = self.server.gui.add_button("", icon=viser.Icon.ARROW_RIGHT, hint="Next grasp or page") | |
| self.shuffle = self.server.gui.add_button("New random batch", icon=viser.Icon.ARROWS_SHUFFLE, visible=False) | |
| self.count = self.server.gui.add_slider("Batch size", min=1, max=12, step=1, initial_value=6, visible=False) | |
| self.info = self.server.gui.add_markdown("") | |
| with self.server.gui.add_folder("Display"): | |
| self.visibility = {key: self.server.gui.add_checkbox(label, initial_value=value) for key, label, value in ( | |
| ("left", "Left hand", True), ("right", "Right hand", True), | |
| ("object", "Object mesh", True), ("table", "Table", True), | |
| ("contacts", "Contact markers", False), ("labels", "Scene labels", True), | |
| )} | |
| self.auto_camera = self.server.gui.add_checkbox("Auto camera", initial_value=True) | |
| self.fit = self.server.gui.add_button("Fit camera", icon=viser.Icon.FOCUS_2) | |
| self.status = self.server.gui.add_markdown("Loading...") | |
| self.obj.on_update(self.object_changed) | |
| self.mode.on_update(self.mode_changed) | |
| self.seq.on_update(lambda _: self.changed.set()) | |
| self.count.on_update(self.batch_changed) | |
| self.previous.on_click(lambda _: self.navigate(-1)) | |
| self.next.on_click(lambda _: self.navigate(1)) | |
| self.shuffle.on_click(self.batch_changed) | |
| self.fit.on_click(lambda _: self.fit_camera()) | |
| for control in self.visibility.values(): | |
| control.on_update(lambda _: self.update_visibility()) | |
| self.server.on_client_connect(self.fit_camera) | |
| self.changed.set() | |
| def object_changed(self, _): | |
| with self.lock: | |
| options = [p.stem for p in self.data.by_object[self.obj.value]] | |
| self.seq.options = options | |
| self.seq.value = options[0] | |
| self.page_index = 0 | |
| self.changed.set() | |
| def mode_changed(self, _): | |
| with self.lock: | |
| single = self.mode.value == MODES[0] | |
| random_mode = self.mode.value == MODES[2] | |
| self.obj.visible = not random_mode | |
| self.seq.visible = single | |
| self.count.visible = not single | |
| self.shuffle.visible = random_mode | |
| self.page_index = 0 | |
| self.random_paths = [] | |
| self.changed.set() | |
| def batch_changed(self, _): | |
| with self.lock: | |
| self.random_paths = [] | |
| self.page_index = 0 | |
| self.changed.set() | |
| def navigate(self, step): | |
| with self.lock: | |
| if self.mode.value == MODES[0]: | |
| options = list(self.seq.options) | |
| self.seq.value = options[(options.index(self.seq.value) + step) % len(options)] | |
| elif self.mode.value == MODES[1]: | |
| pages = (len(self.data.by_object[self.obj.value]) + int(self.count.value) - 1) // int(self.count.value) | |
| self.page_index = (self.page_index + step) % pages | |
| else: | |
| self.random_paths = [] | |
| self.changed.set() | |
| def selection(self): | |
| with self.lock: | |
| if self.mode.value == MODES[2]: | |
| if not self.random_paths: | |
| self.random_paths = self.rng.sample(self.data.paths, min(int(self.count.value), len(self.data.paths))) | |
| return list(self.random_paths), "Random batch" | |
| paths = self.data.by_object[self.obj.value] | |
| if self.mode.value == MODES[0]: | |
| return [next(p for p in paths if p.stem == self.seq.value)], f"{self.obj.value} / {self.seq.value}" | |
| paths = sorted(paths, key=lambda p: (natural_key(self.data.row(p).get("pose_index", "")), natural_key(p.stem))) | |
| count = int(self.count.value) | |
| start = self.page_index * count | |
| return paths[start:start + count], f"{self.obj.value} / page {self.page_index + 1} of {(len(paths) + count - 1) // count}" | |
| def update_visibility(self): | |
| with self.lock: | |
| for node, category in self.visibility_nodes: | |
| node.visible = self.visibility[category].value | |
| def fit_camera(self, client=None): | |
| clients = [client] if client else self.server.get_clients().values() | |
| for current in clients: | |
| current.camera.up_direction = (0, 0, 1) | |
| # Viser position updates also translate look_at: set the target last. | |
| current.camera.position = tuple(self.center + np.array([0.65, -1.25, 0.9]) * self.span) | |
| current.camera.look_at = tuple(self.center) | |
| current.camera.near = 0.005 | |
| current.camera.far = 100.0 | |
| def render(self): | |
| paths, title = self.selection() | |
| self.status.content = "Loading..." | |
| prepared = [] | |
| for path in paths: | |
| record = self.data.record(path) | |
| meshes = self.data.object_meshes(record["object"]) | |
| hands = {side: self.data.hand(side, info) for side, info in record["hand"].items() if info and side in self.data.layers} | |
| points = [m.bounds for m in meshes] + [v for v, _, _ in hands.values()] | |
| bounds = np.concatenate(points) | |
| prepared.append((path, record, meshes, hands, np.array([bounds.min(0), bounds.max(0)]))) | |
| cell_size = max(0.4, max(np.max(item[4][1, :2] - item[4][0, :2]) for item in prepared) + 0.15) | |
| columns = min(3, int(np.ceil(np.sqrt(len(prepared))))) | |
| positions = [] | |
| row, column, previous_pose = 0, 0, None | |
| for index, (path, *_) in enumerate(prepared): | |
| pose = self.data.row(path).get("pose_index", "?") | |
| if self.mode.value == MODES[1]: | |
| if column == columns or (previous_pose is not None and previous_pose != pose): | |
| row, column = row + 1, 0 | |
| positions.append((column, row)) | |
| column += 1 | |
| previous_pose = pose | |
| else: | |
| positions.append((index % columns, index // columns)) | |
| all_bounds = [] | |
| with self.lock, self.server.atomic(): | |
| for root in self.roots: | |
| root.remove() | |
| self.roots.clear() | |
| self.visibility_nodes.clear() | |
| for index, (path, record, meshes, hands, bounds) in enumerate(prepared): | |
| column, row = positions[index] | |
| offset = np.array([column * cell_size, -row * cell_size, 0.0]) | |
| offset[:2] -= bounds.mean(0)[:2] | |
| all_bounds.append(bounds + offset) | |
| prefix = f"/grasps/{index}" | |
| self.roots.append(self.server.scene.add_frame(prefix, show_axes=False, position=offset)) | |
| for mesh_index, mesh in enumerate(meshes): | |
| node = self.server.scene.add_mesh_trimesh(f"{prefix}/object/{mesh_index}", mesh) | |
| self.visibility_nodes.append((node, "object")) | |
| for side, (vertices, faces, joints) in hands.items(): | |
| node = self.server.scene.add_mesh_simple( | |
| f"{prefix}/{side}", vertices, faces, | |
| color=(100, 190, 220) if side == "left" else (225, 154, 125), side="double", | |
| ) | |
| self.visibility_nodes.append((node, side)) | |
| contacts = np.asarray(record["hand"][side].get("contacts", np.zeros(5))).reshape(5) | |
| for finger, joint in enumerate(TIPS): | |
| if contacts[finger] > 0: | |
| marker = self.server.scene.add_icosphere( | |
| f"{prefix}/contacts/{side}/{finger}", radius=0.004, color=(230, 55, 65), position=joints[joint], subdivisions=1, | |
| ) | |
| self.visibility_nodes.append((marker, "contacts")) | |
| table = self.server.scene.add_grid( | |
| f"{prefix}/table", width=cell_size * 0.92, height=cell_size * 0.92, plane="xy", | |
| cell_size=0.05, section_size=0.25, plane_opacity=0.15, | |
| position=(bounds.mean(0)[0], bounds.mean(0)[1], 0), | |
| ) | |
| self.visibility_nodes.append((table, "table")) | |
| label = self.server.scene.add_label( | |
| f"{prefix}/label", f"{path.parent.name} / {path.stem}", | |
| position=(bounds.mean(0)[0], bounds[0, 1] - 0.04, 0.01), anchor="top-center", | |
| ) | |
| self.visibility_nodes.append((label, "labels")) | |
| self.update_visibility() | |
| combined = np.concatenate(all_bounds) | |
| self.center = (combined.min(0) + combined.max(0)) / 2 | |
| self.span = max(0.3, float(np.max(combined.max(0) - combined.min(0))) * 1.15) | |
| if self.auto_camera.value: | |
| self.fit_camera() | |
| lines = [f"**{title}**", f"{len(self.data.by_object)} objects / {len(self.data.paths)} grasps"] | |
| for path in paths: | |
| lines.append(f"{path.parent.name}/{path.stem}: `{self.data.grasp_type(path)}` | pose {self.data.row(path).get('pose_index', '?')}") | |
| self.info.content = "\n\n".join(lines) | |
| self.status.content = f"Ready / {len(paths)} grasp(s) / meters" | |
| LOG.info("Rendered %s (%d grasps)", title, len(paths)) | |
| def run(self): | |
| while True: | |
| self.changed.wait() | |
| self.changed.clear() | |
| try: | |
| self.render() | |
| except Exception as error: | |
| LOG.exception("Could not render selection") | |
| self.status.content = f"**Could not load selection:** {error}" | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--formatted-root", type=Path, default=Path(__file__).resolve().parent / "OurHumanGraspFormat", help="Extracted formatted directory containing grasp/ and metadata.csv") | |
| parser.add_argument("--source-root", type=Path, default=Path(__file__).resolve().parent / "OurHumanGrasp", help="Extracted source directory containing collected_results/") | |
| parser.add_argument("--mano-root", type=Path, required=True, help="Licensed model directory containing MANO_LEFT.pkl and MANO_RIGHT.pkl") | |
| parser.add_argument("--host", default="127.0.0.1") | |
| parser.add_argument("--port", type=int, default=9067) | |
| parser.add_argument("--object", help="Initial object ID, e.g. obj_443") | |
| parser.add_argument("--mesh-cache-size", type=int, default=8) | |
| args = parser.parse_args() | |
| if args.mesh_cache_size < 1: | |
| parser.error("--mesh-cache-size must be positive") | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") | |
| torch.set_num_threads(1) | |
| try: | |
| data = Dataset(args.formatted_root, args.source_root, args.mano_root, args.mesh_cache_size) | |
| # Fail early on missing public mesh inputs, before opening the server. | |
| initial_object = args.object or next(iter(data.by_object)) | |
| if initial_object not in data.by_object: | |
| parser.error(f"Unknown object: {initial_object}") | |
| data.mesh_path(data.record(data.by_object[initial_object][0])["object"]) | |
| Viewer(data, args.host, args.port, initial_object).run() | |
| except KeyboardInterrupt: | |
| pass | |
| except (FileNotFoundError, ValueError, KeyError) as error: | |
| parser.exit(1, f"{error}\n") | |
| if __name__ == "__main__": | |
| main() | |