IDEALFT_OXT / tools /package_oxt_dataset.py
Alan0928's picture
Apply OXT final-review name, directory, metadata and gripper-area corrections
cc98837 verified
Raw History Blame Contribute Delete
51.2 kB
#!/usr/bin/env python3
"""Package a completed, locally validated Franka FT OXT export; never upload.
Run with the export Python environment after export and QC have finished.
Archives use ZIP_STORED/ZIP64 because Zarr chunks are already compressed.
Native H5/SVO files remain individual files and are not duplicated in archives.
Durable archive verification requires Linux O_DIRECT plus system unzip, dd,
and sha256sum; reads use bounded 64 KiB buffers.
"""
from __future__ import annotations
import argparse
from collections import Counter
from contextlib import ExitStack
from datetime import datetime, timezone
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from oxt_direct_io import DirectIOReader
TASK_COUNTS = {"wipe_board": 38, "push_button": 27, "insert_pen": 30, "hang_tape": 30}
TOOL_FILES = (
"README_oxt_export.txt",
"export_oxt_dataset.py", "oxt_array_mapping.py", "svo_decode.py",
"validate_oxt_export.py", "package_oxt_dataset.py", "preview_oxt_dataset.py",
"fix_oxt_zarr_unicode.py", "repair_oxt_ftp1.py", "test_repair_oxt_ftp1.py",
"repair_oxt_area.py", "test_repair_oxt_area.py",
"oxt_direct_io.py", "oxt_file_cache_recovery.py",
"test_oxt_array_mapping.py", "test_svo_eof_recovery.py", "test_svo_png.py",
"test_oxt_export_storage.py", "test_oxt_packaging.py", "test_oxt_validation_names.py",
)
RUNTIME_PACKAGES = ("numpy", "scipy", "h5py", "zarr", "numcodecs", "opencv-python",
"matplotlib", "Pillow")
def utc_now():
return datetime.now(timezone.utc).isoformat()
def log(message):
print(message, file=sys.stderr, flush=True)
def read_json(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def atomic_text(path, text):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, name = tempfile.mkstemp(prefix="." + path.name + ".", suffix=".partial", dir=path.parent)
temporary = Path(name)
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(text)
stream.flush()
os.fsync(stream.fileno())
os.chmod(temporary, 0o644)
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
def atomic_json(path, value):
atomic_text(path, json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
def safe_path(root, relative):
relative = Path(relative)
if relative.is_absolute() or ".." in relative.parts or any(c in str(relative) for c in "\n\r\\"):
raise ValueError("Unsafe package path: " + str(relative))
path = root / relative
if not path.resolve().is_relative_to(root.resolve()):
raise ValueError("Path escapes package: " + str(relative))
return path
def regular_files(directory):
"""Sorted complete file inventory, refusing symlinks or interrupted writes."""
files = []
for parent, directories, names in os.walk(directory, followlinks=False):
for name in directories + names:
path = Path(parent) / name
if name.startswith(".oxt-write-"):
raise ValueError("Incomplete atomic Zarr write remains; inspect before packaging: " + str(path))
if path.is_symlink():
raise ValueError("Package contains a symlink: " + str(path))
for name in names:
path = Path(parent) / name
if not path.is_file():
raise ValueError("Package entry is not a regular file: " + str(path))
if name.endswith(".partial"):
raise ValueError("Incomplete write remains; inspect before packaging: " + str(path))
files.append(path)
return sorted(files)
def remove_interrupted_packaging_stages(root):
"""Remove only this script's reserved temporary filenames on a rerun.
Packaging is a single-writer operation after export/QC have finished. Other
.partial files are deliberately left in place and rejected by the inventory.
"""
targets = [root / "README.md", root / "SHA256SUMS",
root / "requirements_oxt_export.txt", root / "supplementary_tactile_note.json",
root / "checksums/native_sha256.json", root / "metadata/package_manifest.json",
root / "metadata/field_mapping.json", root / "metadata/array_schema.json",
root / "archives/checksums.txt"]
targets += [root / "tools" / name for name in TOOL_FILES]
for task in TASK_COUNTS:
directory = root / "archives" / task
targets += [directory / (task + ".zarr.zip"), directory / (task + ".zarr.zip.manifest.json")]
for target in targets:
if not target.parent.exists():
continue
if target.parent.is_symlink() or not target.parent.resolve().is_relative_to(root):
raise ValueError("Unsafe packaging staging directory: " + str(target.parent))
prefix = "." + target.name + "."
for path in target.parent.glob(prefix + "*.partial"):
token = path.name[len(prefix):-len(".partial")]
if len(token) == 8 and all(c in "abcdefghijklmnopqrstuvwxyz0123456789_" for c in token):
if path.is_symlink() or not path.is_file():
raise ValueError("Unsafe interrupted staging entry: " + str(path))
log("Removing interrupted packaging stage: " + str(path.relative_to(root)))
path.unlink()
class HashCache:
def __init__(self):
self.entries = {}
@staticmethod
def fingerprint(path):
stat = path.stat()
return (stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns, stat.st_ino, stat.st_dev)
def digest(self, path):
path = Path(path)
before = self.fingerprint(path)
previous = self.entries.get(path)
if previous and previous[0] == before:
return previous[1]
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(64 * 1024), b""):
digest.update(block)
if before != self.fingerprint(path):
raise RuntimeError("File changed while hashing: " + str(path))
result = digest.hexdigest()
self.entries[path] = (before, result)
return result
def check_export(root):
manifest = read_json(root / "metadata/export_manifest.json")
episodes = manifest.get("episodes", [])
if manifest.get("complete") is not True:
raise ValueError("Export is not complete")
counts = Counter(e["task"] for e in episodes)
if dict(counts) != TASK_COUNTS or manifest.get("tasks") != TASK_COUNTS:
raise ValueError("Expected frozen task counts 38/27/30/30")
native_rows = sum(e["source_control_steps"] for e in episodes)
standard_rows = sum(e["exported_steps"] for e in episodes)
ft_samples = sum(e["ft_samples"] for e in episodes)
if (len(episodes), native_rows, ft_samples) != (125, 42320, 295674):
raise ValueError("Frozen source totals do not match 125 episodes / 42320 controls / 295674 FT samples")
for key, value in (("total_episodes", 125), ("control_steps_native", native_rows),
("control_steps_zarr", standard_rows), ("ft_samples_native", ft_samples)):
if manifest.get(key) != value:
raise ValueError("Export manifest total mismatch: " + key)
for key in ("episode_id", "native_path"):
if len({e[key] for e in episodes}) != len(episodes):
raise ValueError("Duplicate export " + key)
found = {p.name for p in (root / "zarr").iterdir()}
if found != {task + ".zarr" for task in TASK_COUNTS}:
raise ValueError("Expected exactly the four completed task Zarr directories")
for task, count in TASK_COUNTS.items():
path = root / "zarr" / (task + ".zarr")
attrs = read_json(path / ".zattrs")
if (read_json(path / ".zgroup").get("zarr_format") != 2
or attrs.get("complete") is not True or attrs.get("committed_episodes") != count):
raise ValueError("Incomplete Zarr task: " + task)
task_rows = [e for e in episodes if e["task"] == task]
end = 0
for episode in task_rows:
if episode["start"] != end or episode["end"] - episode["start"] != episode["exported_steps"]:
raise ValueError("Noncontiguous task episode spans: " + task)
if not 0 < episode["exported_steps"] <= episode["source_control_steps"]:
raise ValueError("Invalid retained row count: " + episode["episode_id"])
end = episode["end"]
if read_json(path / "data/timestamps/.zarray")["shape"] != [end]:
raise ValueError("Zarr timestamps length differs from export manifest: " + task)
return manifest
def collect_qc(root, manifest):
independent = []
prechecks = {}
vlm = []
for path in sorted((root / "qc").rglob("*.json")):
document = read_json(path)
if not isinstance(document, dict):
continue
relative = str(path.relative_to(root))
if document.get("schema") == "franka-ft-oxt-validation-v1":
independent.append((path.stat().st_mtime_ns, relative, document))
if document.get("tool") == "openxtactile_check_zarr" and "datasets" in document:
for dataset in document["datasets"]:
if "checks" not in dataset:
continue # Skip abbreviated *_result.json documents.
task = Path(dataset.get("path", dataset.get("name", ""))).stem
if task in TASK_COUNTS:
existing = prechecks.get(task)
if existing is None or path.stat().st_mtime_ns > existing[0]:
prechecks[task] = (path.stat().st_mtime_ns, relative, dataset)
if document.get("tool") == "precheck_vlm":
# A dry-run marker is evidence only of local montage/prompt output.
vlm.append({"report": relative,
"dry_run_marker_present": "dry_run_no_api_call" in json.dumps(document),
"model_evaluation_pass_claimed_by_packager": False})
if not independent:
raise ValueError("No independent export validation report found under qc/")
_, relative, validation = max(independent, key=lambda item: item[0])
if validation.get("passed") is not True:
raise ValueError("Latest independent validation did not pass: " + relative)
summary = validation.get("summary", {})
expected = {"episodes": 125, "native_control_rows": 42320, "native_ft_samples": 295674,
"standard_frames": manifest["control_steps_zarr"]}
if any(summary.get(key) != value for key, value in expected.items()):
raise ValueError("Independent validation totals do not match this complete export")
if set(prechecks) != set(TASK_COUNTS):
raise ValueError("OXT metadata prechecks for all four tasks are required before packaging")
precheck_summary = {}
for task, (_, report, dataset) in prechecks.items():
metadata = dataset.get("metadata", {})
task_frames = sum(e["exported_steps"] for e in manifest["episodes"] if e["task"] == task)
if (dataset.get("passed") is not True or dataset.get("num_errors", 0) != 0
or metadata.get("num_episodes") != TASK_COUNTS[task]
or metadata.get("num_frames") != task_frames):
raise ValueError("OXT metadata precheck does not match a passing complete task: " + task)
precheck_summary[task] = {"report": report, "passed": True,
"warnings": dataset.get("num_warnings", 0),
"episodes": metadata["num_episodes"], "frames": task_frames}
episodes = [e for task in validation.get("tasks", {}).values() for e in task.get("episodes", [])]
selected_holds = None
if len(episodes) == 125 and all("command_dispatched" in e and "control_rows_exported" in e for e in episodes):
selected_holds = sum(e["control_rows_exported"] - e["command_dispatched"] for e in episodes)
return {"independent": {"report": relative, "passed": True, "summary": summary,
"scope": validation.get("scope", {})},
"oxt_metadata": precheck_summary, "vlm": vlm,
"selected_command_not_dispatched": selected_holds,
"physical_calibration_validated": False,
"canonical_wrist_alignment_validated": False,
"four_dimensional_visual_review": "not run by this packaging workflow"}
def copy_tools(root, source_dir, cache):
records = {}
for name in TOOL_FILES:
source = source_dir / name
if not source.is_file() or source.is_symlink():
raise ValueError("Required source tool is missing or symlinked: " + str(source))
destination = root / "tools" / name
destination.parent.mkdir(parents=True, exist_ok=True)
expected = cache.digest(source)
if not destination.exists() or cache.digest(destination) != expected:
fd, temporary_name = tempfile.mkstemp(prefix="." + name + ".", suffix=".partial", dir=destination.parent)
os.close(fd)
temporary = Path(temporary_name)
try:
shutil.copy2(source, temporary)
if cache.digest(temporary) != expected:
raise RuntimeError("Tool copy hash mismatch: " + name)
temporary.replace(destination)
finally:
temporary.unlink(missing_ok=True)
records[str(destination.relative_to(root))] = {"sha256": expected, "bytes": destination.stat().st_size}
return records
def runtime_requirements(root):
versions = {}
for package in RUNTIME_PACKAGES:
try:
versions[package] = importlib.metadata.version(package)
except importlib.metadata.PackageNotFoundError:
if package != "opencv-python":
raise RuntimeError("Run with the export environment; missing distribution " + package)
versions["opencv-python-headless"] = importlib.metadata.version("opencv-python-headless")
runtime = {"python": platform.python_version(), "platform": platform.platform(),
"direct_runtime_packages": versions,
"zed_sdk": "Separate SDK/pyzed installation required only for original SVO decoding; see per-episode decoder metadata for the recorded SDK version."}
lines = ["# Direct runtime versions captured from the packaging/export Python environment.",
"# Python " + runtime["python"] + "; Zarr stores use format 2.",
"# ZED SDK/pyzed is installed separately; reading existing Zarr/H5 does not require it."]
lines += [name + "==" + version for name, version in sorted(versions.items())]
atomic_text(root / "requirements_oxt_export.txt", "\n".join(lines) + "\n")
return runtime
def verify_native(root, manifest, cache):
records = {}
for episode in manifest["episodes"]:
directory = safe_path(root, episode["native_path"])
if Path(episode["native_path"]).parts[:1] != ("native",):
raise ValueError("Expected native/ episode directory")
for relative, expected in episode["files"].items():
path = safe_path(directory, relative)
name = path.relative_to(root).as_posix()
if name in records or not path.is_file() or path.is_symlink():
raise ValueError("Missing/duplicate/nonregular native file: " + name)
digest = cache.digest(path)
if path.stat().st_size != expected["bytes"] or digest != expected["sha256"]:
raise RuntimeError("Native copy differs from export manifest: " + name)
records[name] = {"bytes": expected["bytes"], "sha256": digest}
actual = {p.relative_to(root).as_posix() for p in regular_files(root / "native")}
if actual != set(records):
raise ValueError("Native file set differs from export manifest")
document = {"schema": "oxt-native-copy-sha256-v1", "complete": True,
"file_count": len(records), "total_bytes": sum(r["bytes"] for r in records.values()),
"verified_against": "metadata/export_manifest.json", "files": records}
atomic_json(root / "checksums/native_sha256.json", document)
return document
def write_array_schema(root, manifest, mapping):
"""Describe final on-disk arrays; never infer dataset-wide shapes from a pilot."""
descriptions = {
"timestamps": "Seconds since the original episode's first host control step; subtraction precedes float conversion.",
"timestamp_unix_ns": "Exact selected host control step_start_unix_ns, int64.",
"source_control_row": "Original trajectory row for each retained standard row.",
"right_arm_joints": "Measured seven-joint state in radians, original robot order.",
"right_hand_joints": "Normalized gripper opening = 1 - native closure; 0=closed and 1=open. Dimensionless, not physical width in metres.",
"right_hand_joints_idx": "Constant 28 identifying the single gripper distance/opening channel.",
"sub_task_instruction": "Concrete curated task instruction for the episode.",
"action_joint_position": "Actual recorded seven-joint targets, radians; not derived from future state.",
"action_eef_pose": "Recorded requested pre-IK native EEF target, xyz metres + rotation-vector radians.",
"action_eef_pose_with_ft_offset": "Recorded action EEF point shifted along local +Z by 63mm; not a full TCP transform.",
"state_eef_pose_with_ft_offset": "Recorded state EEF point shifted along local +Z by 63mm; not a full TCP transform.",
"command_dispatched": "Whether env.step was called; false means hypothetical hold, true does not prove acceptance.",
"ft_wrench": "Unmodified native sensor-frame Fx,Fy,Fz,Mx,My,Mz; assumed N,N,N,Nm,Nm,Nm.",
"supplementary_tactile": "The same full six-axis wrench as ft_wrench; see supplementary_tactile_note.json.",
"right_tactile_data_wrist_torque": "Only native sensor-frame Mx,My,Mz, shape (T,1,3); no inferred transform or compensation.",
"right_tactile_area_wrist_torque": "Constant single gripper functional area identifier 0.",
"right_tactile_sensor_wrist_torque": "Constant sensor identifier SRIM3813A1.",
"right_tactile_type_wrist_torque": "Constant tactile representation type state.",
}
document = {"schema": "franka-ft-oxt-final-array-schema-v1",
"scope": "Actual final task-wide data arrays read from each Zarr v2 .zarray file; shapes include all episodes in that task.",
"source": "zarr/<task>.zarr/data/<key>/.zarray",
"native_field_naming": "native__ + original HDF5 path with each '/' replaced by '__'; values retain selected source rows and native numeric dtypes.",
"episode_boundaries": "zarr/<task>.zarr/meta/episode_ends",
"per_episode_mapping": "metadata/episodes/<task>/<episode>.json, mapping member",
"omitted_standard_fields": {"right_wrist_pose": "Native EEF/flange is not aligned to the FTP-1 gripper frame; right_arm_joints is provided and native Cartesian observations are preserved."},
"tasks": {}}
for task in TASK_COUNTS:
data = root / "zarr" / (task + ".zarr") / "data"
row_count = sum(e["exported_steps"] for e in manifest["episodes"] if e["task"] == task)
arrays = {}
for directory in sorted(data.iterdir()):
if not directory.is_dir():
continue
if directory.name == "right_wrist_pose":
raise ValueError("Remove unaligned right_wrist_pose before packaging: " + str(directory))
path = directory / ".zarray"
if not path.is_file():
raise ValueError("Expected flat data array with .zarray metadata: " + str(directory))
storage = read_json(path)
if storage.get("zarr_format") != 2 or not storage.get("shape") or storage["shape"][0] != row_count:
raise ValueError("Array schema is not a finalized task-length Zarr v2 array: " + str(path))
name = directory.name
if (isinstance(storage.get("dtype"), str)
and storage["dtype"].startswith(("<U", ">U", "|U"))
and storage.get("filters") not in (None, [])):
raise ValueError("Fixed-width Unicode must use no filters for Zarr v2 interoperability; run the completed-store compatibility repair before packaging: " + str(path))
info = {key: storage[key] for key in ("shape", "dtype", "chunks", "compressor")}
for key in ("filters", "fill_value", "order", "dimension_separator"):
if key in storage:
info[key] = storage[key]
if name.startswith("native__"):
source = mapping.get("native_fields", {}).get(name, {}).get("source_path")
if not source:
raise ValueError("Missing original HDF5 path for native array: " + name)
info["source_h5_dataset"] = source
info["description"] = "Selected rows copied from trajectory.h5/" + source + "; no value transformation."
elif name in ("camera_main_rgb", "right_wrist_camera_rgb"):
if info["shape"][1:] != [360, 640, 3] or info["dtype"] != "|u1":
raise ValueError("Unexpected RGB shape/dtype in final schema: " + name)
info["description"] = "SDK LEFT rectified RGB uint8 images at 640x360; PNG then Blosc preserves decoded resized pixels."
info["camera_serial"] = "36087771" if name == "camera_main_rgb" else "16478870"
elif name in ("camera_main_intrinsics", "right_wrist_camera_intrinsics"):
info["description"] = "3x3 intrinsic K from SDK rectified LEFT calibration at the exported 640x360 resolution; repeated per selected row, distinct from original HDF5 K."
info["camera_serial"] = "36087771" if name == "camera_main_intrinsics" else "16478870"
elif name.startswith("camera_frame_index__"):
info["description"] = "Exact original decoded SVO frame index for the selected control row."
info["camera_serial"] = name.split("__", 1)[1]
elif name.startswith("camera_timestamp_unix_ns__"):
info["description"] = "Original SDK IMAGE Unix nanoseconds; floor-to-ms exactly matches recorded HDF5 frame_received."
info["camera_serial"] = name.split("__", 1)[1]
else:
info["description"] = descriptions.get(name, "Additional exporter field; see per-episode mapping metadata.")
arrays[name] = info
if not arrays:
raise ValueError("No data arrays found for " + task)
document["tasks"][task] = {"zarr_path": "zarr/" + task + ".zarr",
"row_count": row_count, "array_count": len(arrays), "arrays": arrays}
atomic_json(root / "metadata/array_schema.json", document)
# Keep all original example values while making their limited scope explicit.
example = manifest["episodes"][0]
mapping["scope"] = {
"kind": "first_episode_example",
"description": "This file captures the first exported episode's mapping. source_h5, selected_control_rows, timestamp origin and fields[*].shape are episode-specific examples, not task-wide array shapes.",
"example_episode_id": example["episode_id"],
"example_episode_metadata": example["metadata_path"],
"exact_per_episode_mappings": "metadata/episodes/<task>/<episode>.json, mapping member",
"final_task_array_schema": "metadata/array_schema.json",
}
atomic_json(root / "metadata/field_mapping.json", mapping)
return document
def verify_zip_members(archive, sources, run_crc, direct=False):
with ExitStack() as stack:
stream = stack.enter_context(DirectIOReader(archive, block_size=64 * 1024)) if direct else archive
handle = stack.enter_context(zipfile.ZipFile(stream, "r"))
entries = handle.infolist()
names = [entry.filename for entry in entries]
if len(names) != len(set(names)) or set(names) != set(sources):
raise RuntimeError("Archive member set mismatch: " + str(archive))
for entry in entries:
if entry.file_size != sources[entry.filename]["bytes"] or entry.compress_type != zipfile.ZIP_STORED:
raise RuntimeError("Archive member size/compression mismatch: " + entry.filename)
if run_crc:
for entry in entries:
digest = hashlib.sha256()
# Reading each member to EOF checks its ZIP CRC as well as its
# SHA256 against the independently hashed source file.
with handle.open(entry) as member:
for block in iter(lambda: member.read(64 * 1024), b""):
digest.update(block)
if digest.hexdigest() != sources[entry.filename]["sha256"]:
raise RuntimeError("Archive member SHA256 mismatch: " + entry.filename)
def direct_digest(path):
digest = hashlib.sha256()
with DirectIOReader(path, block_size=64 * 1024) as stream:
for block in iter(lambda: stream.read(64 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def verify_durable_archive(path, sources):
"""Verify disk members with small buffers and independent system hashes.
Large Python read buffers have produced unstable bytes on this host.
Require both a separate buffered sha256sum process and a separate O_DIRECT
dd/sha256sum pipeline to agree with the small-buffer direct verification.
"""
with Path(path).open("rb") as stream:
os.fsync(stream.fileno())
verify_zip_members(path, sources, run_crc=True, direct=True)
verified_hash = direct_digest(path)
subprocess.run(["/usr/bin/unzip", "-tqq", str(path)], check=True)
buffered_hash = subprocess.check_output(
["/usr/bin/sha256sum", str(path)], text=True).split()[0]
with subprocess.Popen(
["/usr/bin/dd", "if=" + str(path), "iflag=direct", "bs=64K", "status=none"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
) as disk_reader:
try:
system_direct_hash = subprocess.check_output(
["/usr/bin/sha256sum"], stdin=disk_reader.stdout, text=True).split()[0]
finally:
disk_reader.stdout.close()
errors = disk_reader.stderr.read()
if disk_reader.wait() != 0:
raise RuntimeError("Independent direct archive read failed: " + errors.decode(errors="replace"))
if verified_hash != buffered_hash or verified_hash != system_direct_hash:
raise RuntimeError("Archive hashes differ: Python64KiB=" + verified_hash
+ ", system_buffered=" + buffered_hash
+ ", system_direct=" + system_direct_hash)
return verified_hash, None
def archive_task(root, task, export_hash, cache, archive_root=None):
source = root / "zarr" / (task + ".zarr")
paths = regular_files(source)
sources = {}
for index, path in enumerate(paths):
name = task + ".zarr/" + path.relative_to(source).as_posix()
sources[name] = {"bytes": path.stat().st_size, "sha256": cache.digest(path)}
if index and index % 5000 == 0:
log(task + ": hashed " + str(index) + " Zarr files")
digest = hashlib.sha256(json.dumps(sources, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
archive_base = Path(archive_root).resolve() if archive_root is not None else root / "archives"
directory = archive_base / task
directory.mkdir(parents=True, exist_ok=True)
archive = directory / (task + ".zarr.zip")
record_path = directory / (task + ".zarr.zip.manifest.json")
if archive.exists() and record_path.exists():
previous = read_json(record_path)
if (previous.get("source_files_sha256") == digest
and previous.get("export_manifest_sha256") == export_hash
and previous.get("crc_verified") is True
and previous.get("direct_disk_verified") is True
and previous.get("archive_bytes") == archive.stat().st_size
and previous.get("archive_sha256") == cache.digest(archive)
and previous.get("archive_sha256") == direct_digest(archive)):
verify_zip_members(archive, sources, run_crc=False)
log(task + ": reused byte-identical archive with verified prior CRC and current source hashes")
return previous
fd, temporary_name = tempfile.mkstemp(prefix="." + archive.name + ".", suffix=".partial", dir=directory)
os.close(fd)
temporary = Path(temporary_name)
try:
log(task + ": writing ZIP_STORED archive (" + str(len(paths)) + " files)")
with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_STORED,
allowZip64=True, strict_timestamps=False) as handle:
synced_offset = 0
for path in paths:
name = task + ".zarr/" + path.relative_to(source).as_posix()
before = cache.fingerprint(path)
handle.write(path, arcname=name)
if before != cache.fingerprint(path) or cache.digest(path) != sources[name]["sha256"]:
raise RuntimeError("Zarr input changed while archiving: " + str(path))
if handle.fp.tell() - synced_offset >= 64 * 1024 * 1024:
# Bound dirty page-cache residency on hosts that have
# previously exhibited cached-page corruption. Only this
# newly generated archive is flushed/evicted here.
handle.fp.flush()
os.fsync(handle.fp.fileno())
position = handle.fp.tell()
if hasattr(os, "posix_fadvise"):
os.posix_fadvise(handle.fp.fileno(), synced_offset,
position - synced_offset, os.POSIX_FADV_DONTNEED)
synced_offset = position
log(task + ": syncing archive and checking every member CRC/SHA256 through direct disk reads")
try:
archive_hash, recovery = verify_durable_archive(temporary, sources)
except Exception:
failed = temporary.with_suffix(".failed")
temporary.replace(failed)
log(task + ": verification failed; diagnostic archive retained at " + str(failed))
raise
record = {"schema": "oxt-task-zarr-archive-v1", "task": task,
"archive": archive.relative_to(archive_base if archive_root is not None else root).as_posix(),
"archive_bytes": temporary.stat().st_size, "archive_sha256": archive_hash,
"compression": "ZIP_STORED", "zip64_allowed": True,
"member_count": len(paths), "source_bytes": sum(r["bytes"] for r in sources.values()),
"source_files_sha256": digest, "export_manifest_sha256": export_hash,
"crc_verified": True, "member_sha256_verified": True,
"direct_disk_verified": True, "buffered_disk_sha256_equal": True,
"verification_backend": "64KiB direct member CRC/SHA256; independent system unzip, sha256sum and dd O_DIRECT",
"cache_recovery": recovery, "verified_at_utc": utc_now()}
os.chmod(temporary, 0o644)
temporary.replace(archive)
atomic_json(record_path, record)
return record
finally:
temporary.unlink(missing_ok=True)
def make_readme(manifest, qc, archived):
lines = ["---", "pretty_name: IDEAL-FT", "language:", "- en",
"tags:", "- robotics", "- force-torque", "- zarr", "---", "",
"# IDEAL-FT: four Franka teleoperation tasks", "",
"A local, schema-compatible OXT-layout export of 125 curated successful demonstrations. "
"It preserves the recorded robot and FT conventions; canonical wrist/TCP geometry and "
"post-installation camera calibration have not been verified. This is not a claim of "
"canonical training readiness or final OXT acceptance.", "",
"Prepared for a future public Hugging Face upload under `Alan0928`. This packaging "
"workflow performs no upload and creates no repository. No dataset license, institution, "
"contact, or repository URL has been inferred.", "",
"Format references: [Open-X-Tactile](https://open-x-tactile.github.io) and the "
"[pinned FTP-1 official data format](https://github.com/michaelyuancb/ftp1-policy/blob/89fa681d6c014cce28300946b7526db808e0b1c1/data_processing/README.md). "
"Submission guidance: `OXT-QC/OXT-Contribution/OXT数据提交指南.pdf` "
"and `OXT-QC/OXT-Contribution/OXT数据提交注意事项.docx` in the local OXT-QC checkout "
"(`cadbf5e7d1cfcec861a6d58779fc6d6e057f3126`). These references do not imply formal acceptance.", "",
"## Contents and counts", "",
"| Task | Episodes | Original controls | Standard rows | Full-rate FT samples |",
"|---|---:|---:|---:|---:|"]
for task in TASK_COUNTS:
episodes = [e for e in manifest["episodes"] if e["task"] == task]
lines.append("| {} | {} | {} | {} | {} |".format(task.replace("_", " "), len(episodes),
sum(e["source_control_steps"] for e in episodes), sum(e["exported_steps"] for e in episodes),
sum(e["ft_samples"] for e in episodes)))
lines += ["| **Total** | **125** | **42320** | **{}** | **295674** |".format(manifest["control_steps_zarr"]), "",
"`insert pen` is the user's confirmed name for the original `insert` demonstrations. "
"The prior user-excluded hang-tape episode at 2026-10-16 20:10:14 is not included; "
"the replacement at 21:19:44 is included. Original task labels and selection evidence "
"remain in `metadata/selected_sources_audit.json`.", "",
"- `zarr/<task>.zarr/`: Zarr format 2, `data/*` arrays and `meta/episode_ends`.",
"- `native/<task>/<episode>/`: complete original trajectory H5, full-rate FT H5, and original stereo SVO files.",
"- `metadata/episodes/`: source attributes, exact camera alignment, decoder calibration, and field mapping.",
"- `metadata/array_schema.json`: final task-wide array shapes, dtypes, chunks, compression, and field descriptions; `metadata/field_mapping.json` is explicitly a first-episode example.",
"- `qc/`: local numeric/preservation checks, OXT metadata prechecks, and any VLM dry-run artifacts.",
"- `qc/previews/`, `examples/`, and `metadata/preview_metadata.json`, when present: small human-viewing previews, separate from the original standard arrays; display resampling is documented in preview metadata.",
"- `tools/` and `requirements_oxt_export.txt`: exact export, mapping, decoding, validation and packaging code plus offline regression tests.",
"- `checksums/native_sha256.json`: all native file hashes verified against the export manifest.",
"- `SHA256SUMS`: every package file except this checksum file itself."]
lines += (["- `archives/checksums.txt`: SHA256 for each task archive.",
"- `archives/<task>/<task>.zarr.zip`: ZIP_STORED/ZIP64 archives of the already-compressed Zarr files; member sizes and CRC verified."]
if archived else ["- Task archives were skipped for this packaging run (`--skip-archives`)."])
lines += ["", "Native files are not duplicated in ZIP archives."]
if archived:
lines += ["Extract each task ZIP into a directory to obtain `<task>.zarr/`; its contents match the corresponding `zarr/` store."]
lines += ["",
"## Array and timing conventions", "",
"`right_arm_joints` contains seven measured joint angles in radians. `right_wrist_pose` "
"is omitted because the recorded native EEF/flange frame (local FR3 configuration: "
"`panda_link8`) has no verified transform to the FTP-1 gripper convention "
"(relative to the wrist camera: z forward, x down, y left). The original state remains in "
"`native__observation__robot_state__cartesian_position` as xyz metres and Euler xyz radians, "
"and in native H5. `right_hand_joints` is normalized gripper opening, computed as "
"`1 - native closure`: 0=closed and 1=open, with gripper-distance index 28. "
"It is dimensionless, not a physical width in metres. Native gripper observations and "
"action fields retain their original closure convention.", "",
"String arrays use explicit fixed-width Unicode with no variable-length UTF-8 filter "
"in Zarr v2 storage. The exporter requests an empty filter list; the included "
"`fix_oxt_zarr_unicode.py` repairs completed stores made with the older implicit "
"filter behavior. Numeric and image arrays are not changed by that repair. "
"Reader compatibility verification is separate from physical calibration.", "",
"True recorded commands are separate: `action_joint_position`, `action_eef_pose`, "
"`action_eef_pose_with_ft_offset`, and `command_dispatched`. The EEF command is the "
"requested target before IK, not FK of commanded joints and not an action inferred "
"from a future observed state. Original action velocity fields are normalized per-step "
"commands, not SI velocities. All 103 original row datasets are also retained under "
"`native__` names with `/` replaced by `__`.", "",
"The additional +63 mm pose fields shift the original EEF point along its local +Z "
"with unchanged orientation. This is an installation length increment, not a complete "
"TCP definition, sensor transform, or verified OXT canonical wrist transform.", "",
"`timestamps` is seconds since the original episode's first host control step; "
"`timestamp_unix_ns` preserves exact host Unix nanoseconds. `source_control_row` maps "
"each standard row back into the full original trajectory. Camera alignment requires "
"SDK IMAGE nanoseconds floored to milliseconds to equal each recorded H5 camera "
"timestamp in both cameras. Only the intersection is retained; no nearest-time guess, "
"repeated final frame or fabricated observation is used. All original control rows "
"remain in native H5, including those omitted from standard arrays.", "",
"FT snapshots use the original latest persisted sample before robot observation; "
"their indices and host receive/snapshot times are retained. Full FT streams remain "
"in each `ft_sensor.h5`. Robot-server seconds/nanoseconds are also preserved, but its "
"clock was about 59.4–62.3 seconds behind the collection host and no offset correction "
"is applied. Local FT/control comparisons use the common host monotonic clock; "
"hardware synchronization is not claimed.", "",
"There are 3509 original rows with `command_dispatched=false`; those rows store "
"hypothetical hold commands. Selected rows retain this flag. A true flag records "
"dispatch, not confirmed asynchronous robot acceptance."]
if qc["selected_command_not_dispatched"] is not None:
lines += ["The independent validator counted **{}** such rows in the standard arrays.".format(qc["selected_command_not_dispatched"])]
lines += ["", "## Force/torque and images", "",
"The sensor is SRI M3813A1 with M8228S1 interface. `ft_wrench` and "
"`supplementary_tactile` contain `[Fx,Fy,Fz,Mx,My,Mz]` in the native sensor frame. "
"N/Nm units are assumed from the device's stored calibration. The standard tactile "
"four-piece set `right_tactile_*_wrist_torque` contains only `[Mx,My,Mz]`, shape "
"`(T,1,3)`, area 0, sensor `SRIM3813A1`, type `state`. "
"`supplementary_tactile_note.json` describes the full six-axis mapping.", "",
"No software bias subtraction, gravity compensation, or sensor-to-TCP/base transform "
"is applied. Sensor mounting axes/origin, mass/COM and full transforms were not supplied. "
"The device's calibration matrix and query responses remain in native metadata. "
"Acquisition used host AT+GOD polling, approximately 70–99 Hz across these episodes; "
"the device's reported internal 1000 Hz setting is not the saved receive rate. "
"Packet-counter discontinuities are diagnostics, not a count of lost internal samples.", "",
"`camera_main_rgb` (external 36087771) and `right_wrist_camera_rgb` (16478870) are "
"640×360 RGB uint8, decoded using SDK LEFT rectified view. PNG staging and Blosc "
"Zstd storage preserve the decoded, resized pixels losslessly; resizing itself is "
"not reversible. Original full-resolution stereo recordings remain in SVO. "
"Output intrinsics come from the decoder SDK calibration at the output resolution. "
"Original H5 intrinsics and historical hand-eye/external extrinsics are preserved "
"separately. The two active cameras' recorded calibrations date to December 2025; validity "
"after FT installation is unconfirmed, and +63 mm was not silently applied to them.", "",
"## Validation status", "",
"Independent preservation/numeric validation passed: `{}`. Scope: {}.".format(
qc["independent"]["report"], qc["independent"]["scope"].get("rgb", "see report")), "",
"| OXT metadata task | Episodes | Rows | Hard errors | Warnings |",
"|---|---:|---:|---:|---:|"]
for task, result in sorted(qc["oxt_metadata"].items()):
lines.append("| {} | {} | {} | 0 | {} |".format(task, result["episodes"], result["frames"], result["warnings"]))
lines += ["", "Metadata checks establish layout consistency, not physical calibration or final OXT acceptance.",
"The dataset-level compact metadata report still has `overall_status=warning`: "
"it requests confirmation of the inferred sensor category and completion of "
"human-authored publication/contact/reference fields. Those prompts are separate "
"from the four passing task-level data checks above."]
if qc["vlm"]:
lines.append("VLM artifacts are local dry-run/montage evidence only; this package does not claim a VLM pass or a completed external model review.")
for report in qc["vlm"]:
lines.append("- `{}`: dry-run marker {}.".format(report["report"], "present" if report["dry_run_marker_present"] else "not established; inspect report"))
else:
lines.append("No VLM evaluation report was found; no VLM pass is claimed.")
lines += ["", "No 4D visual review was run by this packaging workflow. Integrity checks "
"cover stored bytes, not calibration accuracy.", "",
"## Read one episode and its full-rate FT stream", "", "```python",
"from pathlib import Path", "import h5py", "import zarr", "",
"root = Path('franka_ft_oxt')",
"task = zarr.open_group(str(root / 'zarr/wipe_board.zarr'), mode='r')",
"data, meta = task['data'], task['meta']",
"end = int(meta['episode_ends'][0]) # first episode spans [0, end)",
"joints = data['right_arm_joints'][:end]",
"commands = data['action_joint_position'][:end]",
"rgb = data['right_wrist_camera_rgb'][0]",
"relative_native = str(meta['source_episode_paths'][0])",
"with h5py.File(root / relative_native / 'ft_sensor.h5', 'r') as ft:",
" all_wrench = ft['samples/wrench'][:] # all high-rate samples, (F, 6)",
" receive_ns = ft['samples/receive_monotonic_ns'][:]",
" indices = data['native__observation__ft_sensor__sample_index'][:end]",
" recorded_snapshots = all_wrench[indices]",
"```", "",
"Install the pinned direct dependencies with `python -m pip install -r requirements_oxt_export.txt`. "
"Reading Zarr/H5 requires no live hardware or ZED SDK. Re-decoding original SVO files "
"requires a compatible ZED SDK/pyzed environment; SDK versions are recorded per episode.", "",
"Generating example MP4 previews also requires a system `ffmpeg` executable with "
"the `libx264` encoder on PATH; it is not installed by the Python requirements. "
"Running the official OXT prechecks requires a separate OXT-QC checkout at the "
"repository and commit recorded in `metadata/format_reference.json`.", "",
"Verify all delivered files from the package directory with `sha256sum -c SHA256SUMS`. "
"Re-run offline mapping/decoder regressions with "
"`python -m unittest discover -s tools -p 'test_*.py'`.", "",
"The Unicode compatibility repair includes its own synthetic tests: "
"`python tools/fix_oxt_zarr_unicode.py --self-test --zarr2-python /path/to/zarr2/python`. "
"Use a separate Zarr 2 reader environment for that cross-version check; the ordinary "
"export/packaging environment's pinned Zarr version is listed in requirements.", ""]
return "\n".join(lines)
def package(args):
root = Path(args.dataset_root).expanduser().resolve(strict=True)
source_dir = Path(args.source_dir).expanduser().resolve(strict=True)
cache = HashCache()
manifest = check_export(root)
export_hash = cache.digest(root / "metadata/export_manifest.json")
qc = collect_qc(root, manifest)
mapping = read_json(root / "metadata/field_mapping.json")
note = mapping.get("supplementary_tactile_note")
if not isinstance(note, dict) or not note:
raise ValueError("field_mapping.json lacks supplementary_tactile_note")
# Validate inputs before generating packaging outputs.
for name in TOOL_FILES:
if not (source_dir / name).is_file():
raise ValueError("Missing source tool: " + name)
remove_interrupted_packaging_stages(root)
regular_files(root)
runtime = runtime_requirements(root)
tools = copy_tools(root, source_dir, cache)
atomic_json(root / "supplementary_tactile_note.json", note)
array_schema = write_array_schema(root, manifest, mapping)
log("Verifying all original native copies against export SHA256 records")
native = verify_native(root, manifest, cache)
archives = {}
if not args.skip_archives:
for task in TASK_COUNTS:
archives[task] = archive_task(root, task, export_hash, cache)
atomic_text(root / "archives/checksums.txt", "".join(
value["archive_sha256"] + " " + str(Path(value["archive"]).relative_to("archives")) + "\n"
for value in archives.values()))
atomic_text(root / "README.md", make_readme(manifest, qc, bool(archives)))
record = {"schema": "franka-ft-oxt-package-v1", "complete": True,
"packaged_at_utc": utc_now(), "upload_performed": False,
"export_manifest_sha256": export_hash, "runtime": runtime,
"counts": {key: manifest[key] for key in ("tasks", "total_episodes", "control_steps_native", "control_steps_zarr", "ft_samples_native")},
"native_integrity": {"file_count": native["file_count"], "total_bytes": native["total_bytes"],
"report": "checksums/native_sha256.json"},
"tools": tools, "archives": archives, "archive_creation_skipped": bool(args.skip_archives),
"array_schema": {"path": "metadata/array_schema.json",
"task_array_counts": {task: value["array_count"] for task, value in array_schema["tasks"].items()}},
"qc": qc, "integrity_manifest": "SHA256SUMS"}
atomic_json(root / "metadata/package_manifest.json", record)
log("Hashing the complete package, including all Zarr chunks, native files, archives and reports")
files = [p for p in regular_files(root) if p != root / "SHA256SUMS"]
lines = []
last_progress = time.monotonic()
for index, path in enumerate(files, 1):
relative = path.relative_to(root).as_posix()
safe_path(root, relative)
lines.append(cache.digest(path) + " " + relative + "\n")
if time.monotonic() - last_progress >= 20:
log("Package checksums: {}/{} files".format(index, len(files)))
last_progress = time.monotonic()
if cache.digest(root / "metadata/export_manifest.json") != export_hash:
raise RuntimeError("Export manifest changed during packaging")
current = [p for p in regular_files(root) if p != root / "SHA256SUMS"]
if current != files or any(cache.entries[p][0] != cache.fingerprint(p) for p in files):
raise RuntimeError("Package changed during final hashing; rerun after writers finish")
atomic_text(root / "SHA256SUMS", "".join(lines))
return {"complete": True, "dataset_root": str(root), "episodes": manifest["total_episodes"],
"standard_rows": manifest["control_steps_zarr"], "hashed_files": len(files),
"archive_count": len(archives), "native_files": native["file_count"], "upload_performed": False}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset-root", required=True, type=Path)
parser.add_argument("--source-dir", type=Path, default=Path.cwd(), help="Exact exporter/mapping/decoder/validator/test sources (default: current directory)")
parser.add_argument("--skip-archives", action="store_true", help="Generate documentation and integrity manifests without creating/rebuilding archives")
args = parser.parse_args(argv)
try:
print(json.dumps(package(args), ensure_ascii=False), flush=True)
return 0
except Exception as error:
log(type(error).__name__ + ": " + str(error))
return 1
if __name__ == "__main__":
raise SystemExit(main())