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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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/env python3
"""Export a frozen, curated DROID+FT selection to local OXT-layout Zarr v2.

No network or robot access. Native inputs are copied, never modified. Requires
oxt_array_mapping.py and an offline ZED SDK interpreter for SVO decoding.
Each episode is committed only after both cameras and every array are written;
an interrupted episode is safely overwritten on resume.
"""
from __future__ import annotations

import argparse
import asyncio
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import hashlib
import fcntl
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time

import cv2
import h5py
import numpy as np
from numcodecs import Blosc
import zarr
from zarr.storage import LocalStore

from oxt_array_mapping import align_camera_rows, build_arrays

VERSION = "1.0.2"
TASKS = {
    "wipe_board": "Wipe the board.",
    "push_button": "Push the button.",
    "insert_pen": "Insert the pen.",
    "hang_tape": "Hang the tape.",
}
CAMERAS = {"36087771": "camera_main", "16478870": "right_wrist_camera"}


class AtomicLocalStore(LocalStore):
    """Atomic per-key replacement protects committed shared chunks on resume.

    Requires one exporter writer per output directory. This protects against a
    terminated process, not loss of the entire filesystem or machine power.
    """

    async def _set(self, key, value, exclusive=False):
        if not self._is_open:
            await self._open()
        self._check_writable()
        path = self.root / key

        def put():
            path.parent.mkdir(parents=True, exist_ok=True)
            descriptor, name = tempfile.mkstemp(prefix=".oxt-write-", dir=path.parent)
            temporary = Path(name)
            try:
                with os.fdopen(descriptor, "wb") as stream:
                    stream.write(value.to_bytes())
                if exclusive:
                    os.link(temporary, path)
                    temporary.unlink()
                else:
                    temporary.replace(path)
            finally:
                temporary.unlink(missing_ok=True)

        await asyncio.to_thread(put)


def atomic_json(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + ".partial")
    with temporary.open("w", encoding="utf-8") as stream:
        json.dump(value, stream, indent=2, ensure_ascii=False, allow_nan=False)
        stream.write("\n")
        stream.flush()
        os.fsync(stream.fileno())
    temporary.replace(path)


def sha256(path):
    digest = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def json_value(value):
    if isinstance(value, bytes):
        return value.decode("utf-8")
    if isinstance(value, np.ndarray):
        return [json_value(v) for v in value.tolist()]
    if isinstance(value, np.generic):
        return json_value(value.item())
    if isinstance(value, (list, tuple)):
        return [json_value(v) for v in value]
    if isinstance(value, dict):
        return {str(k): json_value(v) for k, v in value.items()}
    return value


def task_slug(episode):
    slug = episode["task_slug"]
    return "insert_pen" if slug == "insert" else slug


def episode_name(episode):
    return Path(episode["source_episode"]).name.replace(":", "-")


def source_fingerprint(episode):
    source = Path(episode["source_episode"])
    for relative, expected in episode["files_before"].items():
        stat = (source / relative).stat()
        if (stat.st_size, stat.st_mtime_ns) != (expected["size"], expected["mtime_ns"]):
            raise RuntimeError(f"Audited source changed: {source / relative}")


def copy_native(episode, destination):
    """Copy all audited source files, verify bytes, and retain original H5 attrs."""
    source_fingerprint(episode)
    source = Path(episode["source_episode"])
    destination.mkdir(parents=True, exist_ok=True)
    file_records = {}
    for relative in sorted(episode["files_before"]):
        src, dst = source / relative, destination / relative
        dst.parent.mkdir(parents=True, exist_ok=True)
        source_hash = sha256(src)
        expected_hash = episode["source_h5_sha256"].get(relative)
        if expected_hash and source_hash != expected_hash:
            raise RuntimeError(f"Audited source hash changed: {src}")
        if not dst.exists() or dst.stat().st_size != src.stat().st_size or sha256(dst) != source_hash:
            partial = dst.with_name(dst.name + ".partial")
            shutil.copy2(src, partial)
            if sha256(partial) != source_hash:
                raise RuntimeError(f"Copy hash mismatch: {dst}")
            partial.replace(dst)
        file_records[relative] = {"bytes": dst.stat().st_size, "sha256": source_hash}
    source_fingerprint(episode)
    return file_records


def string_widths(episodes):
    """Preflight fixed Unicode widths across the entire task to prevent truncation."""
    widths = {}
    for episode in episodes:
        with h5py.File(Path(episode["source_episode"]) / "trajectory.h5", "r") as handle:
            def visit(name, node):
                if isinstance(node, h5py.Dataset) and node.dtype.kind in "OSU":
                    values = node.asstr()[:] if node.dtype.kind in "OS" else node[:]
                    width = max((len(str(v)) for v in values.ravel()), default=1)
                    key = "native__" + name.replace("/", "__")
                    widths[key] = max(widths.get(key, 1), width)
            handle.visititems(visit)
    return widths


def decode_camera(args, source, cache, log_path):
    if cache.exists():
        meta = json.loads((cache / "metadata.json").read_text())
        stat = source.stat()
        if (meta.get("complete") and meta.get("image_format") == "png"
                and meta["source_size"] == stat.st_size and meta["source_mtime_ns"] == stat.st_mtime_ns
                and meta["width"] == args.width and meta["height"] == args.height):
            return meta
        raise RuntimeError(f"Incompatible decode cache: {cache}")
    command = [args.zed_python, str(Path(__file__).with_name("svo_decode.py")),
               "--input", str(source), "--output", str(cache),
               "--width", str(args.width), "--height", str(args.height), "--image-format", "png"]
    log_path.parent.mkdir(parents=True, exist_ok=True)
    for attempt in range(3):
        with log_path.open("a", encoding="utf-8") as stream:
            stream.write(f"\nDecode attempt {attempt + 1}\n")
            stream.flush()
            result = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT)
        if result.returncode == 0:
            return json.loads((cache / "metadata.json").read_text())
        if cache.exists():
            raise RuntimeError(f"Failed decoder left output: {cache}; inspect {log_path}")
    raise RuntimeError(f"SVO decode failed three times: {source}; inspect {log_path}")


def create_array(group, key, sample, capacity, widths):
    dtype = sample.dtype
    if dtype.kind == "U":
        dtype = np.dtype(f"U{max(dtype.itemsize // 4, widths.get(key, 1))}")
    chunks = (min(256, capacity),) + sample.shape[1:]
    return group.create_array(key, shape=(capacity,) + sample.shape[1:], dtype=dtype,
                              chunks=chunks, filters=[], compressor=Blosc(cname="zstd", clevel=3,
                                                              shuffle=Blosc.SHUFFLE))


def write_rows(group, arrays, start, capacity, widths):
    for key, values in arrays.items():
        if values.dtype.kind == "O":
            raise TypeError(f"Object array cannot be exported losslessly: {key}")
        target = group[key] if key in group else create_array(group, key, values, capacity, widths)
        if target.shape[1:] != values.shape[1:]:
            raise ValueError(f"Shape changed for {key}")
        if values.dtype.kind == "U" and values.dtype.itemsize > target.dtype.itemsize:
            raise ValueError(f"String truncation prevented for {key}")
        target[start:start + len(values)] = values


def resized_left_intrinsics(metadata, width, height):
    """Require actual SDK rectified calibration, never substitute stale hand-eye."""
    calib = metadata.get("calibration", {})
    left = calib.get("rectified", {}).get("left", {})
    matrix = left.get("K")
    if matrix is None:
        raise ValueError("Decoder did not provide rectified output K for LEFT view")
    matrix = np.asarray(matrix, dtype=np.float64)
    if matrix.shape != (3, 3) or not np.all(np.isfinite(matrix)) or matrix[0, 0] <= 0:
        raise ValueError("Invalid SDK output intrinsics")
    return matrix


def write_images(group, role, cache, indices, start, capacity, width, height):
    key = role + "_rgb"
    if key not in group:
        group.create_array(key, shape=(capacity, height, width, 3), dtype="u1",
                           chunks=(1, height, width, 3),
                           compressor=Blosc(cname="zstd", clevel=3, shuffle=Blosc.NOSHUFFLE))
    target = group[key]
    for first in range(0, len(indices), 16):
        batch = []
        for frame_index in indices[first:first + 16]:
            path = cache / f"frame{frame_index:06d}.png"
            bgr = cv2.imread(str(path), cv2.IMREAD_COLOR)
            if bgr is None or bgr.shape != (height, width, 3) or bgr.dtype != np.uint8:
                raise RuntimeError(f"Invalid decoded frame: {path}")
            batch.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
        pixels = np.stack(batch)
        target[start + first:start + first + len(batch)] = pixels
        # Compare actual storage roundtrip at boundaries and regular intervals.
        for offset, rgb in enumerate(batch):
            number = first + offset
            if number == 0 or number == len(indices) - 1 or number % 100 == 0:
                if not np.array_equal(target[start + number], rgb):
                    raise RuntimeError(f"Zarr RGB roundtrip failed: {role} frame {indices[number]}")


def update_meta(root, records, final=False):
    meta = root.require_group("meta")
    values = {
        "episode_ends": np.asarray([r["end"] for r in records], dtype=np.int64),
        "episode_ids": np.asarray([r["episode_id"] for r in records], dtype="U36"),
        "episode_names": np.asarray([r["episode_name"] for r in records], dtype="U128"),
        "source_episode_paths": np.asarray([r["native_path"] for r in records], dtype="U256"),
    }
    for key, value in values.items():
        if key in meta:
            del meta[key]
        array = meta.create_array(key, shape=value.shape, dtype=value.dtype,
                                  chunks=(max(1, len(value)),), filters=[])
        array[:] = value
    root.attrs["complete"] = final
    root.attrs["committed_episodes"] = len(records)


def export(args):
    audit_path = Path(args.audit).resolve(strict=True)
    audit = json.loads(audit_path.read_text())
    if audit["errors"] or audit["summary"]["errors"]:
        raise ValueError("Source audit contains errors")
    if len(audit["episodes"]) != 125 or len(set(e["episode_id"] for e in audit["episodes"])) != 125:
        raise ValueError("Expected frozen 125 unique curated episodes")
    output, work = Path(args.output).resolve(), Path(args.work).resolve()
    output.mkdir(parents=True, exist_ok=True)
    work.mkdir(parents=True, exist_ok=True)
    for name in ("native", "zarr", "metadata/episodes", "qc", "tools", "archives"):
        (output / name).mkdir(parents=True, exist_ok=True)
    audit_hash = sha256(audit_path)
    journal_path = work / "export_journal.json"
    config = {"version": VERSION, "source_audit_sha256": audit_hash,
              "output": str(output), "width": args.width, "height": args.height}
    if not journal_path.exists() and any((output / "zarr").glob("*.zarr")):
        raise ValueError("Existing Zarr output requires its original resume journal")
    journal = json.loads(journal_path.read_text()) if journal_path.exists() else {"config": config, "episodes": []}
    if journal["config"] != config:
        raise ValueError("Resume configuration differs from journal")
    for temporary in (output / "zarr").rglob(".oxt-write-*"):
        if temporary.is_file():
            temporary.unlink()
    atomic_json(journal_path, journal)
    shutil.copy2(audit_path, output / "metadata/selected_sources_audit.json")
    semantics = audit_path.with_name("source_field_semantics.json")
    if semantics.exists():
        shutil.copy2(semantics, output / "metadata/source_field_semantics.json")
    processed = 0
    started = time.monotonic()
    for slug, instruction in TASKS.items():
        episodes = [e for e in audit["episodes"] if task_slug(e) == slug]
        capacity = sum(e["control_steps"] for e in episodes)
        records = [e for e in journal["episodes"] if e["task"] == slug]
        completed = {e["episode_id"] for e in records}
        path = output / "zarr" / (slug + ".zarr")
        root = zarr.open_group(store=AtomicLocalStore(path), mode="a", zarr_format=2)
        data = root.require_group("data")
        root.attrs.update({"dataset": "IDEALFT_OXT", "task": instruction, "exporter_version": VERSION,
                           "zarr_format": 2, "image_size_hw": [args.height, args.width],
                           "pose_format": "xyz_m_rotvec_rad", "pose_reference": "native panda_link8 flange",
                           "canonical_gripper_alignment": "right_wrist_pose omitted; calibrated FTP-1 gripper transform unavailable",
                           "right_hand_joints_semantics": "slot 28: normalized opening = 1 - native closure; 0=closed, 1=open; dimensionless",
                           "ft_compensation": "device calibrated; no added gravity/bias compensation",
                           "camera_extrinsic_validity": "recorded old calibration; post-installation validity unconfirmed",
                           "sampling": "Original control rows with exact recorded images from both cameras; no interpolation",
                           "complete": False})
        widths = string_widths(episodes)
        for episode in episodes:
            if episode["episode_id"] in completed:
                continue
            name = episode_name(episode)
            print(f"[{len(journal['episodes']) + 1}/125] {slug}/{name}", flush=True)
            source = Path(episode["source_episode"])
            native_relative = Path("native") / slug / name
            native_files = copy_native(episode, output / native_relative)
            cache_root = work / "decode" / slug / name
            camera_meta, timestamps = {}, {}
            with ThreadPoolExecutor(max_workers=2) as executor:
                futures = {serial: executor.submit(
                    decode_camera, args, source / "recordings/SVO" / (serial + ".svo"), cache_root / serial,
                    work / "logs" / slug / name / (serial + ".log")) for serial in CAMERAS}
                # Only offline decoder processes run concurrently. All Zarr and
                # journal mutations remain on this single parent thread.
                for serial, future in futures.items():
                    camera_meta[serial] = future.result()
            for serial in CAMERAS:
                with np.load(cache_root / serial / "timestamps.npz") as record:
                    timestamps[serial] = record["timestamp_ns"].copy()
            rows, frame_indices, alignment = align_camera_rows(output / native_relative / "trajectory.h5", timestamps)
            selected_times = {serial: timestamps[serial][frame_indices[serial]] for serial in CAMERAS}
            arrays, mapping = build_arrays(output / native_relative / "trajectory.h5", rows, instruction,
                                           camera_indices=frame_indices, camera_timestamp_ns=selected_times)
            for serial, role in CAMERAS.items():
                k = resized_left_intrinsics(camera_meta[serial], args.width, args.height)
                arrays[role + "_intrinsics"] = np.repeat(k[None], len(rows), axis=0)
            start = records[-1]["end"] if records else 0
            end = start + len(rows)
            if end > capacity:
                raise RuntimeError("More selected rows than source control rows")
            # Resume after task finalization can safely grow back to capacity.
            for key in data.array_keys():
                a = data[key]
                if a.shape[0] != capacity:
                    a.resize((capacity,) + a.shape[1:])
            write_rows(data, arrays, start, capacity, widths)
            for serial, role in CAMERAS.items():
                write_images(data, role, cache_root / serial, frame_indices[serial], start,
                             capacity, args.width, args.height)
            record = {"task": slug, "episode_id": episode["episode_id"], "episode_name": name,
                      "native_path": str(native_relative), "start": start, "end": end,
                      "source_control_steps": episode["control_steps"], "exported_steps": len(rows),
                      "ft_samples": episode["ft_samples"], "files": native_files,
                      "source_date": source.parent.name, "source_directory_name": source.name,
                      "source_control_rows_omitted": sorted(set(range(episode["control_steps"])) - set(rows.tolist())),
                      "task_selection_basis": episode["selection_basis"],
                      "metadata_path": str(Path("metadata/episodes") / slug / (name + ".json"))}
            native_attrs = {}
            for fname in ("trajectory.h5", "ft_sensor.h5"):
                with h5py.File(output / native_relative / fname, "r") as handle:
                    native_attrs[fname] = {k: json_value(v) for k, v in handle.attrs.items()}
            atomic_json(output / record["metadata_path"],
                        {"episode": record, "alignment": alignment, "mapping": mapping,
                         "cameras": camera_meta, "native_h5_attributes": native_attrs})
            if not (output / "metadata/field_mapping.json").exists():
                atomic_json(output / "metadata/field_mapping.json", mapping)
            records.append(record)
            update_meta(root, records)
            journal["episodes"].append(record)
            atomic_json(journal_path, journal)
            shutil.rmtree(cache_root)
            processed += 1
            print(f"  committed {len(rows)} rows; native {episode['control_steps']} controls, "
                  f"{episode['ft_samples']} FT samples; elapsed {time.monotonic() - started:.1f}s", flush=True)
            if args.max_new_episodes and processed >= args.max_new_episodes:
                print("Pilot limit reached; resume without --max-new-episodes for all tasks.", flush=True)
                return
        if len(records) != len(episodes):
            raise RuntimeError("Task episode accounting mismatch")
        total_rows = records[-1]["end"]
        for key in data.array_keys():
            array = data[key]
            array.resize((total_rows,) + array.shape[1:])
        update_meta(root, records, final=True)
        print(f"Completed {slug}: {len(records)} episodes, {total_rows} synchronized rows", flush=True)
    counts = Counter(r["task"] for r in journal["episodes"])
    manifest = {"schema": "franka-ft-oxt-local-v1", "complete": True, "upload_status": "not uploaded",
                "source_audit_sha256": audit_hash, "tasks": dict(counts),
                "episodes": journal["episodes"], "total_episodes": len(journal["episodes"]),
                "control_steps_native": sum(r["source_control_steps"] for r in journal["episodes"]),
                "control_steps_zarr": sum(r["exported_steps"] for r in journal["episodes"]),
                "ft_samples_native": sum(r["ft_samples"] for r in journal["episodes"]),
                "geometry_status": "Native flange and FT sensor frames preserved; canonical/TCP calibration pending",
                "created_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
    atomic_json(output / "metadata/export_manifest.json", manifest)
    print(json.dumps({k: v for k, v in manifest.items() if k != "episodes"}, indent=2), flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--audit", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--work", required=True, help="SSD staging and resume journal (outside output)")
    parser.add_argument("--zed-python", default="/home/yygx/anaconda3/envs/zed/bin/python")
    parser.add_argument("--width", type=int, default=640)
    parser.add_argument("--height", type=int, default=360)
    parser.add_argument("--max-new-episodes", type=int, default=0, help="Optional pilot limit; zero means all")
    args = parser.parse_args()
    if args.width <= 0 or args.height <= 0:
        parser.error("image dimensions must be positive")
    work = Path(args.work).resolve()
    work.mkdir(parents=True, exist_ok=True)
    with (work / "export.lock").open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as error:
            raise RuntimeError("Another exporter is using this work directory") from error
        export(args)


if __name__ == "__main__":
    main()