HarrisonPENG commited on
Commit
fcb22db
·
verified ·
1 Parent(s): f1da917

Complete DROID publication and publish subset indexes

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ episodes.jsonl filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -4,7 +4,7 @@ viewer: false
4
 
5
  # DROID episodes
6
 
7
- Publication status: **uploading — do not use yet**.
8
 
9
  33,966 episodes in 1,018 uncompressed TAR shards. Episodes are ordered lexicographically by folder name; no episode spans shards.
10
 
 
4
 
5
  # DROID episodes
6
 
7
+ Publication status: **complete**.
8
 
9
  33,966 episodes in 1,018 uncompressed TAR shards. Episodes are ordered lexicographically by folder name; no episode spans shards.
10
 
droid_hf.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Publish lossless DROID TAR shards and download subsets. Python >= 3.10."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from contextlib import contextmanager
8
+ import fcntl
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import os
13
+ from pathlib import Path, PurePosixPath
14
+ import shutil
15
+ import stat
16
+ import sys
17
+ import tarfile
18
+ import time
19
+
20
+ GIB = 1024 ** 3
21
+ ROOT = Path(__file__).resolve().parent.parent
22
+ FORMAT_VERSION = 1
23
+ LANGUAGE_KEYS = ("language_instruction", "language_instruction_2", "language_instruction_3")
24
+
25
+
26
+ def log(message):
27
+ print(message, flush=True)
28
+
29
+
30
+ def canonical(value):
31
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
32
+
33
+
34
+ def atomic_json(path, value):
35
+ path = Path(path)
36
+ temporary = path.with_name(path.name + ".tmp")
37
+ with temporary.open("wb") as stream:
38
+ stream.write(canonical(value) + b"\n")
39
+ stream.flush()
40
+ os.fsync(stream.fileno())
41
+ os.replace(temporary, path)
42
+ descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
43
+ try:
44
+ os.fsync(descriptor)
45
+ finally:
46
+ os.close(descriptor)
47
+
48
+
49
+ def read_json(path):
50
+ return json.loads(Path(path).read_text(encoding="utf-8"))
51
+
52
+
53
+ def sha256_file(path):
54
+ digest = hashlib.sha256()
55
+ with Path(path).open("rb") as stream:
56
+ for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
57
+ digest.update(block)
58
+ return digest.hexdigest()
59
+
60
+
61
+ def safe_id(name):
62
+ if not isinstance(name, str) or not name or name in (".", "..", ".droid_hf_extract"):
63
+ raise ValueError(f"Invalid episode ID: {name!r}")
64
+ if "/" in name or "\\" in name or "\0" in name:
65
+ raise ValueError(f"Unsafe episode ID: {name!r}")
66
+ return name
67
+
68
+
69
+ def signature(info):
70
+ # ctime detects rewrites even when a producer restores the original mtime.
71
+ return (info.st_dev, info.st_ino, info.st_mode, info.st_size,
72
+ info.st_mtime_ns, info.st_ctime_ns)
73
+
74
+
75
+ def tree_entries(root):
76
+ """Yield deterministic directory/file entries; never follow internal links."""
77
+ root = Path(root)
78
+
79
+ def visit(path, relative):
80
+ info = path.lstat()
81
+ if not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)):
82
+ raise ValueError(f"Only regular files and directories are supported: {path}")
83
+ yield path, relative, info
84
+ if stat.S_ISDIR(info.st_mode):
85
+ for child in sorted(path.iterdir(), key=lambda item: item.name):
86
+ yield from visit(child, relative + "/" + child.name)
87
+
88
+ yield from visit(root, root.name)
89
+
90
+
91
+ def tar_info(relative, info):
92
+ result = tarfile.TarInfo(relative)
93
+ result.type = tarfile.DIRTYPE if stat.S_ISDIR(info.st_mode) else tarfile.REGTYPE
94
+ result.mode = 0o755 if result.isdir() else 0o644
95
+ result.size = 0 if result.isdir() else info.st_size
96
+ # Canonical headers make interrupted/recreated shards byte-for-byte identical.
97
+ result.uid = result.gid = result.mtime = 0
98
+ result.uname = result.gname = ""
99
+ return result
100
+
101
+
102
+ def inspect_tree(root, include_tar_bytes=True):
103
+ digest = hashlib.sha256()
104
+ size = files = directories = tar_bytes = 0
105
+ for _, relative, info in tree_entries(root):
106
+ digest.update(canonical([relative, signature(info)]) + b"\n")
107
+ if include_tar_bytes:
108
+ member = tar_info(relative, info)
109
+ tar_bytes += len(member.tobuf(format=tarfile.PAX_FORMAT))
110
+ tar_bytes += ((member.size + 511) // 512) * 512
111
+ if stat.S_ISDIR(info.st_mode):
112
+ directories += 1
113
+ else:
114
+ size += info.st_size
115
+ files += 1
116
+ return dict(fingerprint=digest.hexdigest(), bytes=size, file_count=files,
117
+ directory_count=directories, tar_bytes=tar_bytes)
118
+
119
+
120
+ def episode_names(source):
121
+ names = []
122
+ for path in source.iterdir():
123
+ if path.is_symlink() or not path.is_dir():
124
+ raise ValueError(f"Expected an episode directory at source root: {path}")
125
+ names.append(safe_id(path.name))
126
+ if not names:
127
+ raise ValueError(f"No episodes found: {source}")
128
+ return sorted(names)
129
+
130
+
131
+ def archive_size(payload):
132
+ return ((payload + 1024 + tarfile.RECORDSIZE - 1) // tarfile.RECORDSIZE) * tarfile.RECORDSIZE
133
+
134
+
135
+ def make_plan(source, shard_bytes):
136
+ source = Path(source).resolve()
137
+ names = episode_names(source)
138
+ episodes = []
139
+ last_log = time.monotonic()
140
+ for index, name in enumerate(names):
141
+ folder = source / name
142
+ metadata_path = folder / "metadata.json"
143
+ before = signature(metadata_path.lstat())
144
+ metadata = read_json(metadata_path)
145
+ if not isinstance(metadata, dict):
146
+ raise ValueError(f"Expected JSON object: {metadata_path}")
147
+ record = inspect_tree(folder)
148
+ if before != signature(metadata_path.lstat()):
149
+ raise ValueError(f"Source changed during scan: {metadata_path}")
150
+ record.update(episode_id=name, lab=name.split("__", 1)[0],
151
+ status=metadata.get("status"), frame_count=metadata.get("frame_count"),
152
+ **{key: metadata.get(key, []) for key in LANGUAGE_KEYS})
153
+ episodes.append(record)
154
+ if time.monotonic() - last_log >= 5 or index + 1 == len(names):
155
+ log(f"[scan] {index + 1}/{len(names)} episodes")
156
+ last_log = time.monotonic()
157
+ if episode_names(source) != names:
158
+ raise ValueError("Episode directory list changed during scan; stop source writers and retry")
159
+ shards = []
160
+ start = payload = 0
161
+ for index, episode in enumerate(episodes):
162
+ if index > start and archive_size(payload + episode["tar_bytes"]) > shard_bytes:
163
+ shards.append(dict(path=f"data/shard-{len(shards):06d}.tar", start=start,
164
+ stop=index, size=archive_size(payload)))
165
+ start, payload = index, 0
166
+ payload += episode["tar_bytes"]
167
+ shards.append(dict(path=f"data/shard-{len(shards):06d}.tar", start=start,
168
+ stop=len(episodes), size=archive_size(payload)))
169
+ for shard in shards:
170
+ for episode in episodes[shard["start"]:shard["stop"]]:
171
+ episode["shard"] = shard["path"]
172
+ plan = dict(format_version=FORMAT_VERSION, source=str(source), shard_bytes=shard_bytes,
173
+ episodes=episodes, shards=shards)
174
+ plan["plan_id"] = hashlib.sha256(canonical(plan)).hexdigest()
175
+ return plan
176
+
177
+
178
+ def verify_source(plan):
179
+ source = Path(plan["source"])
180
+ expected = [episode["episode_id"] for episode in plan["episodes"]]
181
+ if episode_names(source) != expected:
182
+ raise ValueError("Source episode list changed; use a new work directory for a new publication")
183
+ last_log = time.monotonic()
184
+ for index, episode in enumerate(plan["episodes"]):
185
+ folder = source / episode["episode_id"]
186
+ if inspect_tree(folder, False)["fingerprint"] != episode["fingerprint"]:
187
+ raise ValueError(f"Source changed since planning: {folder}")
188
+ if time.monotonic() - last_log >= 5 or index + 1 == len(expected):
189
+ log(f"[source check] {index + 1}/{len(expected)} episodes")
190
+ last_log = time.monotonic()
191
+
192
+
193
+ def load_or_plan(source, work, shard_bytes):
194
+ path = work / "plan.json"
195
+ if path.exists():
196
+ plan = read_json(path)
197
+ contents = {key: value for key, value in plan.items() if key != "plan_id"}
198
+ if hashlib.sha256(canonical(contents)).hexdigest() != plan.get("plan_id"):
199
+ raise ValueError("plan.json checksum mismatch; do not edit a saved plan")
200
+ if (plan["format_version"] != FORMAT_VERSION or plan["source"] != str(source)
201
+ or plan["shard_bytes"] != shard_bytes):
202
+ raise ValueError("Source/format/shard size differs from saved plan; use a new work directory")
203
+ verify_source(plan)
204
+ else:
205
+ plan = make_plan(source, shard_bytes)
206
+ atomic_json(path, plan)
207
+ return plan
208
+
209
+
210
+ def summarize(plan):
211
+ total = sum(item["size"] for item in plan["shards"])
212
+ log(f"Episodes: {len(plan['episodes']):,}; files: "
213
+ f"{sum(ep['file_count'] for ep in plan['episodes']):,}; "
214
+ f"TAR shards: {len(plan['shards']):,}; TAR total: {total / GIB:.3f} GiB")
215
+ log(f"First: {plan['episodes'][0]['episode_id']}; last: {plan['episodes'][-1]['episode_id']}")
216
+
217
+
218
+ def work_usage(work):
219
+ total = 0
220
+ for current, _, files in os.walk(work, followlinks=False):
221
+ for filename in files:
222
+ path = Path(current) / filename
223
+ try:
224
+ info = path.lstat()
225
+ if stat.S_ISREG(info.st_mode):
226
+ total += info.st_size
227
+ except FileNotFoundError: # Xet can rotate its own cache files.
228
+ pass
229
+ return total
230
+
231
+
232
+ def require_space(work, needed, budget, reserve):
233
+ if work_usage(work) + needed > budget:
234
+ raise RuntimeError("Staging budget exhausted (including cache); upload existing shards or increase --max-staging-gib")
235
+ if shutil.disk_usage(work).free < needed + reserve:
236
+ raise RuntimeError("Insufficient free disk space; reserve is controlled by --min-free-gib")
237
+
238
+
239
+ @contextmanager
240
+ def work_lock(work):
241
+ work.mkdir(parents=True, exist_ok=True)
242
+ with (work / ".lock").open("a") as stream:
243
+ try:
244
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
245
+ except BlockingIOError as exc:
246
+ raise RuntimeError(f"Another process is using {work}") from exc
247
+ yield
248
+
249
+
250
+ def configure_cache(work):
251
+ # Leave HF_HOME/HF_TOKEN_PATH alone so an existing hf login remains usable.
252
+ for variable, directory in (("HF_HUB_CACHE", work / "cache" / "hub"),
253
+ ("HF_XET_CACHE", work / "cache" / "xet"),
254
+ ("TMPDIR", work / "tmp")):
255
+ directory.mkdir(parents=True, exist_ok=True)
256
+ os.environ[variable] = str(directory)
257
+ os.environ["HF_XET_CHUNK_CACHE_SIZE_BYTES"] = "0"
258
+ os.environ["HF_XET_SHARD_CACHE_SIZE_LIMIT"] = str(GIB)
259
+
260
+
261
+ class HashWriter:
262
+ def __init__(self, stream):
263
+ self.stream = stream
264
+ self.digest = hashlib.sha256()
265
+
266
+ def write(self, data):
267
+ count = self.stream.write(data)
268
+ self.digest.update(data[:count])
269
+ return count
270
+
271
+
272
+ def pack_shard(plan, shard, work, budget, reserve):
273
+ target = work / shard["path"]
274
+ target.parent.mkdir(parents=True, exist_ok=True)
275
+ partial = target.with_suffix(".tar.partial")
276
+ # These are only our own unfinished/generated archives, never source data.
277
+ partial.unlink(missing_ok=True)
278
+ require_space(work, shard["size"], budget, reserve)
279
+ log(f"[pack] {shard['path']} ({shard['size'] / GIB:.3f} GiB)")
280
+ episodes = plan["episodes"][shard["start"]:shard["stop"]]
281
+ with partial.open("wb") as output:
282
+ writer = HashWriter(output)
283
+ with tarfile.open(fileobj=writer, mode="w|", format=tarfile.PAX_FORMAT,
284
+ bufsize=1024 * 1024) as archive:
285
+ for episode in episodes:
286
+ folder = Path(plan["source"]) / episode["episode_id"]
287
+ if inspect_tree(folder, False)["fingerprint"] != episode["fingerprint"]:
288
+ raise ValueError(f"Source changed: {folder}")
289
+ for path, relative, info in tree_entries(folder):
290
+ member = tar_info(relative, info)
291
+ if member.isdir():
292
+ archive.addfile(member)
293
+ else:
294
+ descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
295
+ with os.fdopen(descriptor, "rb") as stream:
296
+ if signature(os.fstat(stream.fileno())) != signature(info):
297
+ raise ValueError(f"Source changed: {path}")
298
+ archive.addfile(member, stream)
299
+ if signature(os.fstat(stream.fileno())) != signature(info):
300
+ raise ValueError(f"Source changed while packing: {path}")
301
+ if inspect_tree(folder, False)["fingerprint"] != episode["fingerprint"]:
302
+ raise ValueError(f"Source changed while packing: {folder}")
303
+ output.flush()
304
+ os.fsync(output.fileno())
305
+ if partial.stat().st_size != shard["size"]:
306
+ raise ValueError(f"TAR size does not match plan: {partial}")
307
+ os.replace(partial, target)
308
+ return dict(path=shard["path"], size=shard["size"], sha256=writer.digest.hexdigest(),
309
+ episode_count=len(episodes), verified=False)
310
+
311
+
312
+ def get_record(plan, shard, state, work, budget, reserve):
313
+ record = state["shards"].get(shard["path"])
314
+ target = work / shard["path"]
315
+ if record and target.exists():
316
+ if target.stat().st_size != record["size"] or sha256_file(target) != record["sha256"]:
317
+ raise ValueError(f"Local shard is corrupted; remove this generated TAR and rerun: {target}")
318
+ return record
319
+ if target.exists():
320
+ # A crash between rename and state persistence: regenerate, never trust an orphan.
321
+ target.unlink()
322
+ new_record = pack_shard(plan, shard, work, budget, reserve)
323
+ if record and (record["size"], record["sha256"]) != (new_record["size"], new_record["sha256"]):
324
+ raise ValueError(f"Recreated shard differs from saved checksum: {target}")
325
+ state["shards"][shard["path"]] = new_record
326
+ atomic_json(work / "state.json", state)
327
+ return new_record
328
+
329
+
330
+ class Hub:
331
+ """Small transport boundary so publication/recovery can be tested offline."""
332
+
333
+ def __init__(self, repo_id, revision=None):
334
+ try:
335
+ from huggingface_hub import HfApi
336
+ except ImportError as exc:
337
+ raise RuntimeError("Install scripts/requirements-droid-hf.txt in Python >= 3.10") from exc
338
+ self.api = HfApi()
339
+ self.repo_id = repo_id
340
+ # Resolve to an immutable commit for reads; CAS parent_commit protects writes.
341
+ self.revision = self.api.repo_info(repo_id, repo_type="dataset", revision=revision).sha
342
+
343
+ def files(self, paths):
344
+ result = {}
345
+ for start in range(0, len(paths), 100):
346
+ entries = self.api.get_paths_info(self.repo_id, paths[start:start + 100],
347
+ repo_type="dataset", revision=self.revision)
348
+ for entry in entries:
349
+ if not hasattr(entry, "size"):
350
+ raise ValueError(f"Expected remote file, found directory: {entry.path}")
351
+ lfs = entry.lfs
352
+ sha = (lfs.get("sha256") if isinstance(lfs, dict)
353
+ else getattr(lfs, "sha256", None))
354
+ result[entry.path] = dict(size=entry.size, sha256=sha)
355
+ return result
356
+
357
+ def chunks(self, path):
358
+ from huggingface_hub import hf_hub_url
359
+ from huggingface_hub.utils import build_hf_headers, get_session
360
+ url = hf_hub_url(self.repo_id, path, repo_type="dataset", revision=self.revision)
361
+ session = get_session()
362
+ headers = build_hf_headers()
363
+ if callable(getattr(session, "stream", None)):
364
+ # huggingface_hub 1.x uses httpx.Client.
365
+ with session.stream("GET", url, headers=headers,
366
+ follow_redirects=True, timeout=120) as response:
367
+ response.raise_for_status()
368
+ yield from response.iter_bytes(chunk_size=4 * 1024 * 1024)
369
+ else:
370
+ # huggingface_hub 0.x uses requests.Session. Its `stream` attribute
371
+ # is a boolean default, not a method; streaming is a GET argument.
372
+ with session.get(url, headers=headers, stream=True,
373
+ allow_redirects=True, timeout=120) as response:
374
+ response.raise_for_status()
375
+ yield from response.iter_content(chunk_size=4 * 1024 * 1024)
376
+
377
+ def read_json(self, path):
378
+ return json.loads(b"".join(self.chunks(path)))
379
+
380
+ def commit(self, files, message):
381
+ from huggingface_hub import CommitOperationAdd
382
+ result = self.api.create_commit(
383
+ repo_id=self.repo_id, repo_type="dataset", parent_commit=self.revision,
384
+ operations=[CommitOperationAdd(path_in_repo=path, path_or_fileobj=str(local))
385
+ for path, local in files.items()], commit_message=message)
386
+ self.revision = result.oid
387
+
388
+ def download(self, path, directory):
389
+ return Path(self.api.hf_hub_download(self.repo_id, path, repo_type="dataset",
390
+ revision=self.revision, local_dir=directory))
391
+
392
+
393
+ def matches_remote(hub, path, record, remote):
394
+ if remote is None:
395
+ return False
396
+ if remote["size"] != record["size"]:
397
+ raise ValueError(f"Remote size conflict; refusing to overwrite {path}")
398
+ digest = remote.get("sha256")
399
+ if not digest:
400
+ log(f"[verify] Remote SHA-256 unavailable; streaming {path} to hash (no disk copy)")
401
+ hasher = hashlib.sha256()
402
+ count = 0
403
+ for block in hub.chunks(path):
404
+ hasher.update(block)
405
+ count += len(block)
406
+ if count != record["size"]:
407
+ raise ValueError(f"Incomplete remote stream: {path}")
408
+ digest = hasher.hexdigest()
409
+ if digest != record["sha256"]:
410
+ raise ValueError(f"Remote checksum conflict; refusing to overwrite {path}")
411
+ return True
412
+
413
+
414
+ def dataset_readme(plan, complete):
415
+ return ("---\nviewer: false\n---\n\n# DROID episodes\n\n"
416
+ f"Publication status: **{'complete' if complete else 'uploading — do not use yet'}**.\n\n"
417
+ f"{len(plan['episodes']):,} episodes in {len(plan['shards']):,} uncompressed TAR shards. "
418
+ "Episodes are ordered lexicographically by folder name; no episode spans shards.\n\n"
419
+ "All original file contents and directory names are preserved, including RGB, depth, "
420
+ "TCP, actions, observations, calibration and metadata. TAR ownership, permissions "
421
+ "and timestamps are normalized. No image/video re-encoding is performed.\n\n"
422
+ "Use `episodes.jsonl` to map episode IDs to shards and filter language instructions, "
423
+ "lab, status or frame count. `shards.jsonl` provides byte sizes and SHA-256 hashes. "
424
+ "Each TAR extracts to original episode directories. A subset requires only its "
425
+ "corresponding shards, but each selected shard is downloaded in full.\n\n"
426
+ "Download `droid_hf.py` and `requirements-droid-hf.txt` from this repository. "
427
+ "With Python >= 3.10, install the requirements and run:\n\n"
428
+ "```bash\npython droid_hf.py download --repo-id OWNER/DATASET --shards 0-2 "
429
+ "--output-dir ./episodes\n"
430
+ "python droid_hf.py download --repo-id OWNER/DATASET --episodes-file ids.txt "
431
+ "--output-dir ./episodes\n```\n\n"
432
+ "The download command verifies and extracts one shard at a time. "
433
+ "It removes verified local archives after extraction unless `--keep-archives` is set. "
434
+ "Existing differing episode directories are never overwritten.\n")
435
+
436
+
437
+ def write_publication(plan, state, work, complete):
438
+ directory = work / "publication"
439
+ directory.mkdir(exist_ok=True)
440
+ (directory / "README.md").write_text(dataset_readme(plan, complete), encoding="utf-8")
441
+ marker = dict(format_version=FORMAT_VERSION, plan_id=plan["plan_id"],
442
+ complete=complete, episode_count=len(plan["episodes"]),
443
+ shard_count=len(plan["shards"]))
444
+ files = {"README.md": directory / "README.md"}
445
+ if complete:
446
+ with (directory / "episodes.jsonl").open("wb") as stream:
447
+ for episode in plan["episodes"]:
448
+ public = {key: value for key, value in episode.items()
449
+ if key not in ("fingerprint", "tar_bytes")}
450
+ stream.write(canonical(public) + b"\n")
451
+ with (directory / "shards.jsonl").open("wb") as stream:
452
+ for shard in plan["shards"]:
453
+ record = state["shards"][shard["path"]]
454
+ if not record["verified"]:
455
+ raise ValueError(f"Cannot publish unverified shard: {shard['path']}")
456
+ stream.write(canonical({key: value for key, value in record.items()
457
+ if key != "verified"}) + b"\n")
458
+ marker["indexes"] = {}
459
+ for name in ("episodes.jsonl", "shards.jsonl"):
460
+ files[name] = directory / name
461
+ marker["indexes"][name] = dict(size=files[name].stat().st_size,
462
+ sha256=sha256_file(files[name]))
463
+ files["droid_hf.py"] = Path(__file__).resolve()
464
+ files["requirements-droid-hf.txt"] = Path(__file__).with_name("requirements-droid-hf.txt")
465
+ atomic_json(directory / "publication.json", marker)
466
+ files["publication.json"] = directory / "publication.json"
467
+ return files
468
+
469
+
470
+ def publish(plan, state, work, hub, budget, reserve, batch_size=8):
471
+ """Only delete archives after remote verification AND durable state persistence."""
472
+ if state.get("repo_id") not in (None, hub.repo_id):
473
+ raise ValueError("This work directory is bound to a different repository")
474
+ marker_info = hub.files(["publication.json"])
475
+ marker = hub.read_json("publication.json") if marker_info else None
476
+ if marker and marker.get("plan_id") != plan["plan_id"]:
477
+ raise ValueError("Remote repository belongs to a different publication plan")
478
+ state["repo_id"] = hub.repo_id
479
+ atomic_json(work / "state.json", state)
480
+ remote = hub.files([shard["path"] for shard in plan["shards"]])
481
+ if not marker:
482
+ if remote or hub.files(["episodes.jsonl", "shards.jsonl"]):
483
+ raise ValueError("Remote dataset has no matching publication marker; use an empty dataset repository")
484
+ hub.commit(write_publication(plan, state, work, False), "Initialize DROID shard publication")
485
+ pending = []
486
+ for shard in plan["shards"]:
487
+ record = state["shards"].get(shard["path"])
488
+ if record and matches_remote(hub, shard["path"], record, remote.get(shard["path"])):
489
+ record["verified"] = True
490
+ atomic_json(work / "state.json", state)
491
+ (work / shard["path"]).unlink(missing_ok=True)
492
+ else:
493
+ if record:
494
+ record["verified"] = False
495
+ pending.append(shard)
496
+ atomic_json(work / "state.json", state)
497
+ if marker and marker.get("complete") and not pending:
498
+ log("All shards already verified remotely; publication is complete.")
499
+ return
500
+ # Restoring a missing remote shard invalidates the previously complete marker.
501
+ if marker and marker.get("complete"):
502
+ hub.commit(write_publication(plan, state, work, False), "Resume incomplete DROID publication")
503
+ offset = 0
504
+ while offset < len(pending):
505
+ batch = []
506
+ for shard in pending[offset:offset + batch_size]:
507
+ target = work / shard["path"]
508
+ if batch and not target.exists() and work_usage(work) + shard["size"] > budget:
509
+ break
510
+ record = get_record(plan, shard, state, work, budget, reserve)
511
+ if matches_remote(hub, shard["path"], record, remote.get(shard["path"])):
512
+ record["verified"] = True
513
+ atomic_json(work / "state.json", state)
514
+ target.unlink(missing_ok=True)
515
+ else:
516
+ batch.append(shard)
517
+ offset += 1
518
+ if not batch:
519
+ continue
520
+ # Account for caches as well as archives. Xet limits are soft; disk reserve
521
+ # and bounded batches leave headroom rather than promising an OS quota.
522
+ require_space(work, 0, budget, reserve)
523
+ log(f"[upload] {len(batch)} shards; staging {work_usage(work) / GIB:.3f} GiB")
524
+ hub.commit({shard["path"]: work / shard["path"] for shard in batch},
525
+ f"Upload DROID shards {batch[0]['path']} through {batch[-1]['path']}")
526
+ uploaded = hub.files([shard["path"] for shard in batch])
527
+ for shard in batch:
528
+ record = state["shards"][shard["path"]]
529
+ if not matches_remote(hub, shard["path"], record, uploaded.get(shard["path"])):
530
+ raise ValueError(f"Committed shard is not visible remotely: {shard['path']}")
531
+ record["verified"] = True
532
+ atomic_json(work / "state.json", state)
533
+ (work / shard["path"]).unlink()
534
+ log(f"[verified, local TAR removed] {shard['path']}")
535
+ verify_source(plan)
536
+ require_space(work, 0, budget, reserve)
537
+ hub.commit(write_publication(plan, state, work, True), "Complete DROID publication and publish subset indexes")
538
+ log(f"Complete: https://huggingface.co/datasets/{hub.repo_id}")
539
+
540
+
541
+ def validate_archive_path(name):
542
+ path = PurePosixPath(name)
543
+ if (path.is_absolute() or not path.parts or ".." in path.parts
544
+ or "\\" in name or "\0" in name or name.rstrip("/") != path.as_posix()):
545
+ raise ValueError(f"Unsafe archive path: {name!r}")
546
+ safe_id(path.parts[0])
547
+ return path
548
+
549
+
550
+ def content_signature(folder):
551
+ result = []
552
+ for path, relative, info in tree_entries(folder):
553
+ result.append((relative, "directory" if stat.S_ISDIR(info.st_mode) else sha256_file(path)))
554
+ return result
555
+
556
+
557
+ def extract_selected(archive_path, episodes, wanted, output, receipts, save_receipts, shard_hash):
558
+ """Extract into a same-filesystem staging directory before publishing episodes."""
559
+ stage = output / ".droid_hf_extract"
560
+ if stage.is_symlink():
561
+ raise ValueError(f"Refusing extraction through symlink: {stage}")
562
+ if stage.exists():
563
+ owner = stage / ".owner.json"
564
+ if not owner.is_file() or read_json(owner) != {"tool": "droid_hf", "format_version": FORMAT_VERSION}:
565
+ raise ValueError(f"Extraction scratch path already exists and is not owned by this tool: {stage}")
566
+ shutil.rmtree(stage) # Dedicated scratch tree from our interrupted extraction.
567
+ stage.mkdir()
568
+ atomic_json(stage / ".owner.json", {"tool": "droid_hf", "format_version": FORMAT_VERSION})
569
+ seen = set()
570
+ extracted_bytes = {name: 0 for name in wanted}
571
+ try:
572
+ with tarfile.open(archive_path, "r|") as archive:
573
+ for member in archive:
574
+ path = validate_archive_path(member.name)
575
+ if path.as_posix() in seen:
576
+ raise ValueError(f"Duplicate TAR member: {member.name}")
577
+ seen.add(path.as_posix())
578
+ if path.parts[0] not in episodes:
579
+ raise ValueError(f"Unexpected episode in TAR: {member.name}")
580
+ if not (member.isdir() or member.isfile()) or member.issparse():
581
+ raise ValueError(f"Unsupported TAR member (links/devices forbidden): {member.name}")
582
+ if path.parts[0] not in wanted:
583
+ continue
584
+ destination = stage.joinpath(*path.parts)
585
+ if member.isdir():
586
+ destination.mkdir(parents=True, exist_ok=True)
587
+ else:
588
+ extracted_bytes[path.parts[0]] += member.size
589
+ if extracted_bytes[path.parts[0]] > episodes[path.parts[0]]["bytes"]:
590
+ raise ValueError(f"TAR payload exceeds indexed episode size: {path.parts[0]}")
591
+ destination.parent.mkdir(parents=True, exist_ok=True)
592
+ with archive.extractfile(member) as source, destination.open("xb") as target:
593
+ shutil.copyfileobj(source, target, 1024 * 1024)
594
+ for name in sorted(wanted):
595
+ extracted = stage / name
596
+ details = inspect_tree(extracted, False)
597
+ expected = episodes[name]
598
+ for key in ("bytes", "file_count", "directory_count"):
599
+ if details[key] != expected[key]:
600
+ raise ValueError(f"Extracted {key} differs from index: {name}")
601
+ target = output / name
602
+ if target.is_symlink():
603
+ raise ValueError(f"Refusing to overwrite a symlink: {target}")
604
+ if target.exists():
605
+ if content_signature(target) != content_signature(extracted):
606
+ raise ValueError(f"Existing episode differs; refusing to overwrite: {target}")
607
+ else:
608
+ os.replace(extracted, target)
609
+ receipts[name] = dict(sha256=shard_hash, fingerprint=inspect_tree(target, False)["fingerprint"])
610
+ # One durable receipt update per shard avoids rewriting a growing 34k-row
611
+ # index once per episode. A crash gap is recovered by content comparison.
612
+ save_receipts()
613
+ finally:
614
+ shutil.rmtree(stage)
615
+
616
+
617
+ def parse_shards(value, count):
618
+ indexes = set()
619
+ for part in value.split(","):
620
+ ends = part.strip().split("-")
621
+ if len(ends) not in (1, 2) or not all(item.isdigit() for item in ends):
622
+ raise ValueError("--shards must look like 0,2,5-8")
623
+ first, last = int(ends[0]), int(ends[-1])
624
+ if first > last or last >= count:
625
+ raise ValueError(f"Shard index out of range: {part} (total {count})")
626
+ indexes.update(range(first, last + 1))
627
+ return indexes
628
+
629
+
630
+ def download_subset(hub, work, output, shard_selection=None, ids_file=None, all_shards=False,
631
+ keep_archives=False, reserve=5 * GIB):
632
+ marker = hub.read_json("publication.json")
633
+ if marker.get("format_version") != FORMAT_VERSION or not marker.get("complete"):
634
+ raise ValueError("Dataset publication is not complete or uses an unsupported format")
635
+ indexes = {}
636
+ for name in ("episodes.jsonl", "shards.jsonl"):
637
+ path = hub.download(name, work / "indexes")
638
+ expected = marker["indexes"][name]
639
+ if path.stat().st_size != expected["size"] or sha256_file(path) != expected["sha256"]:
640
+ raise ValueError(f"Index checksum mismatch: {name}")
641
+ with path.open(encoding="utf-8") as stream:
642
+ indexes[name] = [json.loads(line) for line in stream if line.strip()]
643
+ shards = indexes["shards.jsonl"]
644
+ episodes = {safe_id(ep["episode_id"]): ep for ep in indexes["episodes.jsonl"]}
645
+ if (len(episodes) != len(indexes["episodes.jsonl"]) or len(episodes) != marker["episode_count"]
646
+ or len(shards) != marker["shard_count"]):
647
+ raise ValueError("Invalid/duplicate index entries")
648
+ for index, shard in enumerate(shards):
649
+ if shard["path"] != f"data/shard-{index:06d}.tar":
650
+ raise ValueError(f"Unexpected shard path: {shard['path']}")
651
+ known_paths = {shard["path"] for shard in shards}
652
+ if any(ep["shard"] not in known_paths for ep in episodes.values()):
653
+ raise ValueError("Episode index references an unknown shard")
654
+ if ids_file is not None:
655
+ wanted = {safe_id(line.strip()) for line in Path(ids_file).read_text(encoding="utf-8").splitlines()
656
+ if line.strip()}
657
+ if not wanted or wanted - episodes.keys():
658
+ raise ValueError(f"Empty/unknown episode selection: {sorted(wanted - episodes.keys())[:10]}")
659
+ selected_paths = {episodes[name]["shard"] for name in wanted}
660
+ else:
661
+ chosen = set(range(len(shards))) if all_shards else parse_shards(shard_selection, len(shards))
662
+ selected_paths = {shards[index]["path"] for index in chosen}
663
+ wanted = {name for name, ep in episodes.items() if ep["shard"] in selected_paths}
664
+ output.mkdir(parents=True, exist_ok=True)
665
+ receipt_path = work / "downloads.json"
666
+ receipt_state = read_json(receipt_path) if receipt_path.exists() else dict(
667
+ repo_id=hub.repo_id, output=str(output), episodes={})
668
+ if receipt_state["repo_id"] != hub.repo_id or receipt_state["output"] != str(output):
669
+ raise ValueError("Download directory is bound to another repository/output; choose a new --download-dir")
670
+ receipts = receipt_state["episodes"]
671
+
672
+ def save():
673
+ atomic_json(receipt_path, receipt_state)
674
+
675
+ total = sum(shard["size"] for shard in shards if shard["path"] in selected_paths)
676
+ log(f"Selected {len(wanted)} episodes in {len(selected_paths)} shards ({total / GIB:.3f} GiB before resume skips)")
677
+ # Also protect shared output directories when different download caches are used.
678
+ with work_lock(output):
679
+ for shard in shards:
680
+ if shard["path"] not in selected_paths:
681
+ continue
682
+ members = {name: ep for name, ep in episodes.items() if ep["shard"] == shard["path"]}
683
+ if len(members) != shard["episode_count"]:
684
+ raise ValueError(f"Shard episode count mismatch: {shard['path']}")
685
+ remaining = wanted & members.keys()
686
+ for name in list(remaining):
687
+ receipt = receipts.get(name)
688
+ destination = output / name
689
+ if receipt and receipt["sha256"] == shard["sha256"] and destination.exists():
690
+ if inspect_tree(destination, False)["fingerprint"] != receipt["fingerprint"]:
691
+ raise ValueError(f"Downloaded episode changed locally: {destination}")
692
+ remaining.remove(name)
693
+ if not remaining:
694
+ if not keep_archives:
695
+ (work / "archives" / shard["path"]).unlink(missing_ok=True)
696
+ log(f"[already extracted] {shard['path']}")
697
+ continue
698
+ extraction_bytes = sum(members[name]["tar_bytes"] if "tar_bytes" in members[name]
699
+ else members[name]["bytes"] + 4096 * (members[name]["file_count"]
700
+ + members[name]["directory_count"])
701
+ for name in remaining)
702
+ shared_disk = work.stat().st_dev == output.stat().st_dev
703
+ if shutil.disk_usage(work).free < shard["size"] + reserve + (extraction_bytes if shared_disk else 0):
704
+ raise RuntimeError("Insufficient download disk space")
705
+ if not shared_disk and shutil.disk_usage(output).free < extraction_bytes + reserve:
706
+ raise RuntimeError("Insufficient extraction disk space")
707
+ archive = hub.download(shard["path"], work / "archives")
708
+ if archive.stat().st_size != shard["size"] or sha256_file(archive) != shard["sha256"]:
709
+ raise ValueError(f"Archive checksum mismatch; remove the local archive and rerun: {archive}")
710
+ extract_selected(archive, members, remaining, output, receipts, save, shard["sha256"])
711
+ if not keep_archives:
712
+ archive.unlink()
713
+ log(f"[extracted] {shard['path']}: {len(remaining)} episodes")
714
+
715
+
716
+ def positive_gib(value):
717
+ result = float(value)
718
+ if not math.isfinite(result) or result <= 0:
719
+ raise argparse.ArgumentTypeError("Must be a finite number > 0")
720
+ return max(1, int(result * GIB))
721
+
722
+
723
+ def nonnegative_gib(value):
724
+ result = float(value)
725
+ if not math.isfinite(result) or result < 0:
726
+ raise argparse.ArgumentTypeError("Must be a finite number >= 0")
727
+ return int(result * GIB)
728
+
729
+
730
+ def main(argv=None):
731
+ parser = argparse.ArgumentParser(description=__doc__)
732
+ commands = parser.add_subparsers(dest="command", required=True)
733
+ for command in ("scan", "pack", "upload"):
734
+ sub = commands.add_parser(command)
735
+ sub.add_argument("--source", type=Path, default=ROOT / "droid_episodes")
736
+ sub.add_argument("--shard-size-gib", type=positive_gib, default=2 * GIB)
737
+ if command != "scan":
738
+ sub.add_argument("--work-dir", type=Path, default=Path("/mnt/ssd/phs/droid_hf_upload"))
739
+ sub.add_argument("--max-staging-gib", type=positive_gib, default=32 * GIB)
740
+ sub.add_argument("--min-free-gib", type=nonnegative_gib, default=100 * GIB)
741
+ if command == "pack":
742
+ sub.add_argument("--max-shards", type=int, default=8)
743
+ if command == "upload":
744
+ sub.add_argument("--repo-id", default="", help="Required: OWNER/DATASET (left empty intentionally)")
745
+ sub.add_argument("--batch-size", type=int, default=8, choices=range(1, 9))
746
+ sub = commands.add_parser("download")
747
+ sub.add_argument("--repo-id", default="", help="Required: OWNER/DATASET")
748
+ sub.add_argument("--revision", default=None, help="Optional commit SHA/tag; reads are pinned to one commit")
749
+ sub.add_argument("--output-dir", type=Path, default=Path("droid_episodes_download"))
750
+ sub.add_argument("--download-dir", type=Path, default=Path("droid_download_cache"))
751
+ selection = sub.add_mutually_exclusive_group(required=True)
752
+ selection.add_argument("--shards", help="Zero-based shard numbers, e.g. 0,2,5-8")
753
+ selection.add_argument("--episodes-file", type=Path, help="UTF-8 text file: one original episode ID per line")
754
+ selection.add_argument("--all", action="store_true", help="Explicitly download the complete dataset")
755
+ sub.add_argument("--keep-archives", action="store_true")
756
+ sub.add_argument("--min-free-gib", type=nonnegative_gib, default=5 * GIB)
757
+ args = parser.parse_args(argv)
758
+ try:
759
+ if args.command in ("upload", "download") and (not args.repo_id or len(args.repo_id.split("/")) != 2
760
+ or not all(args.repo_id.split("/"))):
761
+ raise ValueError("Fill in --repo-id OWNER/DATASET; no repository is assumed or created automatically")
762
+ if args.command == "scan":
763
+ summarize(make_plan(args.source, args.shard_size_gib))
764
+ return 0
765
+ if args.command == "download":
766
+ work, output = args.download_dir.resolve(), args.output_dir.resolve()
767
+ if work == output or work in output.parents or output in work.parents:
768
+ raise ValueError("Download cache and output must be separate, non-nested directories")
769
+ with work_lock(work):
770
+ configure_cache(work)
771
+ hub = Hub(args.repo_id, args.revision)
772
+ download_subset(hub, work, output, args.shards, args.episodes_file, args.all,
773
+ args.keep_archives, args.min_free_gib)
774
+ return 0
775
+ source, work = args.source.resolve(), args.work_dir.resolve()
776
+ if work == source or source in work.parents or work in source.parents:
777
+ raise ValueError("Source and work directory must be separate, non-nested directories")
778
+ if args.command == "pack" and args.max_shards < 1:
779
+ raise ValueError("--max-shards must be positive")
780
+ with work_lock(work):
781
+ require_space(work, 0, args.max_staging_gib, args.min_free_gib)
782
+ # Fail authentication/repository lookup before a potentially long source scan.
783
+ hub = None
784
+ if args.command == "upload":
785
+ configure_cache(work)
786
+ hub = Hub(args.repo_id)
787
+ plan = load_or_plan(source, work, args.shard_size_gib)
788
+ summarize(plan)
789
+ state_path = work / "state.json"
790
+ state = read_json(state_path) if state_path.exists() else dict(plan_id=plan["plan_id"], shards={})
791
+ if state.get("plan_id") != plan["plan_id"]:
792
+ raise ValueError("State and plan belong to different publications")
793
+ if args.command == "upload":
794
+ publish(plan, state, work, hub, args.max_staging_gib, args.min_free_gib, args.batch_size)
795
+ else:
796
+ count = 0
797
+ for shard in plan["shards"]:
798
+ if state["shards"].get(shard["path"], {}).get("verified"):
799
+ continue
800
+ get_record(plan, shard, state, work, args.max_staging_gib, args.min_free_gib)
801
+ count += 1
802
+ if count == args.max_shards:
803
+ break
804
+ log(f"Prepared {count} local shards; no network/upload performed. Work directory: {work}")
805
+ return 0
806
+ except KeyboardInterrupt:
807
+ log("Interrupted. Source files were not changed. Rerun the same command to resume.")
808
+ return 130
809
+ except Exception as exc:
810
+ print(f"ERROR: {exc}\nSource files are never deleted. Fix the error and rerun the same command.", file=sys.stderr)
811
+ return 1
812
+
813
+
814
+ if __name__ == "__main__":
815
+ raise SystemExit(main())
episodes.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b38e73ede247522e7a18ca2600e418ed5ffe22947a5e4b485331d81b3408dbbb
3
+ size 13846267
publication.json CHANGED
@@ -1 +1 @@
1
- {"complete":false,"episode_count":33966,"format_version":1,"plan_id":"1c4ea6c01cd1b4fbfda774efdb7a039cb8fd06325add28edfdfad12745d01b1e","shard_count":1018}
 
1
+ {"complete":true,"episode_count":33966,"format_version":1,"indexes":{"episodes.jsonl":{"sha256":"b38e73ede247522e7a18ca2600e418ed5ffe22947a5e4b485331d81b3408dbbb","size":13846267},"shards.jsonl":{"sha256":"2d678e56a995a6cf7793dbd41c35f8e95c57d658f54868be55ad564a8f51f7de","size":148609}},"plan_id":"1c4ea6c01cd1b4fbfda774efdb7a039cb8fd06325add28edfdfad12745d01b1e","shard_count":1018}
requirements-droid-hf.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Python >= 3.10; the existing caliball environment already has these versions.
2
+ huggingface_hub==1.31.0
3
+ hf_xet==1.6.0
shards.jsonl ADDED
The diff for this file is too large to render. See raw diff