File size: 6,155 Bytes
d350c08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#!/usr/bin/env python3
"""Training-oriented loader example for one package.

The script locates the files most users need for model or robot training:
RGB/depth timelines, corrected EMG/IMU, semantic subtasks, contact-force tables,
and standard gold exports. It uses only the standard library by default. If
pandas + pyarrow are installed, it also previews parquet schemas/rows.
"""
from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path
from typing import Iterable

try:
    import pandas as pd  # type: ignore
except Exception:  # pragma: no cover - optional dependency
    pd = None

CORE_PATHS = {
    "rgb_timeline": "clean/timeline/rgb_frame_index.parquet",
    "depth_timeline": "clean/timeline/depth_frame_index.parquet",
    "frame_pairs": "clean/timeline/frame_pair_index.parquet",
    "left_emg": "clean/sensors/left_emg_corrected.parquet",
    "right_emg": "clean/sensors/right_emg_corrected.parquet",
    "left_imu": "clean/sensors/left_imu_corrected.parquet",
    "right_imu": "clean/sensors/right_imu_corrected.parquet",
    "d455_imu": "clean/sensors/d455_imu.parquet",
    "episode_manifest": "gold/episode_manifest.parquet",
    "emg_features": "gold/emg_feat.parquet",
    "labels": "gold/labels.parquet",
    "robomimic": "gold/robomimic.hdf5",
    "rlds_episodes": "gold/rlds/train/episodes.jsonl",
    "contact_force_long": "analysis/contact_force_v2/tables/contact_force_v2_long.parquet",
    "contact_force_wide": "analysis/contact_force_v2/tables/contact_force_v2_wide.parquet",
    "semantic_segments": "analysis/semantic_subtasks/subtask_segments.jsonl",
    "semantic_labels": "analysis/semantic_subtasks/semantic_labels.jsonl",
}


def read_viewer_index(dataset_root: Path) -> list[dict[str, str]]:
    index_path = dataset_root / "viewer" / "train.csv"
    with index_path.open("r", encoding="utf-8-sig", newline="") as f:
        return list(csv.DictReader(f))


def resolve_package(dataset_root: Path, package_id: str) -> tuple[Path, dict[str, str]]:
    for row in read_viewer_index(dataset_root):
        if row["package_id"] == package_id:
            return dataset_root / row.get("package_path", f"packages/{package_id}"), row
    raise KeyError(f"Package id not found in viewer/train.csv: {package_id}")


def file_size(path: Path) -> str:
    if not path.exists():
        return "missing"
    size = path.stat().st_size
    for unit in ["B", "KB", "MB", "GB"]:
        if size < 1024 or unit == "GB":
            return f"{size:.1f} {unit}" if unit != "B" else f"{size} B"
        size /= 1024
    return f"{size:.1f} GB"


def iter_jsonl(path: Path, limit: int) -> Iterable[dict[str, object]]:
    with path.open("r", encoding="utf-8") as f:
        for i, line in enumerate(f):
            if i >= limit:
                break
            if line.strip():
                yield json.loads(line)


def preview_table(path: Path, max_rows: int) -> None:
    print(f"\nPreview: {path}")
    if not path.exists():
        print("  missing")
        return
    suffix = path.suffix.lower()
    if suffix == ".jsonl":
        rows = list(iter_jsonl(path, max_rows))
        print(f"  jsonl rows shown: {len(rows)}")
        if rows:
            print(f"  columns: {', '.join(rows[0].keys())}")
            print(f"  first row: {json.dumps(rows[0], ensure_ascii=False)[:800]}")
        return
    if suffix == ".csv":
        with path.open("r", encoding="utf-8-sig", newline="") as f:
            reader = csv.DictReader(f)
            rows = [row for _, row in zip(range(max_rows), reader)]
        print(f"  csv rows shown: {len(rows)}")
        if rows:
            print(f"  columns: {', '.join(rows[0].keys())}")
            print(f"  first row: {json.dumps(rows[0], ensure_ascii=False)[:800]}")
        return
    if suffix == ".parquet":
        if pd is None:
            print("  parquet preview skipped: install pandas and pyarrow to read parquet")
            print(f"  size: {file_size(path)}")
            return
        df = pd.read_parquet(path)
        print(f"  shape: {df.shape}")
        print(f"  columns: {', '.join(map(str, df.columns[:30]))}")
        if len(df):
            print(df.head(max_rows).to_string(index=False))
        return
    print(f"  binary or unsupported preview type; size: {file_size(path)}")


def main() -> None:
    parser = argparse.ArgumentParser(description="Load one package for training-oriented inspection.")
    parser.add_argument("--dataset-root", default=".", help="Dataset repository root")
    parser.add_argument("--package-id", default="hand-cream-application", help="Package id from viewer/train.csv")
    parser.add_argument("--max-rows", type=int, default=3, help="Rows to preview for readable tables")
    args = parser.parse_args()

    dataset_root = Path(args.dataset_root).expanduser().resolve()
    package_dir, row = resolve_package(dataset_root, args.package_id)

    print(f"Dataset root: {dataset_root}")
    print(f"Package: {args.package_id}")
    print(f"Task: {row.get('task_name', '')}")
    print(f"Description: {row.get('task_description', '')}")
    print(f"Package dir: {package_dir}")
    print()
    print(f"{'name':24} {'status':>12} path")
    print("-" * 92)
    for name, rel in CORE_PATHS.items():
        path = package_dir / rel
        print(f"{name:24} {file_size(path):>12} {rel}")

    # These previews are the usual starting points for downstream training code.
    for key in ["semantic_segments", "semantic_labels", "rlds_episodes", "contact_force_long", "rgb_timeline", "left_emg"]:
        preview_table(package_dir / CORE_PATHS[key], args.max_rows)

    print("\nSuggested training entry points:")
    print("  1. Use clean/timeline/rgb_frame_index.parquet as the RGB frame clock.")
    print("  2. Join corrected EMG/IMU by corrected timestamp or nearest RGB frame index.")
    print("  3. Read semantic_subtasks for action segments and clips.")
    print("  4. Read contact_force_v2 tables for per-finger contact and force labels.")
    print("  5. Use gold/rlds or gold/robomimic.hdf5 when your training stack supports them.")


if __name__ == "__main__":
    main()