File size: 15,923 Bytes
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110cee3
 
50e0062
 
110cee3
 
50e0062
 
 
 
 
49bbef4
 
 
fa4121e
 
 
749b1c8
 
 
 
110cee3
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
110cee3
 
33c14d6
110cee3
 
 
 
 
 
33c14d6
 
 
 
 
110cee3
 
 
 
 
 
 
 
 
33c14d6
110cee3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be78d6b
 
 
 
 
 
 
 
 
 
 
 
 
 
50e0062
 
 
 
 
fa4121e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
110cee3
33c14d6
 
 
110cee3
33c14d6
110cee3
33c14d6
 
110cee3
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
"""Upload phase 2 outputs into one folder of a Hugging Face dataset repo.

Everything goes under `--path-in-repo` (default `chess-sim`) and nothing outside
that folder is touched:

  chess-sim/README.md             what is here and how to load it
  chess-sim/datasets/<name>/      the LeRobot dataset with phase2_episodes.jsonl and
                                  phase2_summary.json (LeRobot's temporary images left out)
  chess-sim/review/<name>.mp4     the review video, if the dataset folder has one
  chess-sim/reports/              sim/reports/ (grasp validation)
  chess-sim/code/                 the sim/ code and assets that made the data, and pyproject.toml

LeRobot's own push_to_hub writes to the repo root and replaces its README, so the
folder is staged locally and sent with upload_large_folder, which only adds or
replaces files. Log in once first with `.venv/bin/hf auth login` (a token that can
write to the repo).

Run:  .venv/bin/python sim/push_dataset.py --repo-id Machanize/playful --name pilot_60
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import sys
import tempfile
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(HERE))

SKIP_DIRS = {"__pycache__", "renders", "reports", ".cache"}


def _place(src: Path, dst: Path):
    dst.parent.mkdir(parents=True, exist_ok=True)
    try:
        os.link(src, dst)            # same disk: no copy of a large dataset
    except OSError:
        shutil.copy2(src, dst)


def _tree(src: Path, dst: Path, skip=frozenset()):
    for dirpath, dirnames, filenames in os.walk(src):
        dirnames[:] = [n for n in dirnames if n not in skip]
        for f in filenames:
            if f == ".DS_Store":
                continue
            p = Path(dirpath) / f
            _place(p, dst / p.relative_to(src))


NOTES = {
    "pilot_60": "The first pilot: nominal board and tray, narrower lighting and camera variety. Kept for reference.",
    "varied_2000": "Heavy randomisation (see *What varies*). Trained the first model, 0% in the sim test "
                   "(since deleted; report in `reports/policy_eval/`).",
    "baseline_v1": "The simple baseline (see *Baseline scene*): one fixed scene and ten fixed opening moves. "
                   "Trains `Machanize/chess_phase_smolvla_baseline`.",
    "baseline_recovery_v1": "Correction demonstrations in the baseline scene (see *Corrections*), first "
                            "attempt: the teacher rises and pauses before regrasping, which made the fine-tuned "
                            "policy hover (20%). Kept for reference; not used for training.",
    "baseline_recovery_v2": "Correction demonstrations, second attempt (`collect_recovery.py --style v2`): the "
                            "teacher lines up from where the arm is, rising only as far as needed, and goes "
                            "straight down, with no pause. Fine-tuning the baseline on these plus baseline_v1 "
                            "lowered success (30% vs 51.7% on the same episodes: more pieces knocked over). "
                            "Kept for reference; not used.",
    "baseline_dart_v1": "baseline_v1's 300 scenes (same episode seeds) with a perturbed teacher (see *Perturbed "
                        "teacher*): in about half the episodes the executed approach drifts 2-10 mm off-centre and "
                        "returns before the fingertips reach the piece, while the recorded actions stay the clean "
                        "plan. A model trained fresh on it with the baseline recipe corrects on the way down and "
                        "closes more precisely (5.4 vs 6.6 mm); success 28.5% vs 25.5% on 200 paired scenes "
                        "(not significant), 17/40 vs 7/40 on the trace scenes (`reports/dart_eval/`). Checkpoint in "
                        "`experiments/dart/`.",
}


def _info(repo_id: str, folder: str, name: str) -> dict:
    """LeRobot's meta/info.json of a dataset already in the repo."""
    from huggingface_hub import hf_hub_download

    try:
        return json.loads(Path(hf_hub_download(repo_id, f"{folder}/datasets/{name}/meta/info.json",
                                               repo_type="dataset")).read_text())
    except Exception:
        return {}


def readme(repo_id: str, folder: str, name: str, dataset: Path) -> str:
    """The folder README: every dataset in it (those already uploaded plus this one)."""
    from huggingface_hub import HfApi

    try:
        names = {Path(e.path).name for e in HfApi().list_repo_tree(repo_id, path_in_repo=f"{folder}/datasets",
                                                                   repo_type="dataset")}
    except Exception:
        names = set()
    names.add(name)
    val_path = HERE / "reports" / "grasp_validation.json"
    val = json.loads(val_path.read_text())["summary"] if val_path.exists() else {}
    lines = [
        "# chess-sim: SO-101 chess pick-and-place in simulation", "",
        "Scripted-expert demonstrations of an SO-101 arm moving one chess piece from a square "
        "to another square or into a capture tray, recorded in MuJoCo. Made for training SmolVLA "
        "(phase 2 of the play-machanize project).", "",
        "Every dataset is LeRobot v3.0 at 30 fps, 640x480 images, with the source square highlighted "
        "red and the destination (square or tray) blue. `observation.state` and `action`: 5 arm joints in "
        "degrees and the gripper 0-100 (LeRobot's SO-101 follower with `use_degrees=True`). One instruction "
        "for every frame: \"move the piece on the red square to the blue square\". `phase2_episodes.jsonl` "
        "has per-episode notes (seed, piece, squares, board, piece set, lighting, cameras).", "",
        "## Datasets", "",
        "| folder | episodes | frames | cameras | video | notes |", "|---|---|---|---|---|---|",
    ]
    for n in sorted(names):
        info = json.loads((dataset / "meta" / "info.json").read_text()) if n == name else _info(repo_id, folder, n)
        cams = [k.split(".")[-1] for k, f in info.get("features", {}).items() if f.get("dtype") == "video"]
        vid = next((f.get("info", {}) for f in info.get("features", {}).values() if f.get("dtype") == "video"), {})
        video = f"{vid.get('video.codec', '?')} {vid.get('video.pix_fmt', '')}".strip()
        lines.append(f"| `datasets/{n}/` | {info.get('total_episodes', '?')} | {info.get('total_frames', '?')} | "
                     f"{', '.join(cams) or '?'} | {video} | {NOTES.get(n, '')} |")
    lines += ["", "`review/<name>.mp4`: random episodes of a dataset, read back through LeRobot. "
              "`reports/`: expert validation, policy tests and diagnostics. `code/`: the simulation, expert "
              "and export code that produced the data.", ""]
    lines += ["## What varies (varied_2000)", "",
              "- **Board and tray:** 22-25 mm squares, 6-22 mm border, 3-20 mm thick, pieces scaled to the "
              "squares. The robot plays white or black. The board's angle and position vary within reach; "
              "the tray varies in side, angle, size and colour.",
              "- **Table:** slides so its edges and corners, with the floor, come into view. Matte to glossy "
              "tables, with varied floors and walls.",
              "- **Lighting:** one to four lamps (window, ceiling, desk lamp, sun), 2700-6500 K, dim to "
              "bright, with and without shadows.",
              "- **Colours:** the arm (white most often), the pieces and the board.",
              "- **Clutter:** a laptop, phone, mug, notebook, pen and cables around the board.",
              "- **Overhead camera:** anywhere a person would mount it (35-80 cm up, up to 45 degrees from "
              "vertical, any side but behind the robot, 38-62 degree lenses). The wrist and rover cameras "
              "vary only by small mounting errors.",
              "- **Webcam look:** auto-exposure, white balance, blur, noise, JPEG and vignetting.",
              "- **Video:** LeRobot's default encoding (H.264, CRF 30, 4:2:0 chroma), which washes out the "
              "small red and blue squares.", ""]
    if "baseline_v1" in names:
        lines += ["## Baseline scene (baseline_v1)", "",
                  "Everything fixed, to get reliable closed-loop success before adding variety back one change "
                  "at a time (settings: `code/sim/phase2_baseline.toml`).", "",
                  "- The nominal board (25 mm squares) square to the robot and flush against its deck; the "
                  "robot plays black. Reference piece set, black and white pieces, white arm.",
                  "- Tray on the right, fixed table, the scene's window and ceiling lamps, no clutter.",
                  "- An overhead camera like the owner's (65 cm up, straight down, 44 degree lens, the arm at the "
                  "top edge) and the wrist camera, no mounting error, a clean webcam (no noise, blur or colour "
                  "effects, light JPEG).",
                  "- Ten opening moves from the start position: e7e5, d7d5, g8f6, b8c6, c7c5 (the robot's "
                  "side) and e2e4, d2d4, g1f3, b1c3, c2c4 (the far side).",
                  "- Markers with an opaque 2 px outline; pieces centred in their squares.",
                  "- Sharper video: H.264 at CRF 18 with full 4:4:4 chroma.", ""]
    if "baseline_recovery_v1" in names:
        lines += ["## Corrections (baseline_recovery_v1)", "",
                  "DAgger-style data in the baseline scene. The baseline policy "
                  "(`Machanize/chess_phase_smolvla_baseline`) drives; the scripted teacher takes over from "
                  "exactly where the arm is, and only the teacher's part is recorded. A grasp inspection had "
                  "shown the policy's jaws close 4-6 mm off the piece when it fails, against about 1 mm when "
                  "it holds. Handovers (`recovery.trigger` in `phase2_episodes.jsonl`):", "",
                  "- `pre_grasp`: the jaws, still open, come within 15-45 mm above the piece. The teacher "
                  "lines up above it, holds still 0.5 s (the wrist camera sees the piece between the jaws), "
                  "descends, grasps and finishes the move.",
                  "- `misaligned_close`: the policy starts closing more than 2.5 mm off. The teacher reopens, "
                  "rises clear, holds still 0.5 s to look, lines up, grasps and finishes.",
                  "- `failed_lift`: the jaws closed but the piece did not rise within 1.2 s. Same recovery.", "",
                  "Episodes where the piece had toppled or a neighbour had moved before the handover are "
                  "dropped, as are failed recoveries.", "",
                  "Fine-tuning the baseline on these plus baseline_v1 gave 20% (from 36.7%): in `pre_grasp` "
                  "and after a misaligned close the teacher first rises to its approach height and pauses, "
                  "and the policy learned to hover over pawns. The next attempt (`--style v2`) lines up from "
                  "where the arm is and goes straight down.", ""]
    if "baseline_dart_v1" in names:
        lines += ["## Perturbed teacher (baseline_dart_v1)", "",
                  "DART-style demonstrations (`PHASE2_PROFILE=baseline,dart`, `Expert.perturb_pick`). The plain "
                  "teacher always starts its descent exactly centred and goes straight down, so near the piece "
                  "its next action can be predicted from the joint state alone; the baseline policy's roughly "
                  "7 mm aiming error is never corrected on the way down.", "",
                  "- In about half the episodes the executed hand drifts sideways by a random 2-10 mm (any "
                  "direction) during the approach, holds the offset into the descent and returns to the plan "
                  "over 0.3-0.8 s, ending 4 mm above the target's top. Each offset is collision-checked with "
                  "the target included.",
                  "- The recorded `action` is the clean plan throughout; `observation.state` and the images "
                  "show the perturbed hand. The episodes therefore show \"from off-centre, command the centred "
                  "path\", and never an off-centre aim.",
                  "- Same 300 episode seeds as baseline_v1 (`--seeds-from`), so each episode repeats the same "
                  "scene, move and timing. `dart_offset_mm` in `phase2_episodes.jsonl` is the executed offset "
                  "(null when unperturbed).", "",
                  "Teacher validation, 100 scenes: 100% success perturbed and plain, no touches on the target "
                  "or its neighbours before the grasp (`reports/dart_teacher/`).", ""]
    if val:
        lines += [f"Expert validation (random layouts): {val['success_percent']}% of {val['trials']} trials "
                  f"(target above {val['target_percent']}%).", ""]
    lines += [
        "## Load", "",
        "LeRobot expects a dataset at the top of a folder, so download it first (replace `<name>`):", "",
        "```bash",
        f"hf download {repo_id} --repo-type dataset --include \"{folder}/datasets/<name>/*\" --local-dir playful",
        "```", "", "```python",
        "from lerobot.datasets.lerobot_dataset import LeRobotDataset",
        f"ds = LeRobotDataset(\"local/so101_chess_sim\", root=\"playful/{folder}/datasets/<name>\")",
        "```", "",
    ]
    return "\n".join(lines)


def push(repo_id: str, dataset: Path, name: str, folder: str = "chess-sim", delete_local: bool = False,
         dry_run: bool = False) -> str:
    from huggingface_hub import HfApi

    with tempfile.TemporaryDirectory(dir=dataset.parent) as tmp:
        stage = Path(tmp) / folder
        _tree(dataset, stage / "datasets" / name, skip={"images", ".cache"})
        videos = list(dataset.glob("review_*.mp4"))
        for v in videos:
            (stage / "datasets" / name / v.name).unlink()
            _place(v, stage / "review" / f"{name}.mp4")
        _tree(HERE / "reports", stage / "reports")
        _tree(HERE, stage / "code" / "sim", skip=SKIP_DIRS)
        _place(ROOT / "pyproject.toml", stage / "code" / "pyproject.toml")
        (stage / "README.md").write_text(readme(repo_id, folder, name, dataset))
        if dry_run:
            files = [p for p in Path(tmp).rglob("*") if p.is_file()]
            print((stage / "README.md").read_text())
            print(f"{len(files)} files, {sum(p.stat().st_size for p in files) / 1e6:.1f} MB, for example:")
            for p in sorted(files)[:: max(1, len(files) // 25)]:
                print("  ", p.relative_to(tmp))
            return "(dry run, nothing uploaded)"
        HfApi().upload_large_folder(repo_id=repo_id, folder_path=tmp, repo_type="dataset")
    if delete_local:
        shutil.rmtree(dataset)
    return f"https://huggingface.co/datasets/{repo_id}/tree/main/{folder}"


def main():
    from episode import load_config

    cfg = load_config()
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--repo-id", required=True, help="e.g. Machanize/playful")
    ap.add_argument("--name", required=True, help="dataset folder name, e.g. pilot_60")
    ap.add_argument("--root", default=cfg["dataset"]["root"])
    ap.add_argument("--path-in-repo", default="chess-sim")
    ap.add_argument("--delete-local", action="store_true", help="remove the local dataset after a successful upload")
    ap.add_argument("--dry-run", action="store_true", help="stage and list the files, upload nothing")
    args = ap.parse_args()
    url = push(args.repo_id, (ROOT / args.root).resolve(), args.name, args.path_in_repo, args.delete_local,
               args.dry_run)
    print(f"uploaded to {url}")


if __name__ == "__main__":
    main()