Download probe_common.py from JackieMM/progress_probe_repro: direct link, hf CLI and curl.
- Browser
- Download file 20.8 kB
-
https://huggingface.co/JackieMM/progress_probe_repro/resolve/main/probe_common.py
- Command line
-
hf download hf://JackieMM/progress_probe_repro/probe_common.py
-
curl -L -o probe_common.py https://huggingface.co/JackieMM/progress_probe_repro/resolve/main/probe_common.py
20.8 kB
| """Shared utilities for progress and classification probes.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import subprocess | |
| import tempfile | |
| from pathlib import Path | |
| from typing import Iterable | |
| import h5py | |
| import numpy as np | |
| from PIL import Image | |
| DEFAULT_LABEL_ROOT = Path("/home/ydming/datasets/himaconplusplus_0.8B_labels") | |
| DEFAULT_VIDEO_ROOT = Path("/home/ydming/datasets/robotwin2.0-hard") | |
| DEFAULT_OUTPUT_ROOT = Path("/home/ydming/progress_probe_repro/outputs") | |
| # Classification / Progress label defaults: | |
| # 1) Himacon D1 cache (has ALOHA for all 7 tasks) | |
| # 2) ACP /data/share or Himacon /share cross-embodiment | |
| D1_LABEL_ROOT = Path("/data1/202608/himacon++_cache2/robotwin2.0-hard-cross-embodiment") | |
| REPO_ALOHA_OVERLAY = Path(__file__).resolve().parent / "data" / "aloha_concepts" | |
| def _default_cross_embodiment_roots() -> tuple[Path, Path]: | |
| if D1_LABEL_ROOT.is_dir(): | |
| for share in (Path("/share"), Path("/data/share")): | |
| video = share / "robotwin2.0-hard" | |
| if video.is_dir(): | |
| return D1_LABEL_ROOT, video | |
| return D1_LABEL_ROOT, Path("/share/robotwin2.0-hard") | |
| for share in (Path("/data/share"), Path("/share")): | |
| label = share / "robotwin2.0-hard-cross-embodiment" | |
| video = share / "robotwin2.0-hard" | |
| if label.is_dir(): | |
| return label, video | |
| return ( | |
| Path("/share/robotwin2.0-hard-cross-embodiment"), | |
| Path("/share/robotwin2.0-hard"), | |
| ) | |
| def label_root_search_paths(primary: Path | str | None = None) -> list[Path]: | |
| """Primary label root plus optional overlays (ALOHA concepts not on share SX).""" | |
| import os | |
| roots: list[Path] = [] | |
| if primary is not None: | |
| roots.append(Path(primary)) | |
| else: | |
| roots.append(_default_cross_embodiment_roots()[0]) | |
| extra = os.environ.get("LABEL_ROOT_EXTRA", "").strip() | |
| if extra: | |
| roots.append(Path(extra)) | |
| if REPO_ALOHA_OVERLAY.is_dir(): | |
| roots.append(REPO_ALOHA_OVERLAY) | |
| # D1 as last-resort fill for missing demos when primary is share-only | |
| if D1_LABEL_ROOT.is_dir(): | |
| roots.append(D1_LABEL_ROOT) | |
| # de-dupe preserving order | |
| out: list[Path] = [] | |
| seen: set[str] = set() | |
| for r in roots: | |
| key = str(r.resolve()) if r.exists() else str(r) | |
| if key in seen: | |
| continue | |
| if r.exists(): | |
| seen.add(key) | |
| out.append(r) | |
| return out | |
| CLASSIFICATION_LABEL_ROOT, CLASSIFICATION_VIDEO_ROOT = _default_cross_embodiment_roots() | |
| CLASSIFICATION_OUTPUT_ROOT = Path("outputs/classification_probe") | |
| DEFAULT_TASK_DIRS = { | |
| "blocks_ranking_size": "validation-robotwin_blocks_ranking_size-20260516_192550-fps10-label", | |
| "hanging_mug": "validation-robotwin_hanging_mug-20260610_134829-fps5-label", | |
| "place_bread_basket": "validation-robotwin_place_bread_basket-20260612_135321-fps3-label", | |
| "place_dual_shoes": "validation-robotwin_place_dual_shoes-20260614_102824-fps3-label", | |
| "place_mouse_pad": "validation-robotwin_place_mouse_pad-20260620_205834-fps2-label", | |
| "place_object_basket": "validation-robotwin_place_object_basket-20260611_214001-fps4-label", | |
| "scan_object": "validation-robotwin_scan_object-20260618_204507-fps2-label", | |
| "stack_blocks_three": "validation-robotwin_stack_blocks_three-20260528_231301-fps10-label", | |
| } | |
| PILOT_TASK = "blocks_ranking_rgb" | |
| PILOT_DEMOS = [ | |
| "demo_clean_100_aloha", | |
| "demo_clean_100_arx", | |
| "demo_clean_100_franka", | |
| "demo_clean_100_ur5", | |
| ] | |
| PILOT_LABEL_KINDS = ["full_label", "womae_label"] | |
| CLASS_NAMES = ["reach", "grasp", "transition", "release", "retract"] | |
| CLASS_TO_ID = {name: i for i, name in enumerate(CLASS_NAMES)} | |
| ID_TO_CLASS = {i: name for name, i in CLASS_TO_ID.items()} | |
| IGNORE_ID = -1 # unlabeled timesteps only (gaps in segment coverage) | |
| def default_output_root() -> Path: | |
| return Path.cwd() / "progress_probe_outputs" | |
| def natural_key(value: str | Path) -> list[object]: | |
| stem = Path(value).stem | |
| return [int(part) if part.isdigit() else part.lower() for part in re.split(r"(\d+)", stem)] | |
| def episode_number(path: str | Path) -> int: | |
| matches = re.findall(r"\d+", Path(path).stem) | |
| if not matches: | |
| raise ValueError(f"Cannot parse episode number from {path}") | |
| return int(matches[-1]) | |
| def demo_to_robot(demo: str) -> str: | |
| prefix = "demo_clean_100_" | |
| if demo.startswith(prefix): | |
| return demo[len(prefix):] | |
| return demo | |
| def episode_label_stem(episode_id: int) -> str: | |
| return f"episode_{episode_id:05d}" | |
| def episode_video_name(episode_id: int) -> str: | |
| return f"episode{episode_id}.mp4" | |
| def ensure_dir(path: Path) -> Path: | |
| path.mkdir(parents=True, exist_ok=True) | |
| return path | |
| def load_concept(path: Path, feature_start: int = 0, feature_end: int | None = None) -> np.ndarray: | |
| with h5py.File(path, "r") as handle: | |
| concept = handle["concept"][:] | |
| if concept.ndim != 2: | |
| raise ValueError(f"{path} concept must be 2D, got {concept.shape}") | |
| return concept[:, feature_start:feature_end].astype(np.float32, copy=False) | |
| def progress_labels(num_steps: int) -> np.ndarray: | |
| if num_steps <= 1: | |
| return np.zeros((num_steps,), dtype=np.float32) | |
| return np.linspace(0.0, 1.0, num_steps, dtype=np.float32) | |
| def label_files(task_dir: Path) -> list[Path]: | |
| files = sorted(task_dir.glob("episode_*.hdf5"), key=natural_key) | |
| if not files: | |
| raise FileNotFoundError(f"No episode_*.hdf5 files found in {task_dir}") | |
| return files | |
| def video_files(video_dir: Path) -> list[Path]: | |
| files = sorted(video_dir.glob("*.mp4"), key=natural_key) | |
| if not files: | |
| raise FileNotFoundError(f"No *.mp4 files found in {video_dir}") | |
| return files | |
| def validation_dirs( | |
| root: Path, | |
| task: str, | |
| demo: str | None, | |
| label_kind: str | None, | |
| pattern: str, | |
| ) -> list[Path]: | |
| root = Path(root) | |
| candidates: list[Path] = [] | |
| if demo and label_kind: | |
| candidates.extend(sorted((root / task / demo / label_kind).glob(pattern), key=natural_key)) | |
| elif demo: | |
| candidates.extend(sorted((root / task / demo).glob(f"*/{pattern}"), key=natural_key)) | |
| elif task in DEFAULT_TASK_DIRS and (root / DEFAULT_TASK_DIRS[task]).exists(): | |
| candidates.append(root / DEFAULT_TASK_DIRS[task]) | |
| else: | |
| candidates.extend(sorted((root / task).glob(f"demo_clean_100_*/*/{pattern}"), key=natural_key)) | |
| candidates.extend(sorted(root.glob(f"validation-robotwin_{task}-*-label"), key=natural_key)) | |
| valid = [] | |
| for path in candidates: | |
| if path.is_dir() and list(path.glob("episode_*.hdf5")): | |
| valid.append(path) | |
| return valid | |
| def resolve_label_dir(args: argparse.Namespace) -> Path: | |
| if getattr(args, "task_dir", None): | |
| return Path(args.task_dir) | |
| if getattr(args, "label_dir", None): | |
| return Path(args.label_dir) | |
| root = Path(getattr(args, "label_root", DEFAULT_LABEL_ROOT)) | |
| pattern = getattr(args, "validation_glob", "validation-*-label") | |
| dirs: list[Path] = [] | |
| for cand_root in label_root_search_paths(root): | |
| dirs = validation_dirs( | |
| cand_root, args.task, getattr(args, "demo", None), getattr(args, "label_kind", None), pattern | |
| ) | |
| if dirs: | |
| root = cand_root | |
| break | |
| if not dirs: | |
| raise FileNotFoundError( | |
| f"No validation label directory found for task={args.task}, demo={getattr(args, 'demo', None)}, " | |
| f"label_kind={getattr(args, 'label_kind', None)} under {label_root_search_paths(root)}" | |
| ) | |
| index = getattr(args, "validation_index", 0) | |
| if index >= len(dirs): | |
| raise IndexError(f"--validation-index {index} out of range; found {len(dirs)} dirs: {[str(d) for d in dirs]}") | |
| if len(dirs) > 1 and not getattr(args, "allow_multiple_validation_dirs", False): | |
| print( | |
| "warning: multiple validation dirs found; using index " | |
| f"{index}. Pass --validation-index or --allow-multiple-validation-dirs explicitly." | |
| ) | |
| for i, path in enumerate(dirs): | |
| print(f" [{i}] {path}") | |
| return dirs[index] | |
| def resolve_video_dir(args: argparse.Namespace) -> Path: | |
| if getattr(args, "video_dir", None): | |
| return Path(args.video_dir) | |
| root = Path(getattr(args, "video_root", DEFAULT_VIDEO_ROOT)) | |
| demo = getattr(args, "demo", None) | |
| if demo: | |
| return root / args.task / demo / "video" | |
| return root / args.task / "demo_clean_100" / "video" | |
| def resolve_raw_data_dir(task: str, demo: str, video_root: Path) -> Path: | |
| return video_root / task / demo / "data" | |
| def dataset_entries(label_root: Path, video_root: Path, validation_glob: str) -> list[dict]: | |
| entries = [] | |
| seen_keys: set[tuple[str, str, str, int]] = set() | |
| for root in label_root_search_paths(label_root): | |
| if not Path(root).is_dir(): | |
| continue | |
| for task_dir in sorted(Path(root).iterdir(), key=natural_key): | |
| if not task_dir.is_dir(): | |
| continue | |
| for demo_dir in sorted(task_dir.glob("demo_clean_100*"), key=natural_key): | |
| if not demo_dir.is_dir(): | |
| continue | |
| for kind_dir in sorted(demo_dir.iterdir(), key=natural_key): | |
| if not kind_dir.is_dir(): | |
| continue | |
| for val_idx, label_dir in enumerate(sorted(kind_dir.glob(validation_glob), key=natural_key)): | |
| if not label_dir.is_dir(): | |
| continue | |
| labels = sorted(label_dir.glob("episode_*.hdf5"), key=natural_key) | |
| if not labels: | |
| continue | |
| key = (task_dir.name, demo_dir.name, kind_dir.name, val_idx) | |
| if key in seen_keys: | |
| continue | |
| seen_keys.add(key) | |
| video_dir = Path(video_root) / task_dir.name / demo_dir.name / "video" | |
| videos = sorted(video_dir.glob("*.mp4"), key=natural_key) if video_dir.exists() else [] | |
| entries.append( | |
| { | |
| "task": task_dir.name, | |
| "demo": demo_dir.name, | |
| "label_kind": kind_dir.name, | |
| "label_dir": str(label_dir), | |
| "video_dir": str(video_dir), | |
| "label_count": len(labels), | |
| "video_count": len(videos), | |
| "has_video_dir": video_dir.exists(), | |
| "status": "ok" if len(labels) == len(videos) else "warn", | |
| } | |
| ) | |
| return entries | |
| def concat_episode_data( | |
| files: list[Path], | |
| indices: Iterable[int], | |
| feature_start: int, | |
| feature_end: int | None, | |
| ): | |
| xs = [] | |
| ys = [] | |
| for idx in indices: | |
| x = load_concept(files[int(idx)], feature_start, feature_end) | |
| xs.append(x) | |
| ys.append(progress_labels(x.shape[0])) | |
| return np.concatenate(xs, axis=0), np.concatenate(ys, axis=0) | |
| def list_task_demos(label_root: Path, task: str) -> list[str]: | |
| demos: set[str] = set() | |
| found_any = False | |
| for root in label_root_search_paths(label_root): | |
| task_dir = root / task | |
| if not task_dir.is_dir(): | |
| continue | |
| found_any = True | |
| for p in task_dir.iterdir(): | |
| if p.is_dir() and p.name.startswith("demo_clean_100"): | |
| demos.add(p.name) | |
| if not found_any: | |
| raise FileNotFoundError(f"Task directory not found for {task} under {label_root_search_paths(label_root)}") | |
| if not demos: | |
| raise FileNotFoundError(f"No demo_clean_100* for task={task}") | |
| return sorted(demos, key=natural_key) | |
| def resolve_kind_label_dir( | |
| label_root: Path, | |
| task: str, | |
| demo: str, | |
| label_kind: str, | |
| validation_glob: str = "validation-*-label", | |
| validation_index: int = 0, | |
| ) -> Path | None: | |
| for root in label_root_search_paths(label_root): | |
| kind_dir = root / task / demo / label_kind | |
| if not kind_dir.is_dir(): | |
| continue | |
| dirs = sorted(kind_dir.glob(validation_glob), key=natural_key) | |
| dirs = [d for d in dirs if d.is_dir()] | |
| if not dirs: | |
| continue | |
| if validation_index >= len(dirs): | |
| continue | |
| return dirs[validation_index] | |
| return None | |
| def ffprobe_video(path: Path) -> dict: | |
| cmd = [ | |
| "ffprobe", | |
| "-v", | |
| "error", | |
| "-select_streams", | |
| "v:0", | |
| "-show_entries", | |
| "stream=nb_frames,r_frame_rate,avg_frame_rate,width,height,duration", | |
| "-of", | |
| "json", | |
| str(path), | |
| ] | |
| try: | |
| result = subprocess.run(cmd, check=True, text=True, capture_output=True) | |
| stream = json.loads(result.stdout)["streams"][0] | |
| frames = stream.get("nb_frames") | |
| if frames is None or frames == "N/A": | |
| duration = float(stream.get("duration", 0.0) or 0.0) | |
| fps = parse_rate(stream.get("avg_frame_rate") or stream.get("r_frame_rate") or "0/1") | |
| frames = int(round(duration * fps)) if duration and fps else 0 | |
| return { | |
| "video_frames": int(frames), | |
| "video_fps": parse_rate(stream.get("avg_frame_rate") or stream.get("r_frame_rate") or "0/1"), | |
| "width": int(stream["width"]), | |
| "height": int(stream["height"]), | |
| "duration": float(stream.get("duration", 0.0) or 0.0), | |
| } | |
| except (FileNotFoundError, subprocess.CalledProcessError, KeyError, json.JSONDecodeError): | |
| return _video_meta_opencv_fallback(path) | |
| def _video_meta_opencv_fallback(path: Path) -> dict: | |
| import cv2 | |
| cap = cv2.VideoCapture(str(path)) | |
| if not cap.isOpened(): | |
| raise FileNotFoundError(f"Cannot open video: {path}") | |
| frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) | |
| fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) | |
| width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0) | |
| height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0) | |
| cap.release() | |
| duration = frames / fps if fps > 0 else 0.0 | |
| return { | |
| "video_frames": frames, | |
| "video_fps": fps, | |
| "width": width, | |
| "height": height, | |
| "duration": duration, | |
| } | |
| def parse_rate(rate: str) -> float: | |
| if "/" in rate: | |
| num, den = rate.split("/", 1) | |
| den_f = float(den) | |
| return float(num) / den_f if den_f else 0.0 | |
| return float(rate) | |
| def concept_steps(path: Path) -> int: | |
| with h5py.File(path, "r") as handle: | |
| return int(handle["concept"].shape[0]) | |
| def infer_alignment(concept_count: int, video_count: int, tolerance: float = 0.05) -> tuple[str, str]: | |
| if concept_count <= 0 or video_count <= 0: | |
| return "bad", "missing_count" | |
| ratio = video_count / concept_count | |
| nearest = round(ratio) | |
| if video_count == concept_count: | |
| return "ok", "one_to_one" | |
| if nearest >= 1 and abs(ratio - nearest) <= tolerance * max(1, nearest): | |
| return "ok", f"constant_ratio_{nearest}:1" | |
| if ratio > 1: | |
| return "warn", "linear_time_resample" | |
| return "warn", "video_shorter_than_concept" | |
| def concept_to_frame_index(t: int, concept_count: int, video_count: int) -> int: | |
| if concept_count <= 1 or video_count <= 1: | |
| return 0 | |
| return int(round(t / (concept_count - 1) * (video_count - 1))) | |
| def frame_to_concept_index(f: int, concept_count: int, video_count: int) -> int: | |
| if video_count <= 1 or concept_count <= 1: | |
| return 0 | |
| return int(round(f / (video_count - 1) * (concept_count - 1))) | |
| def concept_timesteps_to_video_frames(T: int, V: int) -> np.ndarray: | |
| if T <= 0: | |
| return np.array([], dtype=np.int32) | |
| if T == 1: | |
| return np.array([0], dtype=np.int32) | |
| if V <= 1: | |
| return np.zeros(T, dtype=np.int32) | |
| return np.round(np.arange(T) / (T - 1) * (V - 1)).astype(np.int32) | |
| def pair_episodes_by_id(labels: list[Path], videos: list[Path]) -> dict[int, tuple[Path, Path | None]]: | |
| video_by_idx = {episode_number(path): path for path in videos} | |
| pairs: dict[int, tuple[Path, Path | None]] = {} | |
| for label_path in labels: | |
| eid = episode_number(label_path) | |
| pairs[eid] = (label_path, video_by_idx.get(eid)) | |
| return pairs | |
| def resolve_episode_paths( | |
| task: str, | |
| demo: str, | |
| episode_id: int, | |
| label_root: Path, | |
| video_root: Path, | |
| label_kind: str | None = None, | |
| validation_index: int = 0, | |
| validation_glob: str = "validation-*-label", | |
| ) -> tuple[Path, Path, Path | None]: | |
| if label_kind: | |
| label_dir = resolve_kind_label_dir(label_root, task, demo, label_kind, validation_glob, validation_index) | |
| if label_dir is None: | |
| raise FileNotFoundError(f"No label dir for {task}/{demo}/{label_kind}") | |
| else: | |
| label_dir = None | |
| for kind in PILOT_LABEL_KINDS: | |
| label_dir = resolve_kind_label_dir(label_root, task, demo, kind, validation_glob, validation_index) | |
| if label_dir is not None: | |
| break | |
| if label_dir is None: | |
| raise FileNotFoundError(f"No label dir for {task}/{demo}") | |
| label_path = label_dir / f"{episode_label_stem(episode_id)}.hdf5" | |
| video_path = video_root / task / demo / "video" / episode_video_name(episode_id) | |
| if not label_path.exists(): | |
| raise FileNotFoundError(f"Label not found: {label_path}") | |
| if not video_path.exists(): | |
| raise FileNotFoundError(f"Video not found: {video_path}") | |
| return label_path, video_path, label_dir | |
| def status_counts(rows: list[dict]) -> dict[str, int]: | |
| counts: dict[str, int] = {} | |
| for row in rows: | |
| key = row.get("status", "unknown") | |
| counts[key] = counts.get(key, 0) + 1 | |
| return counts | |
| def remap_path(path: Path, old_root: Path, new_root: Path) -> Path: | |
| try: | |
| return new_root / path.relative_to(old_root) | |
| except ValueError: | |
| return path | |
| def read_video_frame(video_path: Path, frame_idx: int) -> Image.Image: | |
| import cv2 | |
| cap = cv2.VideoCapture(str(video_path)) | |
| if cap.isOpened(): | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx) | |
| ok, frame = cap.read() | |
| cap.release() | |
| if ok: | |
| return Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) | |
| try: | |
| with tempfile.TemporaryDirectory() as tmp: | |
| out = Path(tmp) / "frame.png" | |
| subprocess.run( | |
| [ | |
| "ffmpeg", | |
| "-v", | |
| "error", | |
| "-y", | |
| "-i", | |
| str(video_path), | |
| "-vf", | |
| f"select=eq(n\\,{frame_idx})", | |
| "-frames:v", | |
| "1", | |
| str(out), | |
| ], | |
| check=True, | |
| ) | |
| return Image.open(out).convert("RGB") | |
| except (FileNotFoundError, subprocess.CalledProcessError) as exc: | |
| raise RuntimeError(f"Cannot read frame {frame_idx} from {video_path}") from exc | |
| def iter_video_frames( | |
| video_path: Path, | |
| step: int = 1, | |
| max_frame: int | None = None, | |
| progress_every: int = 50, | |
| ) -> Iterable[tuple[int, Image.Image]]: | |
| """Read video frames sequentially with OpenCV (much faster than per-frame ffmpeg).""" | |
| import cv2 | |
| cap = cv2.VideoCapture(str(video_path)) | |
| if not cap.isOpened(): | |
| raise FileNotFoundError(f"Cannot open video: {video_path}") | |
| total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) | |
| end = min(total, max_frame) if max_frame is not None else total | |
| f = 0 | |
| while f < end: | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, f) | |
| ok, frame = cap.read() | |
| if not ok: | |
| break | |
| if progress_every and f % progress_every == 0: | |
| print(f"reading video frame {f}/{max(0, end - 1)}", flush=True) | |
| yield f, Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) | |
| f += step | |
| cap.release() | |
| def inspect_hdf5_group(handle, prefix: str = "") -> list[str]: | |
| lines = [] | |
| for key in handle.keys(): | |
| obj = handle[key] | |
| full_key = f"{prefix}{key}" | |
| if isinstance(obj, h5py.Group): | |
| lines.append(f"{full_key}/ (group)") | |
| for sub in obj.keys(): | |
| arr = obj[sub] | |
| if hasattr(arr, "shape"): | |
| lines.append(f" {full_key}/{sub}: shape={arr.shape} dtype={arr.dtype}") | |
| elif hasattr(obj, "shape"): | |
| lines.append(f"{full_key}: shape={obj.shape} dtype={obj.dtype}") | |
| return lines | |