File size: 8,043 Bytes
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""Choose recording directories without mixing incompatible hand layouts.

Stdlib only: collection and the task queue must select the same dataset.

Two things make a dataset's layout: which HANDS drove it (one 7-float wrist
pose per hand in `observation.wrist_pose`, the free roots first in
`observation.state`) and which EMBODIMENT they drove -- the MANO rig or, since
2026-09-15, the Robotiq 2F-140 (`--embodiment gripper`) and, since 2026-09-20,
the 2F-85 (`robotiq85`) and the Sharpa / Allegro / LEAP hands, whose state
slice, contact shapes and `robot_type` are their own. A robot dataset lives in
its own directory (`<task>_<embodiment>`), and an explicit --record path is
checked for both. Since 2026-09-28 every recording is two-handed, so the
hand layout no longer picks a directory; it is only checked.
"""

import json
import os

DEFAULT_COLLECTION_HAND = "both"
DEFAULT_EMBODIMENT = "mano"
#: info.json robot_type per embodiment, one hand and two. The keys are the
#: --embodiment names (embodiment/registry.py); the names are the assets'.
ROBOT_TYPES = {"mano": ("mano_hand", "mano_hand_bimanual"),
               "gripper": ("robotiq_2f140", "robotiq_2f140_bimanual"),
               "robotiq85": ("robotiq_2f85", "robotiq_2f85_bimanual"),
               "sharpa": ("sharpa", "sharpa_bimanual"),
               "allegro": ("allegro", "allegro_bimanual"),
               "leap": ("leap", "leap_bimanual")}


def robot_type(embodiment, hands):
    one, two = ROBOT_TYPES[embodiment]
    return two if len(tuple(hands)) > 1 else one


def embodiment_of(robot_type_name):
    """The embodiment a robot_type string names ('mano' for the legacy names)."""
    for name, types in ROBOT_TYPES.items():
        if robot_type_name == name or robot_type_name in types:
            return name
    return DEFAULT_EMBODIMENT


def _meta(root):
    for name in ("info.json", "scene.json"):
        path = os.path.join(root, "meta", name)
        if not os.path.exists(path):
            continue
        with open(path) as fh:
            return json.load(fh)
    return None


def recorded_hands(root):
    """Read the authoritative layout, including pre-bimanual metadata."""
    old = _meta(root)
    if old is None:
        return None
    hands = old.get("hands")
    if hands is None:
        side = (old.get("collection_config") or {}).get("hand")
        side = side or ((old.get("assets") or {}).get("hand") or {}).get("side", "right")
        hands = ["left", "right"] if side == "both" else [side]
    return tuple(hands)


def recorded_embodiment(root):
    """Which embodiment a dataset was recorded with; 'mano' for everything
    that predates the flag (no robot_type, or a mano_hand one)."""
    old = _meta(root)
    if old is None:
        return None
    rt = old.get("robot_type") or (old.get("collection_config") or {}).get("embodiment")
    if rt is None:
        rt = (old.get("assets") or {}).get("embodiment")
    return embodiment_of(rt)


def check_recording_hands(root, hands, embodiment=DEFAULT_EMBODIMENT):
    old = recorded_hands(root)
    if old is not None and old != tuple(hands):
        raise ValueError(f"{root} contains {list(old)} hands; requested "
                         f"{list(hands)}. Use a fresh --record directory.")
    old_e = recorded_embodiment(root)
    if old_e is not None and old_e != embodiment:
        raise ValueError(f"{root} was recorded with the {old_e} embodiment; "
                         f"requested {embodiment}. Use a fresh --record directory.")


#: Filesystems a recording must not be written to. ntfs3 is the external HDD's
#: (/media/richardxu/HDD): writing there can hang the writer in the kernel
#: (do_truncate, uninterruptible -- 2026-10-03, cube_pickup episode 19) or oops
#: it (2026-09-29, the hammer_nail scene). tools/offload_datasets.sh leaves a
#: finished task there behind a symlink, so a chain that collects MORE of that
#: task follows the link onto the HDD.
UNSAFE_FILESYSTEMS = ("ntfs3", "ntfs", "fuseblk")


def filesystem_of(path):
    """The fstype of the mount `path` (resolved through symlinks) lives on."""
    real = os.path.realpath(path)
    best, kind = "", None
    try:
        with open("/proc/mounts") as fh:
            for line in fh:
                parts = line.split()
                if len(parts) < 3:
                    continue
                mnt = parts[1].replace("\\040", " ")
                if (real == mnt or real.startswith(mnt.rstrip("/") + "/")) and len(mnt) > len(best):
                    best, kind = mnt, parts[2]
    except OSError:
        return None
    return kind


def check_recording_filesystem(root):
    """Refuse to record onto the HDD (see UNSAFE_FILESYSTEMS). Reading it is safe."""
    kind = filesystem_of(root)
    if kind in UNSAFE_FILESYSTEMS:
        raise ValueError(
            f"{root} resolves to {os.path.realpath(root)}, on a {kind} filesystem (the external HDD): "
            f"writing there can hang the episode writer in the kernel or crash it (2026-09-29, "
            f"2026-10-03). Copy the dataset back to the SSD and replace the symlink with that copy "
            f"before collecting more of this task. Use a fresh --record directory.")


def _table_numbers(value):
    """'x,y,z' (the flag's form), a list or a number -> a tuple of floats."""
    if value is None:
        return None
    if isinstance(value, str):
        value = value.split(",")
    if not isinstance(value, (list, tuple)):
        value = [value]
    try:
        return tuple(float(v) for v in value)
    except (TypeError, ValueError):
        return None


def check_recording_table(root, table_pos, table_size):
    """Refuse to add episodes on a different table to a dataset that has some.

    Every session rewrites meta/scene.json (and the table in it) from the run's
    own table, so episodes recorded on the old table would afterwards replay on
    the new one -- objects sunk into it or floating over it, with nothing to
    say so. Compared against info.json's collection_config, which exists once
    an episode has been saved; a directory with none has nothing to protect."""
    path = os.path.join(root, "meta", "info.json")
    if not os.path.exists(path):
        return
    with open(path) as fh:
        cfg = json.load(fh).get("collection_config") or {}
    for key, now in (("table_pos", table_pos), ("table_size", table_size)):
        old, new = _table_numbers(cfg.get(key)), _table_numbers(now)
        if old is None or new is None:
            continue
        if key == "table_size":
            # one number is a square: 0.9 (every dataset before 2026-09-28)
            # and "0.9,0.9" (the collector's form since) are the same table
            old, new = ((v * 2 if len(v) == 1 else v[:2]) for v in (old, new))
        if len(old) != len(new) or any(abs(a - b) > 1e-6 for a, b in zip(old, new)):
            raise ValueError(
                f"{root} was recorded with {key} {cfg.get(key)}; this run's is {now}. "
                f"meta/scene.json is rewritten every session, so its episodes would "
                f"replay on this table. Archive them or use a fresh --record directory.")


def default_recording_dir(datasets, task, hands, embodiment=DEFAULT_EMBODIMENT):
    """The one directory a task's demos go to: ``<task>`` for the MANO hands,
    ``<task>_<embodiment>`` for a robot.

    Collection is bimanual only (2026-09-28), so there is no longer a layout
    to choose between and no per-hand sibling (``_right``, ``_left``,
    ``_bimanual``) to fall back to. A directory that already holds a
    DIFFERENT layout -- a one-handed dataset from before, or another
    embodiment's -- is not silently redirected: :func:`check_recording_hands`
    refuses it when recording starts, and nothing is overwritten. Read-only;
    ``hands`` is accepted for the callers' convenience and not consulted.
    """
    name = task.replace(":", "_")
    if embodiment != DEFAULT_EMBODIMENT:
        name = f"{name}_{embodiment}"
    return os.path.join(datasets, name)