File size: 7,117 Bytes
d94c87e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d53876e
 
d94c87e
 
d53876e
 
d94c87e
 
 
 
 
 
 
 
 
 
 
 
 
 
d53876e
 
 
 
d94c87e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d53876e
 
 
 
 
d94c87e
 
 
 
 
 
d53876e
 
 
 
 
 
 
 
 
d94c87e
 
 
d53876e
d94c87e
 
d53876e
d94c87e
 
 
 
d53876e
d94c87e
 
 
 
 
 
d53876e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84af0a7
 
 
d94c87e
84af0a7
 
 
 
 
 
 
d94c87e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Publish this dataset to the Hugging Face Hub, ready for `huggingface-cli download` on Brev.

    uv run python scripts/upload_to_hf.py <user-or-org>/pick_and_place-300           # private
    uv run python scripts/upload_to_hf.py <user-or-org>/pick_and_place-300 --public
    uv run python scripts/upload_to_hf.py <repo_id> --dry-run                        # list only

Requires `huggingface-cli login` (or HF_TOKEN) first.

Two things this does that a bare `huggingface-cli upload` does not:

1. **Tags the repo `v2.1`.** lerobot resolves a dataset revision via `get_safe_version()`, which
   raises `RevisionNotFoundError` on an untagged repo. That path is only reached when the local
   metadata load fails, but the tag costs nothing and removes the failure class outright.
2. **Excludes local-only cruft** (`.claude/`, `__pycache__`, `.DS_Store`, the vendored test stub)
   so the published tree is exactly what the runbook expects.
"""

import argparse
import sys

from huggingface_hub import HfApi

EXCLUDE_DIRS = ("data/", "videos/", ".claude/", ".git/", ".cache/")

IGNORE = [
    ".claude/*",
    ".cache/*",          # huggingface_hub's own upload/download bookkeeping

    "**/__pycache__/*",
    "**/.DS_Store",
    ".git/*",
]


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("repo_id", help="e.g. your-username/pick_and_place-300")
    ap.add_argument("--public", action="store_true",
                    help="publish publicly. NOTE: bystanders are identifiable in the wrist "
                         "cameras. A private repo downloads identically on Brev after "
                         "`huggingface-cli login`.")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--code-only", action="store_true",
                    help="push only docs/scripts/reference_frames, not data/ or videos/. Use to "
                         "refresh tooling on a repo whose data is already uploaded -- a handful of "
                         "small files, so no rate-limit risk.")
    ap.add_argument("--root", default=None, help="defaults to the repo root next to scripts/")
    a = ap.parse_args()

    import pathlib
    root = pathlib.Path(a.root) if a.root else pathlib.Path(__file__).resolve().parent.parent

    # Refuse to publish a dataset whose indices are broken -- the failure is silent downstream.
    import json
    import glob
    info = json.load(open(root / "meta/info.json"))
    n_files = len(glob.glob(str(root / "data/chunk-000/episode_*.parquet")))
    n_vids = len(glob.glob(str(root / "videos/chunk-000/*/*.mp4")))
    problems = []
    if info["total_episodes"] != n_files:
        problems.append(f"info.total_episodes={info['total_episodes']} but {n_files} parquet files")
    if info["total_videos"] != n_vids:
        problems.append(f"info.total_videos={info['total_videos']} but {n_vids} mp4 files")
    if info["splits"]["train"] != f"0:{n_files}":
        problems.append(f"info.splits={info['splits']} does not cover 0:{n_files}")
    if problems and a.code_only:
        print("note: data counters look off, but --code-only touches no data files:")
        for pr in problems:
            print("  -", pr)
        problems = []
    if problems:
        print("REFUSING TO UPLOAD -- run scripts/repair_indices.py first:")
        for p in problems:
            print("  -", p)
        return 1

    data_ignore = ["data/*", "videos/*"]
    ignore = IGNORE + (data_ignore if a.code_only else [])
    if a.code_only:
        files = [f for f in root.rglob("*") if f.is_file()
                 and not str(f.relative_to(root)).startswith(EXCLUDE_DIRS)
                 and "__pycache__" not in str(f) and f.name != ".DS_Store"]
        print(f"code-only: {len(files)} file(s)")
        for f in sorted(files):
            print(f"    {f.relative_to(root)}")
    size_gb = sum(f.stat().st_size for f in root.rglob("*") if f.is_file()) / 1e9
    print(f"root         {root}")
    print(f"repo_id      {a.repo_id}")
    print(f"visibility   {'unchanged (--code-only)' if a.code_only else ('PUBLIC' if a.public else 'private')}")
    print(f"episodes     {n_files}   frames {info['total_frames']}   videos {n_vids}")
    print(f"size         ~{size_gb:.2f} GB")
    print(f"ignored      {ignore}")
    if a.dry_run:
        print("\n--dry-run: nothing uploaded.")
        return 0

    if a.public and not a.code_only:
        print("\nPublishing PUBLICLY. Bystanders are identifiable in the wrist-camera views.")
        if input("Type 'public' to confirm: ").strip() != "public":
            print("aborted.")
            return 1

    api = HfApi()
    if a.code_only:
        # Deliberately no create_repo here. --code-only targets a repo that already exists, and
        # calling create_repo(private=...) against it risks changing visibility as a side effect.
        if not api.repo_exists(a.repo_id, repo_type="dataset"):
            print(f"{a.repo_id} does not exist -- do a full upload first (without --code-only).")
            return 1
        print(f"visibility unchanged (not touching repo settings)")
    else:
        api.create_repo(a.repo_id, repo_type="dataset", private=not a.public, exist_ok=True)
    if a.code_only:
        print("\nuploading docs + scripts only...")
        api.upload_folder(
            repo_id=a.repo_id,
            repo_type="dataset",
            folder_path=str(root),
            ignore_patterns=ignore,
            commit_message="Update runbook and tooling",
        )
    else:
        print("\nuploading (resumable -- rerun the same command if it drops)...")
        api.upload_large_folder(
            repo_id=a.repo_id,
            repo_type="dataset",
            folder_path=str(root),
            ignore_patterns=ignore,
        )
    # create_tag(exist_ok=True) does NOT move an existing tag -- it silently succeeds and leaves
    # v2.1 pointing at whatever commit it was first cut from. That is how the tag ended up missing
    # scripts added by later --code-only pushes. Delete and recreate so v2.1 always means HEAD.
    try:
        try:
            api.delete_tag(a.repo_id, tag="v2.1", repo_type="dataset")
            print("removed stale v2.1 tag")
        except Exception:  # noqa: BLE001 - absent tag is the normal first-upload case
            pass
        api.create_tag(a.repo_id, tag="v2.1", repo_type="dataset")
        print("tagged v2.1 at HEAD")
    except Exception as e:  # noqa: BLE001 - tagging is best-effort, upload already succeeded
        print(f"WARNING: could not create the v2.1 tag ({e}). Create it by hand:")
        print(f"  python -c \"from huggingface_hub import HfApi; "
              f"HfApi().create_tag('{a.repo_id}', tag='v2.1', repo_type='dataset')\"")

    print(f"\ndone -> https://huggingface.co/datasets/{a.repo_id}")
    print("\nOn the Brev instance:")
    print("  export HF_LEROBOT_HOME=/home/ubuntu/lerobot_data")
    print(f"  uv run huggingface-cli download {a.repo_id} --repo-type dataset \\")
    print(f"    --local-dir $HF_LEROBOT_HOME/{a.repo_id}")
    return 0


if __name__ == "__main__":
    sys.exit(main())