Buckets:
| """Shared helpers for action-primitive (act_pri) labeling of LeRobot datasets. | |
| The vocabulary is the SARM2 action-primitive vocabulary (``config/act_pri.yaml`` | |
| -> ``model.task_list``). For this T-shirt folding dataset only four of those | |
| primitives are emitted, but indices always stay in the full vocabulary so labels | |
| drop straight into act_pri / sarm2 training. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import Dict, Iterable, List, Optional, Sequence | |
| from omegaconf import OmegaConf | |
| # --------------------------------------------------------------------------- # | |
| # vocabulary | |
| # --------------------------------------------------------------------------- # | |
| # Keep this fallback in sync with config/act_pri.yaml : cfg.model.task_list. | |
| DEFAULT_SARM2_TASK_LIST: List[str] = [ | |
| "clamp", | |
| "erase", | |
| "fold_flatten", | |
| "hang", | |
| "insert", | |
| "install", | |
| "pass", | |
| "pick_grab", | |
| "place", | |
| "pour_dump", | |
| "press", | |
| "pull", | |
| "roll", | |
| "rotate_turn", | |
| "scoop", | |
| "screw_unscrew", | |
| "sweep", | |
| "tie", | |
| "untie", | |
| "wrap", | |
| "zip_unzip", | |
| "dummy", | |
| ] | |
| def _load_task_list_from_config() -> List[str]: | |
| cfg_path = Path(__file__).resolve().parents[1] / "config" / "act_pri.yaml" | |
| try: | |
| cfg = OmegaConf.load(cfg_path) | |
| task_list = OmegaConf.to_container(cfg.cfg.model.task_list, resolve=True) | |
| if isinstance(task_list, list) and all(isinstance(x, str) for x in task_list): | |
| return task_list | |
| except Exception: | |
| pass | |
| return list(DEFAULT_SARM2_TASK_LIST) | |
| SARM2_TASK_LIST: List[str] = _load_task_list_from_config() | |
| TASK_TO_INDEX: Dict[str, int] = {name: i for i, name in enumerate(SARM2_TASK_LIST)} | |
| # Keep in sync with config/act_pri.yaml : cfg.model.class_list (num_class = 8), | |
| # used as the MoE gate index by sarm2. | |
| SARM2_CLASS_LIST: List[str] = [ | |
| "pick_grab or scoop or pull", | |
| "place or pour_dump", | |
| "erase or zip_unzip or sweep or pass", | |
| "install or insert or assembly or load", | |
| "fold_flatten or hang", | |
| "rotate_turn or screw_unscrew or tie or wrap or untie or roll", | |
| "press or clamp", | |
| "dummy", | |
| ] | |
| def task_to_class_id(task: str) -> int: | |
| """Map a primitive name onto its SARM2 MoE gate (class) index.""" | |
| for class_id, group in enumerate(SARM2_CLASS_LIST): | |
| if task in [t.strip() for t in group.split(" or ")]: | |
| return class_id | |
| return len(SARM2_CLASS_LIST) - 1 # dummy / fallback gate | |
| # The four primitives this T-shirt pipeline is allowed to emit. | |
| PRIMITIVES: List[str] = ["pick_grab", "fold_flatten", "place", "dummy"] | |
| PRIMITIVE_DESCRIPTIONS: Dict[str, str] = { | |
| "pick_grab": "an arm approaches, reaches for, pinches or grabs the cloth", | |
| "fold_flatten": "an arm folds a sleeve onto the shirt, or folds / flattens the bottom half of the shirt", | |
| "place": "an arm places or settles the cloth at the target location", | |
| "dummy": "the arms are idle, retreating or not manipulating the cloth", | |
| } | |
| ANNOTATOR_MODEL_ID = "Qwen/Qwen3-VL-8B-Instruct" | |
| ANNOTATOR_SAMPLE_FRAMES = 48 | |
| ANNOTATOR_STORYBOARD_ROWS = 4 | |
| ANNOTATOR_STORYBOARD_COLS = 4 | |
| ANNOTATOR_STORYBOARD_CELL_EDGE = 224 | |
| # Tolerated spellings coming from the CLI / web UI / older annotation files. | |
| PRIMITIVE_ALIASES: Dict[str, str] = { | |
| "prick_grab": "pick_grab", | |
| "pick_grasp": "pick_grab", | |
| "pick-grab": "pick_grab", | |
| "pickgrab": "pick_grab", | |
| "pick": "pick_grab", | |
| "grab": "pick_grab", | |
| "fold-flatten": "fold_flatten", | |
| "foldflatten": "fold_flatten", | |
| "fold": "fold_flatten", | |
| "flatten": "fold_flatten", | |
| "put": "place", | |
| "set_down": "place", | |
| "setdown": "place", | |
| "drop": "place", | |
| "none": "dummy", | |
| "idle": "dummy", | |
| "null": "dummy", | |
| } | |
| def canonical_primitive(name: str) -> Optional[str]: | |
| """Normalize a free-form label to one of PRIMITIVES (or None if unknown).""" | |
| if name is None: | |
| return None | |
| key = str(name).strip().strip(".\"'` ").lower().replace(" ", "_") | |
| if key in PRIMITIVES: | |
| return key | |
| return PRIMITIVE_ALIASES.get(key) | |
| def primitive_index(name: str) -> int: | |
| """SARM2 vocabulary index for a primitive name.""" | |
| canon = canonical_primitive(name) | |
| if canon is None: | |
| raise ValueError(f"unknown primitive: {name!r}") | |
| return TASK_TO_INDEX[canon] | |
| def write_vocab(path: Path) -> None: | |
| payload = { | |
| "task_list": SARM2_TASK_LIST, | |
| "index": TASK_TO_INDEX, | |
| "class_list": SARM2_CLASS_LIST, | |
| "used_primitives": {p: TASK_TO_INDEX[p] for p in PRIMITIVES}, | |
| "used_primitive_gate": {p: task_to_class_id(p) for p in PRIMITIVES}, | |
| } | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(payload, indent=1)) | |
| # --------------------------------------------------------------------------- # | |
| # dataset introspection (LeRobot v2.x and v3.0 layouts) | |
| # --------------------------------------------------------------------------- # | |
| class VideoRef: | |
| """Where an episode's frames live inside a (possibly aggregated) mp4.""" | |
| path: Path | |
| start_time: float # timestamp of the episode's frame 0 within that file | |
| class EpisodeMeta: | |
| index: int | |
| length: int | |
| from_index: int # first row of this episode in the global data table | |
| to_index: int # one past the last row | |
| task: str | |
| videos: Dict[str, VideoRef] = field(default_factory=dict) | |
| class DatasetMeta: | |
| root: Path | |
| name: str | |
| codebase_version: str | |
| fps: float | |
| camera_keys: List[str] | |
| episodes: List[EpisodeMeta] | |
| total_frames: int | |
| def episode(self, index: int) -> EpisodeMeta: | |
| for ep in self.episodes: | |
| if ep.index == index: | |
| return ep | |
| raise KeyError(f"episode {index} not in dataset {self.name}") | |
| def _read_episode_rows_v30(root: Path) -> List[dict]: | |
| import pyarrow.parquet as pq | |
| files = sorted((root / "meta" / "episodes").rglob("*.parquet")) | |
| if not files: | |
| raise FileNotFoundError(f"no meta/episodes/**.parquet under {root}") | |
| rows: List[dict] = [] | |
| for f in files: | |
| table = pq.read_table(f) | |
| keep = [ | |
| c | |
| for c in table.column_names | |
| if not c.startswith("stats/") # per-episode stats are huge and unused here | |
| ] | |
| rows.extend(table.select(keep).to_pylist()) | |
| rows.sort(key=lambda r: r["episode_index"]) | |
| return rows | |
| V3_VIDEO_TEMPLATE = "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4" | |
| def _has_v3_episode_meta(root: Path) -> bool: | |
| return bool(list((root / "meta" / "episodes").rglob("*.parquet"))) if ( | |
| root / "meta" / "episodes" | |
| ).is_dir() else False | |
| def load_dataset_meta(root: Path, video_layout: str = "auto") -> DatasetMeta: | |
| """Read info.json + episode metadata for a LeRobot dataset directory. | |
| `video_layout` selects where frames are read from: | |
| * ``"v3"`` - aggregated per-camera mp4s addressed by the per-episode | |
| ``chunk_index`` / ``file_index`` / ``from_timestamp`` in | |
| ``meta/episodes/**.parquet``. | |
| * ``"v2"`` - one mp4 per episode per camera, via ``info.json``'s template. | |
| * ``"auto"`` (default) - v3 whenever that metadata and those files exist, | |
| otherwise v2. | |
| Auto deliberately prefers v3 even when ``info.json`` declares v2.0: datasets | |
| converted between the two can ship *both* layouts, and the per-episode files | |
| are the ones that go stale. In cloth_folder's 171909 session, episodes 26-40 | |
| have their `left_top` frames in `file-001`, and the per-episode `left_top` | |
| mp4s for those episodes contain a different episode's footage entirely, | |
| while the aggregated files are correct and camera-synchronized. | |
| """ | |
| root = Path(root).expanduser().resolve() | |
| info = json.loads((root / "meta" / "info.json").read_text()) | |
| fps = float(info["fps"]) | |
| version = str(info.get("codebase_version", "v2.0")) | |
| camera_keys = [ | |
| key | |
| for key, feat in info["features"].items() | |
| if feat.get("dtype") in ("video", "image") | |
| ] | |
| video_path_tpl = info["video_path"] | |
| chunks_size = int(info.get("chunks_size", 1000)) | |
| v3_rows = _read_episode_rows_v30(root) if _has_v3_episode_meta(root) else None | |
| v3_tpl = video_path_tpl if "{file_index" in video_path_tpl else V3_VIDEO_TEMPLATE | |
| def v3_video_ref(row: dict, cam: str) -> VideoRef: | |
| return VideoRef( | |
| path=root | |
| / v3_tpl.format( | |
| video_key=cam, | |
| chunk_index=int(row[f"videos/{cam}/chunk_index"]), | |
| file_index=int(row[f"videos/{cam}/file_index"]), | |
| ), | |
| start_time=float(row[f"videos/{cam}/from_timestamp"]), | |
| ) | |
| if video_layout not in ("auto", "v2", "v3"): | |
| raise ValueError(f"video_layout must be auto/v2/v3, got {video_layout!r}") | |
| use_v3_video = video_layout == "v3" | |
| if video_layout == "auto" and v3_rows: | |
| use_v3_video = all( | |
| v3_video_ref(v3_rows[0], cam).path.is_file() for cam in camera_keys | |
| ) | |
| if use_v3_video and not v3_rows: | |
| raise SystemExit(f"{root}: video_layout=v3 needs meta/episodes/**.parquet") | |
| episodes: List[EpisodeMeta] = [] | |
| if v3_rows: | |
| for row in v3_rows: | |
| ep_index = int(row["episode_index"]) | |
| tasks = row.get("tasks") or [] | |
| task = tasks[0] if isinstance(tasks, (list, tuple)) and tasks else str(tasks) | |
| if use_v3_video: | |
| videos = {cam: v3_video_ref(row, cam) for cam in camera_keys} | |
| else: | |
| videos = { | |
| cam: VideoRef( | |
| path=root | |
| / video_path_tpl.format( | |
| episode_chunk=ep_index // chunks_size, | |
| video_key=cam, | |
| episode_index=ep_index, | |
| ), | |
| start_time=0.0, | |
| ) | |
| for cam in camera_keys | |
| } | |
| episodes.append( | |
| EpisodeMeta( | |
| index=ep_index, | |
| length=int(row["length"]), | |
| from_index=int(row["dataset_from_index"]), | |
| to_index=int(row["dataset_to_index"]), | |
| task=task, | |
| videos=videos, | |
| ) | |
| ) | |
| else: | |
| # ---- v2.x only: one parquet + one mp4 per episode, videos start at t=0 | |
| jsonl = root / "meta" / "episodes.jsonl" | |
| if not jsonl.exists(): | |
| raise FileNotFoundError(f"missing {jsonl}") | |
| cursor = 0 | |
| for line in jsonl.read_text().splitlines(): | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| ep_index = int(row["episode_index"]) | |
| length = int(row["length"]) | |
| tasks = row.get("tasks") or [] | |
| task = tasks[0] if isinstance(tasks, (list, tuple)) and tasks else str(tasks) | |
| videos = { | |
| cam: VideoRef( | |
| path=root | |
| / video_path_tpl.format( | |
| episode_chunk=ep_index // chunks_size, | |
| video_key=cam, | |
| episode_index=ep_index, | |
| ), | |
| start_time=0.0, | |
| ) | |
| for cam in camera_keys | |
| } | |
| episodes.append( | |
| EpisodeMeta( | |
| index=ep_index, | |
| length=length, | |
| from_index=cursor, | |
| to_index=cursor + length, | |
| task=task, | |
| videos=videos, | |
| ) | |
| ) | |
| cursor += length | |
| episodes.sort(key=lambda e: e.index) | |
| return DatasetMeta( | |
| root=root, | |
| name=root.name, | |
| codebase_version=version, | |
| fps=fps, | |
| camera_keys=camera_keys, | |
| episodes=episodes, | |
| total_frames=int(info.get("total_frames", sum(e.length for e in episodes))), | |
| ) | |
| # --------------------------------------------------------------------------- # | |
| # grouping: one label per `group_seconds` of recorded frames | |
| # --------------------------------------------------------------------------- # | |
| class Group: | |
| group_index: int | |
| start_frame: int # inclusive, episode-local | |
| end_frame: int # inclusive, episode-local | |
| key_frame: int # the frame whose camera images are shown to the VLM | |
| def num_frames(self) -> int: | |
| return self.end_frame - self.start_frame + 1 | |
| def group_size_for(fps: float, group_seconds: float) -> int: | |
| """Frames per label group; one recording-frequency cycle = `fps` frames.""" | |
| return max(1, int(round(fps * group_seconds))) | |
| def build_groups( | |
| num_frames: int, group_size: int, key_position: str = "mid" | |
| ) -> List[Group]: | |
| """Split an episode into consecutive, non-overlapping groups of frames. | |
| Exactly one label is produced per group, so no two VLM queries ever land | |
| inside the same recording-frequency cycle. | |
| """ | |
| groups: List[Group] = [] | |
| for g, start in enumerate(range(0, num_frames, group_size)): | |
| end = min(start + group_size, num_frames) - 1 | |
| if key_position == "start": | |
| key = start | |
| elif key_position == "end": | |
| key = end | |
| else: # "mid" | |
| key = start + (end - start) // 2 | |
| groups.append(Group(group_index=g, start_frame=start, end_frame=end, key_frame=key)) | |
| return groups | |
| def expand_groups_to_frames( | |
| groups: Sequence[dict], num_frames: int, default_index: int = TASK_TO_INDEX["dummy"] | |
| ) -> "list[int]": | |
| """Per-frame act_pri indices at the dataset's native frequency.""" | |
| per_frame = [default_index] * num_frames | |
| for grp in groups: | |
| idx = int(grp.get("label_index", default_index)) | |
| for f in range(int(grp["start_frame"]), min(int(grp["end_frame"]) + 1, num_frames)): | |
| per_frame[f] = idx | |
| return per_frame | |
| def segments_from_per_frame(per_frame: Sequence[int], fps: float) -> List[dict]: | |
| """Run-length encode per-frame indices into readable segments.""" | |
| segments: List[dict] = [] | |
| if not per_frame: | |
| return segments | |
| start = 0 | |
| for i in range(1, len(per_frame) + 1): | |
| if i == len(per_frame) or per_frame[i] != per_frame[start]: | |
| segments.append( | |
| { | |
| "start_frame": start, | |
| "end_frame": i - 1, | |
| "start_time": round(start / fps, 3), | |
| "end_time": round((i - 1) / fps, 3), | |
| "primitive": SARM2_TASK_LIST[per_frame[start]], | |
| "primitive_index": int(per_frame[start]), | |
| } | |
| ) | |
| start = i | |
| return segments | |
| def smooth_labels(labels: List[str], window: int) -> List[str]: | |
| """Majority filter over consecutive groups (window must be odd, >= 3).""" | |
| if window < 3 or window % 2 == 0 or len(labels) < window: | |
| return list(labels) | |
| half = window // 2 | |
| out = list(labels) | |
| for i in range(len(labels)): | |
| lo, hi = max(0, i - half), min(len(labels), i + half + 1) | |
| chunk = labels[lo:hi] | |
| out[i] = max(set(chunk), key=chunk.count) | |
| return out | |
| def sample_episode_frames(num_frames: int, max_samples: int) -> List[int]: | |
| """Uniform sample positions for episode-level Qwen context.""" | |
| if num_frames <= 0: | |
| return [0] | |
| if max_samples <= 1 or num_frames == 1: | |
| return [0] | |
| if num_frames <= max_samples: | |
| return list(range(num_frames)) | |
| step = (num_frames - 1) / float(max_samples - 1) | |
| samples = sorted({int(round(i * step)) for i in range(max_samples)}) | |
| if samples[0] != 0: | |
| samples[0] = 0 | |
| if samples[-1] != num_frames - 1: | |
| samples[-1] = num_frames - 1 | |
| return samples | |
| def sanitize_episode_segments(segments: Sequence[dict], num_frames: int) -> List[dict]: | |
| """Clamp, sort, densify, and merge semantic segments to cover the episode.""" | |
| if num_frames <= 0: | |
| return [ | |
| { | |
| "start_frame": 0, | |
| "end_frame": 0, | |
| "label": "dummy", | |
| "confidence": 0.0, | |
| "evidence": "empty episode", | |
| } | |
| ] | |
| cleaned: List[dict] = [] | |
| for seg in segments: | |
| label = canonical_primitive(seg.get("label")) or "dummy" | |
| start_frame = max(0, min(num_frames - 1, int(seg.get("start_frame", 0)))) | |
| end_frame = max(0, min(num_frames - 1, int(seg.get("end_frame", start_frame)))) | |
| if end_frame < start_frame: | |
| start_frame, end_frame = end_frame, start_frame | |
| cleaned.append( | |
| { | |
| "start_frame": start_frame, | |
| "end_frame": end_frame, | |
| "label": label, | |
| "confidence": max(0.0, min(1.0, float(seg.get("confidence", 0.0) or 0.0))), | |
| "evidence": str(seg.get("evidence", "")).strip(), | |
| } | |
| ) | |
| if not cleaned: | |
| cleaned = [ | |
| { | |
| "start_frame": 0, | |
| "end_frame": num_frames - 1, | |
| "label": "dummy", | |
| "confidence": 0.0, | |
| "evidence": "fallback", | |
| } | |
| ] | |
| cleaned.sort(key=lambda s: (s["start_frame"], s["end_frame"])) | |
| cleaned[0]["start_frame"] = 0 | |
| cleaned[-1]["end_frame"] = num_frames - 1 | |
| for i in range(len(cleaned) - 1): | |
| left = cleaned[i] | |
| right = cleaned[i + 1] | |
| boundary = int(round((int(left["end_frame"]) + int(right["start_frame"]) - 1) / 2.0)) | |
| boundary = max(int(left["start_frame"]), min(boundary, num_frames - 2)) | |
| left["end_frame"] = boundary | |
| right["start_frame"] = boundary + 1 | |
| merged: List[dict] = [] | |
| for seg in cleaned: | |
| if merged and merged[-1]["label"] == seg["label"] and int(seg["start_frame"]) <= int(merged[-1]["end_frame"]) + 1: | |
| prev = merged[-1] | |
| prev["end_frame"] = max(int(prev["end_frame"]), int(seg["end_frame"])) | |
| prev["confidence"] = max(float(prev["confidence"]), float(seg["confidence"])) | |
| evidence = [x for x in [prev.get("evidence", ""), seg.get("evidence", "")] if x] | |
| prev["evidence"] = " | ".join(dict.fromkeys(evidence)) | |
| else: | |
| merged.append(dict(seg)) | |
| return merged | |
| def qwen_segments_for(group: dict) -> List[dict]: | |
| """Normalized Qwen proposal spans stored alongside editable human segments.""" | |
| spans = group.get("qwen_segments") or group.get("qwen_proposal") or [ | |
| { | |
| "start_frame": int(group["start_frame"]), | |
| "end_frame": int(group["end_frame"]), | |
| "label": canonical_primitive(group.get("qwen_label") or group.get("pred") or group.get("label")) or "dummy", | |
| "confidence": float(group.get("qwen_confidence", group.get("confidence", 0.0)) or 0.0), | |
| "evidence": str(group.get("qwen_evidence", "")).strip(), | |
| } | |
| ] | |
| out = [] | |
| for span in spans: | |
| out.append( | |
| { | |
| "start_frame": int(span["start_frame"]), | |
| "end_frame": int(span["end_frame"]), | |
| "label": canonical_primitive(span.get("label")) or "dummy", | |
| "confidence": max(0.0, min(1.0, float(span.get("confidence", 0.0) or 0.0))), | |
| "evidence": str(span.get("evidence", "")).strip(), | |
| } | |
| ) | |
| out.sort(key=lambda s: (int(s["start_frame"]), int(s["end_frame"]))) | |
| return out | |
| def summarize_qwen_segments(spans: Sequence[dict]) -> tuple[str, float]: | |
| """Duration-weighted dominant Qwen label and average confidence.""" | |
| if not spans: | |
| return "dummy", 0.0 | |
| weights: Dict[str, int] = {} | |
| total_conf = 0.0 | |
| total_frames = 0 | |
| for span in spans: | |
| label = canonical_primitive(span.get("label")) or "dummy" | |
| length = max(1, int(span["end_frame"]) - int(span["start_frame"]) + 1) | |
| weights[label] = weights.get(label, 0) + length | |
| total_conf += float(span.get("confidence", 0.0) or 0.0) * length | |
| total_frames += length | |
| qwen_label = max(weights.items(), key=lambda kv: (kv[1], kv[0]))[0] | |
| qwen_conf = total_conf / max(1, total_frames) | |
| return qwen_label, max(0.0, min(1.0, qwen_conf)) | |
| def clip_qwen_segments(spans: Sequence[dict], start_frame: int, end_frame: int) -> List[dict]: | |
| """Clip Qwen proposal spans to an edited human segment boundary range.""" | |
| clipped: List[dict] = [] | |
| for span in qwen_segments_for({"start_frame": start_frame, "end_frame": end_frame, "qwen_segments": list(spans)}): | |
| lo = max(int(span["start_frame"]), int(start_frame)) | |
| hi = min(int(span["end_frame"]), int(end_frame)) | |
| if lo > hi: | |
| continue | |
| clipped.append( | |
| { | |
| "start_frame": lo, | |
| "end_frame": hi, | |
| "label": span["label"], | |
| "confidence": span["confidence"], | |
| "evidence": span.get("evidence", ""), | |
| } | |
| ) | |
| return clipped | |
| def merge_adjacent_segments(groups: Sequence[dict], fps: float) -> List[dict]: | |
| """Merge touching segments that share the same editable human label.""" | |
| ordered = sorted(groups, key=lambda g: (int(g["start_frame"]), int(g["end_frame"]))) | |
| merged: List[dict] = [] | |
| for group in ordered: | |
| label = canonical_primitive(group.get("label")) or "dummy" | |
| current = dict(group) | |
| current["label"] = label | |
| current["qwen_segments"] = qwen_segments_for(group) | |
| if merged and merged[-1]["label"] == label and int(current["start_frame"]) <= int(merged[-1]["end_frame"]) + 1: | |
| prev = merged[-1] | |
| prev_q_label, _ = summarize_qwen_segments(prev.get("qwen_segments") or []) | |
| curr_q_label, _ = summarize_qwen_segments(current.get("qwen_segments") or []) | |
| keep_qwen_source = ( | |
| prev.get("source", "qwen") == "qwen" | |
| and current.get("source", "qwen") == "qwen" | |
| and prev["label"] == prev_q_label | |
| and current["label"] == curr_q_label | |
| ) | |
| prev["end_frame"] = max(int(prev["end_frame"]), int(current["end_frame"])) | |
| prev["qwen_segments"] = qwen_segments_for(prev) + current["qwen_segments"] | |
| prev["source"] = "qwen" if keep_qwen_source else "human" | |
| prev["reviewed"] = bool(prev.get("reviewed") or current.get("reviewed")) | |
| else: | |
| merged.append(current) | |
| for i, group in enumerate(merged): | |
| start_frame = int(group["start_frame"]) | |
| end_frame = int(group["end_frame"]) | |
| qwen_label, qwen_conf = summarize_qwen_segments(group.get("qwen_segments") or []) | |
| group["segment_id"] = i | |
| group["group_index"] = i | |
| group["start_frame"] = start_frame | |
| group["end_frame"] = end_frame | |
| group["num_frames"] = max(0, end_frame - start_frame + 1) | |
| group["start_time"] = round(start_frame / fps, 3) | |
| group["end_time"] = round(end_frame / fps, 3) | |
| group["label_index"] = TASK_TO_INDEX[group["label"]] | |
| group["qwen_label"] = qwen_label | |
| group["qwen_label_index"] = TASK_TO_INDEX[qwen_label] | |
| group["qwen_confidence"] = qwen_conf | |
| group["pred"] = qwen_label | |
| group["pred_index"] = TASK_TO_INDEX[qwen_label] | |
| group["qwen_evidence"] = " | ".join( | |
| [span.get("evidence", "") for span in group.get("qwen_segments") or [] if span.get("evidence")] | |
| ) | |
| group["final_human_label"] = group["label"] | |
| group["final_human_start_frame"] = start_frame | |
| group["final_human_end_frame"] = end_frame | |
| group["modified"] = bool(group.get("source") == "human" or group["label"] != qwen_label) | |
| if group.get("source") not in ("qwen", "human"): | |
| group["source"] = "human" if group["modified"] else "qwen" | |
| group["reviewed"] = bool(group.get("reviewed", group["source"] == "human")) | |
| return merged | |
| # --------------------------------------------------------------------------- # | |
| # on-disk layout of the label store (shared by the CLI and the review UI) | |
| # --------------------------------------------------------------------------- # | |
| def groups_path(out_dir: Path, episode_index: int) -> Path: | |
| return Path(out_dir) / "groups" / f"episode_{episode_index:06d}.json" | |
| def per_frame_path(out_dir: Path, episode_index: int) -> Path: | |
| return Path(out_dir) / "per_frame" / f"episode_{episode_index:06d}.npy" | |
| def images_dir(out_dir: Path, episode_index: int) -> Path: | |
| return Path(out_dir) / "images" / f"episode_{episode_index:06d}" | |
| def list_episode_files(out_dir: Path) -> List[Path]: | |
| return sorted((Path(out_dir) / "groups").glob("episode_*.json")) | |
| def load_episode_labels(out_dir: Path, episode_index: int) -> dict: | |
| return json.loads(groups_path(out_dir, episode_index).read_text()) | |
| def save_episode_labels(out_dir: Path, payload: dict) -> None: | |
| path = groups_path(out_dir, int(payload["episode_index"])) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_suffix(".json.tmp") | |
| tmp.write_text(json.dumps(payload, indent=1)) | |
| tmp.replace(path) | |
| def write_per_frame(out_dir: Path, payload: dict) -> "object": | |
| """Expand group labels to one index per recorded frame and store as .npy.""" | |
| import numpy as np | |
| per_frame = expand_groups_to_frames(payload["groups"], int(payload["num_frames"])) | |
| arr = np.asarray(per_frame, dtype=np.int64) | |
| path = per_frame_path(out_dir, int(payload["episode_index"])) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| np.save(path, arr) | |
| return arr | |
| def export_act_pri_parquet(out_dir: Path, dataset_root: Optional[Path] = None) -> Path: | |
| """Merge every labeled episode into one row-aligned act_pri sidecar table. | |
| One row per recorded frame, in dataset row order, so step 2 can attach the | |
| `act_pri` column straight onto the LeRobot data parquet. | |
| """ | |
| import numpy as np | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| out_dir = Path(out_dir) | |
| rows_index: List[int] = [] | |
| rows_episode: List[int] = [] | |
| rows_frame: List[int] = [] | |
| rows_act: List[int] = [] | |
| payloads = [] | |
| for f in list_episode_files(out_dir): | |
| payloads.append(json.loads(f.read_text())) | |
| payloads.sort(key=lambda p: int(p["episode_index"])) | |
| for payload in payloads: | |
| ep = int(payload["episode_index"]) | |
| n = int(payload["num_frames"]) | |
| from_index = int(payload.get("dataset_from_index", 0)) | |
| per_frame = expand_groups_to_frames(payload["groups"], n) | |
| for i, value in enumerate(per_frame): | |
| rows_index.append(from_index + i) | |
| rows_episode.append(ep) | |
| rows_frame.append(i) | |
| rows_act.append(int(value)) | |
| table = pa.table( | |
| { | |
| "index": pa.array(rows_index, type=pa.int64()), | |
| "episode_index": pa.array(rows_episode, type=pa.int64()), | |
| "frame_index": pa.array(rows_frame, type=pa.int64()), | |
| "act_pri": pa.array(rows_act, type=pa.int64()), | |
| "act_pri_name": pa.array( | |
| [SARM2_TASK_LIST[v] for v in rows_act], type=pa.string() | |
| ), | |
| } | |
| ) | |
| path = out_dir / "act_pri.parquet" | |
| pq.write_table(table, path) | |
| # human-readable mirror of the same information | |
| summary = { | |
| "dataset_root": str(dataset_root) if dataset_root else None, | |
| "num_episodes": len(payloads), | |
| "num_frames": len(rows_act), | |
| "vocab": "SARM2 act_pri (22 classes)", | |
| "frame_counts": { | |
| name: int(np.sum(np.asarray(rows_act) == TASK_TO_INDEX[name])) | |
| for name in PRIMITIVES | |
| }, | |
| "group_counts": { | |
| name: sum( | |
| 1 | |
| for p in payloads | |
| for g in p["groups"] | |
| if g.get("label") == name | |
| ) | |
| for name in PRIMITIVES | |
| }, | |
| "modified_groups": sum( | |
| 1 for p in payloads for g in p["groups"] if g.get("modified") | |
| ), | |
| "reviewed_groups": sum( | |
| 1 for p in payloads for g in p["groups"] if g.get("reviewed") | |
| ), | |
| "total_groups": sum(len(p["groups"]) for p in payloads), | |
| "episodes": [ | |
| { | |
| "episode_index": int(p["episode_index"]), | |
| "num_frames": int(p["num_frames"]), | |
| "num_groups": len(p["groups"]), | |
| "modified": sum(1 for g in p["groups"] if g.get("modified")), | |
| "segments": segments_from_per_frame( | |
| expand_groups_to_frames(p["groups"], int(p["num_frames"])), | |
| float(p.get("fps", 15.0)), | |
| ), | |
| } | |
| for p in payloads | |
| ], | |
| } | |
| (out_dir / "summary.json").write_text(json.dumps(summary, indent=1)) | |
| return path | |
| def rebuild_all_exports(out_dir: Path, dataset_root: Optional[Path] = None) -> Path: | |
| """Refresh per-frame .npy files and the merged parquet from the group JSONs.""" | |
| out_dir = Path(out_dir) | |
| for f in list_episode_files(out_dir): | |
| write_per_frame(out_dir, json.loads(f.read_text())) | |
| return export_act_pri_parquet(out_dir, dataset_root) | |
Xet Storage Details
- Size:
- 29.4 kB
- Xet hash:
- ffaa3b328c06104ec0903f1b2db4e55b660516c0810950ac25722197afb2289e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.