RoboSteer-Preprocessing / scripts /build_dataset.py
PhoebeCC's picture
Release v1.0.0: verified Level 1 preprocessing assets
ca3d57d verified
Raw History Blame Contribute Delete
19.7 kB
#!/usr/bin/env python3
"""Build the RoboSteer Level 1 publication tree without modifying source assets."""
import argparse
import concurrent.futures
import hashlib
import io
import json
import os
from pathlib import Path
import shutil
import tarfile
import time
import pyarrow as pa
import pyarrow.parquet as pq
VERSION = "v1.0.0"
TEXT = [
("txt_gen", "text/processed/TXT/IMIT/TXT_GEN", "text/txt_imit/txt_gen", "TXT_GEN", 38522),
("txt_comp_hands", "text/processed/TXT/IMIT/TXT_COMP_HANDS", "text/txt_imit/txt_comp_hands", "TXT_COMP_HANDS", 38522),
("txt_comp_legs", "text/processed/TXT/IMIT/TXT_COMP_LEGS", "text/txt_imit/txt_comp_legs", "TXT_COMP_LEGS", 38522),
("txt_fore", "text/processed/TXT/PRED/TXT_FORE", "text/txt_pred/txt_fore", "TXT_FORE", 14333),
("txt_retro", "text/processed/TXT/PRED/TXT_RETRO", "text/txt_pred/txt_retro", "TXT_RETRO", 14333),
("txt_inter", "text/processed/TXT/PRED/TXT_INTER", "text/txt_pred/txt_inter", "TXT_INTER", 7764),
("img_txt", "text/processed/IMG_TXT", "text/img_txt", "IMG_TXT_SKEL", 14333),
("mul_bal_txt", "text/processed/MUL_BAL_TXT", "text/mul_bal_txt", "MUL_BAL", 8193),
("audio_motion_instructions", "audio/processed/whisper_txt_preprocessed", "audio/motion_instructions", "AUDIO_MOTION_INSTRUCTIONS", 38522),
]
def log(*args):
print(time.strftime("%Y-%m-%d %H:%M:%S"), *args, flush=True)
def digest(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(4 * 1024 * 1024), b""):
h.update(block)
return h.hexdigest()
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def write_parquet(path, rows):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".parquet.tmp")
pq.write_table(pa.Table.from_pylist(rows), tmp, compression="zstd", row_group_size=10000)
tmp.replace(path)
def source_id(stem, task):
prefix = "L1_" + task + "_"
if stem.startswith(prefix):
return stem[len(prefix):]
if task == "AUDIO_MOTION_INSTRUCTIONS" and stem.endswith("_audio"):
return stem[:-len("_audio")]
raise ValueError(f"Unrecognized sample naming: {task}: {stem}")
def read_unchanged(path):
before = path.stat()
data = path.read_bytes()
after = path.stat()
assert (before.st_size, before.st_mtime_ns) == (after.st_size, after.st_mtime_ns), path
return data
def build_text(source, release):
manifest = []
ids = {}
for config, src, dst, task, expected in TEXT:
files = sorted((source / src).rglob("*.txt"))
assert len(files) == expected, (src, len(files), expected)
def convert(path):
assert not path.is_symlink(), path
data = read_unchanged(path)
return {
"sample_id": path.stem,
"source_sample_id": source_id(path.stem, task),
"task": task,
"level": "level1",
"source_modality": "audio" if config.startswith("audio_") else "text",
"text": data.decode("utf-8"),
"original_relpath": str(path.relative_to(source)),
"size_bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
}
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
rows = list(pool.map(convert, files))
assert len({x["sample_id"] for x in rows}) == expected
dest = release / "level1" / dst / "data.parquet"
write_parquet(dest, rows)
restored = pq.read_table(dest).to_pylist()
assert len(restored) == expected
for row in restored:
raw = row["text"].encode("utf-8")
assert len(raw) == row["size_bytes"]
assert hashlib.sha256(raw).hexdigest() == row["sha256"]
ids[config] = {x["source_sample_id"] for x in rows}
manifest.append({"config": "level1_" + config, "task": task,
"path": str(dest.relative_to(release)), "records": expected,
"empty_text_records": sum(not x["text"].strip() for x in rows)})
log("TEXT_VERIFIED", config, expected)
return manifest, ids
class HashReader:
def __init__(self, f):
self.f = f
self.hash = hashlib.sha256()
def read(self, n=-1):
data = self.f.read(n)
self.hash.update(data)
return data
def public_relative(value):
if "/public/" in value:
value = value.split("/public/", 1)[1]
p = Path(value)
if p.is_absolute() or ".." in p.parts:
raise ValueError("Image provenance must be relative to public root")
return p.as_posix()
def tar_info(name, size):
entry = tarfile.TarInfo(name)
entry.size = size
entry.mode = 0o644
entry.uid = entry.gid = entry.mtime = 0
return entry
def build_video(source, release, task, target_bytes):
folder = release / "level1/image" / task.lower()
folder.mkdir(parents=True, exist_ok=True)
source_dir = source / "img+mul_bal/output" / task
metadata_dir = source / "img+mul_bal/inputs/keyframe_static_videos" / task
videos = sorted(source_dir.glob("*.mp4"))
assert len(videos) == 14333
assert {p.stem for p in videos} == {p.stem for p in metadata_dir.glob("*.json")}
groups, group, size = [], [], 0
for p in videos:
estimate = ((p.stat().st_size + 511) // 512) * 512 + 8192
if group and size + estimate > target_bytes:
groups.append(group)
group, size = [], 0
group.append(p)
size += estimate
if group:
groups.append(group)
all_rows = []
for i, members in enumerate(groups):
shard = folder / f"videos-{i:05d}-of-{len(groups):05d}.tar"
checkpoint = shard.with_suffix(".index.parquet")
if shard.exists() and checkpoint.exists():
rows = pq.read_table(checkpoint).to_pylist()
assert [x["sample_id"] for x in rows] == [p.stem for p in members]
all_rows.extend(rows)
log("REUSE_SHARD", shard.name)
continue
rows = []
temp = shard.with_suffix(".tar.tmp")
with tarfile.open(temp, "w", format=tarfile.PAX_FORMAT) as tar:
for p in members:
assert not p.is_symlink()
before = p.stat()
meta_path = metadata_dir / (p.stem + ".json")
raw_meta = read_unchanged(meta_path)
meta = json.loads(raw_meta)
assert meta["task_id"] == p.stem
meta["input_images"] = [public_relative(x) for x in meta["input_images"]]
meta["input_images_base"] = "external_public_root"
normalized = (json.dumps(meta, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
with p.open("rb") as f:
reader = HashReader(f)
tar.addfile(tar_info(p.name, before.st_size), reader)
after = p.stat()
assert (before.st_size, before.st_mtime_ns) == (after.st_size, after.st_mtime_ns)
tar.addfile(tar_info(p.stem + ".json", len(normalized)), io.BytesIO(normalized))
rows.append({
"sample_id": p.stem, "source_sample_id": source_id(p.stem, task),
"task": task, "level": "level1", "source_modality": "image",
"shard": str(shard.relative_to(release)), "member_path": p.name,
"metadata_member_path": p.stem + ".json",
"original_relpath": str(p.relative_to(source)),
"size_bytes": before.st_size, "sha256": reader.hash.hexdigest(),
"metadata_sha256": hashlib.sha256(normalized).hexdigest(),
"source_metadata_sha256": hashlib.sha256(raw_meta).hexdigest(),
"text": meta["text"],
"source_duration_seconds": float(meta["source_duration_seconds"]),
"generated_duration_seconds": float(meta["generated_duration_seconds"]),
"timestamps_seconds": meta["timestamps_seconds"],
"static_frame_durations_seconds": meta["static_frame_durations_seconds"],
"input_images": meta["input_images"],
})
temp.replace(shard)
write_parquet(checkpoint, rows)
all_rows.extend(rows)
log("SHARD_WRITTEN", task, shard.name, len(rows), shard.stat().st_size)
assert len(all_rows) == 14333
assert len({x["sample_id"] for x in all_rows}) == 14333
write_parquet(folder / "index.parquet", all_rows)
# Read all tar payloads back, checking hashes and exact archive membership.
for shard in sorted(folder.glob("*.tar")):
wanted = {}
for row in all_rows:
if row["shard"] == str(shard.relative_to(release)):
wanted[row["member_path"]] = row["sha256"]
wanted[row["metadata_member_path"]] = row["metadata_sha256"]
seen = set()
with tarfile.open(shard, "r|") as tar:
for entry in tar:
assert entry.isfile() and entry.name in wanted and entry.name not in seen
f = tar.extractfile(entry)
h = hashlib.sha256()
for block in iter(lambda: f.read(1024 * 1024), b""):
h.update(block)
assert h.hexdigest() == wanted[entry.name]
seen.add(entry.name)
assert seen == set(wanted)
log("SHARD_VERIFIED", task, shard.name)
# Per-shard indexes are kept: they support selective download and resumable builds.
return {"task": task, "path": str(folder.relative_to(release)), "records": len(all_rows),
"shards": len(groups), "source_mp4_bytes": sum(x["size_bytes"] for x in all_rows)}, {
x["source_sample_id"] for x in all_rows}
def build_docs(release, texts, videos, validation):
config = []
for row in texts:
config += [f"- config_name: {row['config']}", " data_files:", " - split: data",
f" path: {row['path']}"]
for row in videos:
config += [f"- config_name: level1_{row['task'].lower()}_index", " data_files:",
" - split: data", f" path: {row['path']}/index.parquet"]
readme = "---\npretty_name: RoboSteer Preprocessing\nlanguage:\n- en\ntags:\n- robosteer\n- preprocessing\n- motion-generation\n- intermediate-assets\nconfigs:\n" + "\n".join(config) + "\n---\n\n"
readme += """# RoboSteer Preprocessing
Reusable intermediate preprocessing assets for RoboSteer. This initial release contains Level 1 processed text instructions and image-conditioned static videos. Other levels and preprocessing stages can be added under their own directories.
## Release v1.0.0
- **213,044 text records** in nine lossless UTF-8 Parquet tables.
- **28,666 original MP4 files**: 14,333 IMG_TXT_HUMAN and 14,333 IMG_TXT_SKEL.
- Independent, uncompressed tar shards contain MP4 files and their normalized JSON metadata.
- Per-sample indexes, release inventory, SHA-256 checksums, and validation report.
These are preprocessing assets, not a declared train/validation/test split. The `data` split means the complete asset collection for a configuration. Audio motion instructions are text derived from audio; audio recordings and raw transcripts are not included. MUL_BAL is included as processed text; this release does not contain MUL_BAL videos. Prediction-video manifests are outside this release scope.
## Layout
```text
level1/
text/txt_imit/{txt_gen,txt_comp_hands,txt_comp_legs}/data.parquet
text/txt_pred/{txt_fore,txt_retro,txt_inter}/data.parquet
text/{img_txt,mul_bal_txt}/data.parquet
audio/motion_instructions/data.parquet
image/{img_txt_human,img_txt_skel}/
videos-00000-of-NNNNN.tar
videos-00000-of-NNNNN.index.parquet
index.parquet
manifests/{assets,validation,provenance}.json
scripts/restore_text.py
scripts/build_dataset.py
SHA256SUMS
CHANGELOG.md
```
## Load text or an index
```python
from datasets import load_dataset
ds = load_dataset("PhoebeCC/RoboSteer-Preprocessing", "level1_txt_gen", split="data", revision="v1.0.0")
video_index = load_dataset("PhoebeCC/RoboSteer-Preprocessing", "level1_img_txt_human_index", split="data", revision="v1.0.0")
```
Text columns: `sample_id`, `source_sample_id`, `task`, `level`, `source_modality`, `text`, `original_relpath`, `size_bytes`, `sha256`. Original UTF-8 bytes, including line endings, can be reconstructed with `text.encode('utf-8')`. Use `scripts/restore_text.py` to restore the original relative file layout.
## Download video shards
```python
from huggingface_hub import snapshot_download
snapshot_download("PhoebeCC/RoboSteer-Preprocessing", repo_type="dataset",
revision="v1.0.0", local_dir="robosteer-preprocessing",
allow_patterns=["level1/image/img_txt_human/*", "level1/manifests/*", "README.md", "SHA256SUMS"])
```
Each tar is independently extractable. The index identifies its repository-relative `shard`, MP4 `member_path`, JSON `metadata_member_path`, and checksums. Video indexes are searchable tables; this release does not configure an embedded-video viewer. Extract each task into a separate folder. MP4 files are preserved byte for byte, without re-encoding.
## Provenance and alignment
`sample_id` preserves the source filename stem. `source_sample_id` removes only the known task prefix (or audio suffix). Use `(task, sample_id)` as an asset key; use `source_sample_id` to join related tasks, without assuming all tasks cover the same samples. Coverage results are recorded in the validation report.
Video metadata originates from existing sidecar JSON files. Metadata text is the original sidecar description, not necessarily the rewritten `text/img_txt` instruction. Image paths are converted to paths relative to the external public-data root. Source duration and generated duration are metadata values, not newly measured properties. The source generator specifies 25 FPS; this packaging run does not probe actual MP4 frame rates. Source images, external task JSONs, model weights, raw audio, audit logs, and organization backups are not bundled.
## Rights and citation
The repository owner has not yet supplied a release license or complete upstream attribution. No blanket open-source license is asserted for these derived assets. Upstream restrictions remain applicable; consult the owner about permitted redistribution and use. Formal benchmark citation and upstream dataset attribution will be added when supplied.
## Reproducibility
See `level1/manifests/provenance.json` for packaging rules and generator fingerprints, `assets.json` for counts, and `validation.json` for checks. `SHA256SUMS` covers all payload and documentation files except itself. SHA-256 verification can be performed with `sha256sum -c SHA256SUMS` after a full download. Release tags identify immutable intended snapshots; pin the tag or commit for experiments. Later assets should extend task-specific paths and receive a new version and changelog entry.
"""
(release / "README.md").write_text(readme)
(release / "CHANGELOG.md").write_text("# Changelog\n\n## v1.0.0 — 2026-09-17\n\nInitial Level 1 release: nine processed-text tables, two static-video tasks, original-name recovery, metadata indexes, and SHA-256 verification. No source text rewriting or video re-encoding.\n")
table = "\n".join(f"| {x['config']} | {x['records']:,} | `{x['path']}` |" for x in texts)
(release / "level1/README.md").write_text("# Level 1 预处理中间资产\n\n本发布目录独立于工作目录,包含本次选定的整理后文本和 IMG_TXT 条件视频。\n\n| 文本配置 | 条数 | 仓库路径 |\n|---|---:|---|\n" + table + "\n\nHUMAN 与 SKEL 各 14,333 个 MP4,保存在 image/ 下独立 tar 分片中;index.parquet 可定位每个视频及 JSON 元数据。已有 JSON 中的服务器绝对图片路径已改为相对于外部 public 根的路径。\n\n音频类仅包含整理后的动作指令;本发布不含音频实体或转写全文。MUL_BAL 目前仅包含文本。各配置的 data 表示完整资产集合,不代表训练集划分。\n\n详见仓库根 README、manifests/ 清单和 SHA256SUMS。\n")
write_json(release / "level1/manifests/assets.json", {"version": VERSION, "text": texts, "videos": videos})
write_json(release / "level1/manifests/validation.json", validation)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, required=True, help="Current level1 work directory")
parser.add_argument("--release", type=Path, required=True, help="Dedicated publication directory")
parser.add_argument("--shard-bytes", type=int, default=1024**3)
args = parser.parse_args()
assert args.source.resolve() != args.release.resolve()
args.release.mkdir(parents=True, exist_ok=True)
text, ids = build_text(args.source, args.release)
videos = []
for task in ["IMG_TXT_HUMAN", "IMG_TXT_SKEL"]:
row, sample_ids = build_video(args.source, args.release, task, args.shard_bytes)
videos.append(row)
ids[task] = sample_ids
validation = {
"text_records": sum(x["records"] for x in text), "video_records": sum(x["records"] for x in videos),
"text_utf8_roundtrip_sha256": "passed for every row",
"video_and_metadata_tar_payload_sha256": "passed for every member",
"duplicate_asset_ids": 0,
"human_skel_matching_source_ids": len(ids["IMG_TXT_HUMAN"] & ids["IMG_TXT_SKEL"]),
"img_text_skel_matching_source_ids": len(ids["img_txt"] & ids["IMG_TXT_SKEL"]),
"empty_text_records": sum(x["empty_text_records"] for x in text),
"mp4_decoding_test": "not performed; lossless packaging only",
}
assert validation["text_records"] == 213044
assert validation["human_skel_matching_source_ids"] == 14333
assert validation["img_text_skel_matching_source_ids"] == 14333
build_docs(args.release, text, videos, validation)
scripts = args.release / "scripts"
scripts.mkdir(exist_ok=True)
shutil.copy2(__file__, scripts / "build_dataset.py")
shutil.copy2(Path(__file__).with_name("restore_text.py"), scripts / "restore_text.py")
generators = [args.source / "img+mul_bal/scripts/build_keyframe_static_videos.py",
args.source.parent / "GEM/scripts/demo/run_img_txt_video_to_motion_fast.sh"]
write_json(args.release / "level1/manifests/provenance.json", {
"release": VERSION, "packaged_date": "2026-09-17", "packaging_script_sha256": digest(Path(__file__)),
"pyarrow_version": pa.__version__, "text_policy": "strict UTF-8; bytes and line endings preserved",
"mp4_policy": "unmodified source bytes", "metadata_policy": "external image paths normalized to public-root-relative",
"shard_target_bytes": args.shard_bytes, "tar_policy": "independent PAX tar, sorted filenames, normalized headers",
"source_generator_fingerprints": {p.name: digest(p) for p in generators},
"source_generation_commit": None, "source_generation_commit_note": "Historical generation commit was not recorded",
})
checks = []
for p in sorted(args.release.rglob("*")):
if p.is_file() and p.name != "SHA256SUMS" and ".cache" not in p.parts:
checks.append(f"{digest(p)} {p.relative_to(args.release).as_posix()}")
(args.release / "SHA256SUMS").write_text("\n".join(checks) + "\n")
log("BUILD_COMPLETE", json.dumps(validation))
if __name__ == "__main__":
main()