| |
| """Apply instruction strings into ArenaVlaSafety HDF5 files. |
| |
| Input is a JSONL file whose each line contains at least: |
| - path: path to HDF5 relative to --base-dir (or an absolute path) |
| - instruction or instructions: text string, or a list of strings |
| |
| For every HDF5, this script writes the instruction into all groups under |
| `data/<timestamp>/instruction`. If the dataset is missing, it will be created |
| as UTF-8 variable-length string. If it already exists (scalar or array), it is |
| overwritten with the provided text. |
| |
| Example: |
| python scripts/apply_instructions.py \ |
| --instructions /path/to/instructions.jsonl \ |
| --base-dir /mnt/nvme1/WS/czx/data/trainv0 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from pathlib import Path |
| from typing import Any, Optional |
|
|
| import h5py |
| import numpy as np |
|
|
|
|
| def _resolve_h5(base_dir: Path, file_path: str) -> Path: |
| p = Path(file_path) |
| if not p.is_absolute(): |
| p = base_dir / p |
| return p.expanduser().resolve() |
|
|
|
|
| def _pick_instruction(obj: Any) -> Optional[str]: |
| |
| if obj is None: |
| return None |
| if isinstance(obj, str): |
| return obj.strip() or None |
| if isinstance(obj, (list, tuple)): |
| for item in obj: |
| if isinstance(item, str) and item.strip(): |
| return item.strip() |
| return None |
| return None |
|
|
|
|
| def _write_instruction(h5_path: Path, text: str) -> None: |
| text = str(text) |
| with h5py.File(h5_path, "a") as f: |
| data_group = f.get("data") |
| if data_group is None: |
| raise ValueError(f"{h5_path} missing 'data' group") |
| |
| str_dtype = h5py.string_dtype(encoding="utf-8") |
| for ts_key in list(data_group.keys()): |
| grp = data_group[ts_key] |
| ds = grp.get("instruction") |
| if ds is None: |
| ds = grp.create_dataset("instruction", shape=(), dtype=str_dtype) |
| ds[...] = text |
| continue |
| |
| if ds.shape == (): |
| try: |
| ds[...] = text |
| except TypeError: |
| |
| del grp["instruction"] |
| ds = grp.create_dataset("instruction", shape=(), dtype=str_dtype) |
| ds[...] = text |
| else: |
| fill = np.empty(ds.shape, dtype=ds.dtype) |
| try: |
| fill[...] = text |
| except TypeError: |
| fill = np.empty(ds.shape, dtype=str) |
| fill[...] = text |
| ds[...] = fill |
|
|
|
|
| def main() -> None: |
| ap = argparse.ArgumentParser(description="Inject instruction text into HDF5 episodes") |
| ap.add_argument("--instructions", required=True, help="Path to JSONL file") |
| ap.add_argument("--base-dir", required=True, help="Base dir to resolve relative HDF5 paths") |
| args = ap.parse_args() |
|
|
| base_dir = Path(args.base_dir).expanduser().resolve() |
| jsonl = Path(args.instructions).expanduser().resolve() |
| if not jsonl.exists(): |
| raise FileNotFoundError(jsonl) |
|
|
| updated = 0 |
| skipped = 0 |
| missing = 0 |
| with jsonl.open("r", encoding="utf-8") as fh: |
| for line in fh: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| rec = json.loads(line) |
| except json.JSONDecodeError: |
| print(f"[WARN] skip invalid JSON: {line[:80]}...") |
| skipped += 1 |
| continue |
| |
| path_field = rec.get("path") or rec.get("relpath") or rec.get("file") or rec.get("h5_path") |
| if not path_field: |
| print("[WARN] skip record without path") |
| skipped += 1 |
| continue |
| instr = ( |
| _pick_instruction(rec.get("instruction")) |
| or _pick_instruction(rec.get("instructions")) |
| ) |
| if not instr: |
| print(f"[WARN] no instruction for {path_field}; skip") |
| skipped += 1 |
| continue |
| h5_path = _resolve_h5(base_dir, str(path_field)) |
| if not h5_path.exists(): |
| print(f"[WARN] missing file: {h5_path}") |
| missing += 1 |
| continue |
| try: |
| _write_instruction(h5_path, instr) |
| updated += 1 |
| except Exception as e: |
| print(f"[ERROR] write failed for {h5_path}: {e}") |
| skipped += 1 |
| print(f"Done. Updated={updated}, Missing={missing}, Skipped={skipped}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|