File size: 4,819 Bytes
7f97480 | 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 | #!/usr/bin/env python3
"""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]:
# Accept either `instruction` (str) or `instructions` (list[str]/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")
# Use variable-length UTF-8 strings
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
# Scalar dataset
if ds.shape == ():
try:
ds[...] = text
except TypeError:
# Recreate dataset with string dtype
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
# Flexible field names for path
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()
|