"""Restartable full ReInterHand conversion using the accepted pilot logic. Each capture archive is streamed exactly once into a capture-local scratch directory. Segments are converted independently and committed only after a manifest has been written. Raw data is opened read-only. Capture scratch is removed only after every official segment has a verified checkpoint. """ from __future__ import annotations import argparse import hashlib import json import os from pathlib import Path, PurePosixPath import shutil import subprocess import sys import tarfile import time import traceback import preprocess_reinterhand as pilot def atomic_json(path: Path, value: object) -> None: pilot.atomic_json(path, value) def file_sha256(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: for block in iter(lambda: f.read(8 * 1024 * 1024), b""): h.update(block) return h.hexdigest() def capture_names(root: Path) -> list[str]: return sorted(p.name for p in (root / "raw" / "data").iterdir() if p.is_dir() and (p / "frame_list.txt").is_file()) def segment_names(capture_root: Path) -> list[str]: result: list[str] = [] seen: set[str] = set() frame_ids: set[int] = set() for line in (capture_root / "frame_list.txt").read_text(encoding="utf-8").splitlines(): row = line.split() if len(row) < 2: continue frame = int(row[1]) if frame in frame_ids: raise RuntimeError(f"Frame ID appears in multiple rows: {capture_root.name}:{frame}") frame_ids.add(frame) if row[0] not in seen: result.append(row[0]); seen.add(row[0]) if not result: raise RuntimeError(f"No official segments: {capture_root}") return result def wanted(group: str, member_name: str, valid_frames: set[str]) -> bool: return pilot.wanted(group, member_name, valid_frames) def extract_group(group: str, parts: list[Path], destination: Path, valid_frames: set[str], status_path: Path, status: dict) -> dict: out_root = destination / group out_root.mkdir(parents=True, exist_ok=True) process = subprocess.Popen(["cat", *map(str, parts)], stdout=subprocess.PIPE) assert process.stdout is not None scanned = selected = selected_bytes = 0 try: with tarfile.open(fileobj=process.stdout, mode="r|gz") as archive: for member in archive: if not member.isfile(): continue scanned += 1 if not wanted(group, member.name, valid_frames): continue rel = PurePosixPath(member.name) if rel.is_absolute() or ".." in rel.parts: raise RuntimeError(f"Unsafe member: {member.name}") output = out_root.joinpath(*rel.parts) if not output.resolve().is_relative_to(out_root.resolve()): raise RuntimeError(f"Member escapes scratch: {member.name}") output.parent.mkdir(parents=True, exist_ok=True) source = archive.extractfile(member) if source is None: raise RuntimeError(f"Cannot read {member.name}") temporary = output.with_name(output.name + ".partial") with source, temporary.open("wb") as target: shutil.copyfileobj(source, target, length=8 * 1024 * 1024) if temporary.stat().st_size != member.size: raise RuntimeError(f"Extracted size mismatch: {member.name}") os.replace(temporary, output) selected += 1; selected_bytes += member.size if selected % 250 == 0: status.update(phase="extracting", active_group=group, members_scanned=scanned, selected_files=selected, selected_bytes=selected_bytes, updated_at=pilot.now()) atomic_json(status_path, status) finally: process.stdout.close() code = process.wait() if code != 0: raise RuntimeError(f"cat failed for {group}: {code}") return {"group": group, "members_scanned": scanned, "selected_files": selected, "selected_bytes": selected_bytes} def extract_capture(root: Path, capture: str, state: Path) -> Path: capture_root = root / "raw" / "data" / capture destination = state / "scratch" / capture marker = destination / "extraction-complete.json" if marker.exists(): data = json.loads(marker.read_text(encoding="utf-8")) if data.get("capture") == capture and data.get("complete") is True: return destination raise RuntimeError(f"Invalid extraction marker: {marker}") destination.mkdir(parents=True, exist_ok=True) status_path = state / "captures" / capture / "status.json" status = {"schema":"reinterhand-full-capture-status/v1", "capture":capture, "phase":"extracting", "started_at":pilot.now(), "updated_at":pilot.now()} atomic_json(status_path, status) all_ids = {str(value) for segment in segment_names(capture_root) for value in pilot.frame_ids(capture_root, segment)} sources = { "Ego_cameras/envmap_per_frame": ("Ego_cameras", pilot.canonical_parts(capture_root / "Ego_cameras", "envmap_per_frame.tar.gz")), "Ego_cameras/envmap_per_segment": ("Ego_cameras", pilot.canonical_parts(capture_root / "Ego_cameras", "envmap_per_segment.tar.gz")), "Mugsy_cameras/envmap_per_frame": ("Mugsy_cameras", pilot.canonical_parts(capture_root / "Mugsy_cameras", "envmap_per_frame.tar.gz")), "Mugsy_cameras/envmap_per_segment": ("Mugsy_cameras", pilot.canonical_parts(capture_root / "Mugsy_cameras", "envmap_per_segment.tar.gz")), "mano_fits": ("mano_fits", pilot.canonical_parts(capture_root / "mano_fits", "mano_fits.tar.gz")), } results=[] for label,(group,parts) in sources.items(): status.update(active_archive=label, updated_at=pilot.now()); atomic_json(status_path,status) results.append(extract_group(group, parts, destination, all_ids, status_path, status)) target = destination / "Mugsy_cameras" / "cam_params.json" target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(capture_root / "Mugsy_cameras" / "cam_params.json", target) atomic_json(marker, {"schema":"reinterhand-full-extraction/v1", "capture":capture, "complete":True, "valid_frame_count":len(all_ids), "archives":results, "completed_at":pilot.now()}) return destination def tree_manifest(base: Path) -> list[dict]: rows=[] for p in sorted(x for x in base.rglob("*") if x.is_file()): rows.append({"path":p.relative_to(base).as_posix(), "bytes":p.stat().st_size, "sha256":file_sha256(p)}) return rows def decoded_video_sha256(path: Path) -> str: """Hash FFmpeg's per-frame checksums, excluding non-semantic MKV UIDs.""" process = subprocess.Popen( ["ffmpeg", "-v", "error", "-threads", "1", "-i", str(path), "-f", "framemd5", "-"], stdout=subprocess.PIPE ) assert process.stdout is not None h = hashlib.sha256() for block in iter(lambda: process.stdout.read(1024 * 1024), b""): h.update(block) if process.wait() != 0: raise RuntimeError(f"Cannot decode existing video for comparison: {path}") return h.hexdigest() def existing_matches(source: Path, target: Path, manifest: list[dict]) -> bool: if not target.is_dir(): return False current=[] for row in manifest: p=target/row["path"] if not p.is_file() or p.stat().st_size != row["bytes"]: return False if file_sha256(p) != row["sha256"]: candidate = source / row["path"] if p.suffix.lower() != ".mkv" or decoded_video_sha256(p) != decoded_video_sha256(candidate): return False current.append(row["path"]) return sorted(p.relative_to(target).as_posix() for p in target.rglob("*") if p.is_file()) == current def regroup_camera_families(work: Path, report: dict, capture: str, segment: str) -> list[str]: """Keep render setting in level one and all cameras/views in level two.""" data = work / "shared-v1.0" / "data" expected = {"envmap_per_frame": 21, "envmap_per_segment": 6} ids=pilot.frame_ids(work/"raw/data"/capture,segment) span_start,span_end=ids[0],ids[-1] desired_ids=[] for variant, camera_count in expected.items(): desired_id=f"{capture}__{variant}__{span_start}__{span_end}" desired=data/desired_id legacy=[data/f"{capture}__{segment}__{family}__{variant}" for family in ("ego","mugsy")] if desired.exists() and any(path.exists() for path in legacy): raise RuntimeError(f"Mixed direct and legacy layouts: {desired_id}") if not desired.exists(): desired.mkdir(parents=True,exist_ok=False) for old in legacy: if not old.is_dir(): raise RuntimeError(f"Missing temporary family directory: {old}") old_id=old.name for camera in sorted(p for p in old.iterdir() if p.is_dir()): target=desired/camera.name if target.exists(): raise RuntimeError(f"Camera collision while regrouping: {target}") metainfo=json.loads((camera/"metainfo.json").read_text(encoding="utf-8")) if metainfo.get("sequence_id") != old_id: raise RuntimeError(f"Unexpected sequence_id: {camera}") metainfo["sequence_id"]=desired_id # The accepted pilot converter is reused for the numerical # conversion, but committed production views must not # advertise themselves as pilot output. for key in ("pilot", "pilot_complete", "pilot_human_review"): metainfo.pop(key, None) metainfo["conversion_scope"]="full" metainfo["full_conversion_complete"]=True metainfo["full_output_human_review"]="pending" atomic_json(camera/"metainfo.json",metainfo) os.replace(camera,target) old.rmdir() cameras=sorted(p.name for p in desired.iterdir() if p.is_dir()) if len(cameras)!=camera_count or "ego" not in cameras: raise RuntimeError(f"Unexpected regrouped camera coverage: {desired_id}: {cameras}") desired_ids.append(desired_id) for row in report["views"]: if row["background_variant"]==variant: row["sequence_id"]=desired_id return desired_ids def convert_segment(root: Path, runtime: Path, state: Path, capture: str, segment: str, extracted: Path) -> dict: checkpoint = state / "checkpoints" / capture / f"{segment}.json" if checkpoint.exists(): value=json.loads(checkpoint.read_text(encoding="utf-8")) if value.get("phase")=="complete": return value raise RuntimeError(f"Non-complete checkpoint requires investigation: {checkpoint}") work = state / "work" / capture / segment if work.exists(): shutil.rmtree(work) (work / "tmp" / "pilot-v1.0" / "extracted").mkdir(parents=True) (work / "shared-v1.0" / "script").mkdir(parents=True) os.symlink(root / "raw", work / "raw", target_is_directory=True) os.symlink(extracted, work / "tmp" / "pilot-v1.0" / "extracted" / f"{capture}__{segment}", target_is_directory=True) atomic_json(work/"tmp/pilot-v1.0/status.json", {"schema":"reinterhand-full-segment-status/v1", "capture":capture,"segment":segment,"phase":"converting","started_at":pilot.now()}) pilot.convert_complete_pilot_v2(work, runtime, capture, segment) report=json.loads((work/"shared-v1.0/doc/validation/report.json").read_text(encoding="utf-8")) if len(report.get("views",[])) != 27: raise RuntimeError(f"Expected 27 streams, got {len(report.get('views',[]))}") sequence_ids=regroup_camera_families(work,report,capture,segment) committed=[]; all_manifest=[] for sequence_id in sequence_ids: source=work/"shared-v1.0/data"/sequence_id manifest=tree_manifest(source) target=root/"shared-v1.0/data"/sequence_id if target.exists(): if not existing_matches(source,target,manifest): raise RuntimeError(f"Existing output differs: {target}") shutil.rmtree(source) else: target.parent.mkdir(parents=True,exist_ok=True) os.replace(source,target) committed.append(sequence_id) # The checkpoint always describes the actual committed tree. This is # relevant when a previously accepted MKV is semantically identical # but has a different Matroska segment UID. all_manifest.extend({"sequence_id":sequence_id,**row} for row in tree_manifest(target)) value={"schema":"reinterhand-full-segment-checkpoint/v1","phase":"complete", "capture":capture,"segment":segment,"sequence_ids":committed, "views":27,"files":len(all_manifest),"bytes":sum(x["bytes"] for x in all_manifest), "manifest_sha256":hashlib.sha256(json.dumps(all_manifest,sort_keys=True,separators=(",",":")).encode()).hexdigest(), "source_mesh_parameter_checks":report["source_mesh_parameter_checks"], "completed_at":pilot.now()} atomic_json(checkpoint,value) shutil.rmtree(work) return value def capture_worker(root: Path, runtime: Path, state: Path, capture: str) -> None: status_path=state/"captures"/capture/"status.json" try: extracted=extract_capture(root,capture,state) segments=segment_names(root/"raw/data"/capture) completed=[] for index,segment in enumerate(segments): atomic_json(status_path,{"schema":"reinterhand-full-capture-status/v1","capture":capture, "phase":"converting","active_segment":segment,"segments_total":len(segments), "segments_completed":completed,"updated_at":pilot.now()}) result=convert_segment(root,runtime,state,capture,segment,extracted) completed.append(segment) atomic_json(status_path,{"schema":"reinterhand-full-capture-status/v1","capture":capture, "phase":"complete","segments_total":len(segments),"segments_completed":completed, "completed_at":pilot.now(),"updated_at":pilot.now()}) shutil.rmtree(extracted) except Exception as exc: atomic_json(status_path,{"schema":"reinterhand-full-capture-status/v1","capture":capture, "phase":"failed","error_type":type(exc).__name__,"error":str(exc), "traceback":traceback.format_exc(),"updated_at":pilot.now()}) raise def selected_capture_names(root: Path, captures_file: Path | None) -> list[str]: available = capture_names(root) if captures_file is None: return available requested = [line.strip() for line in captures_file.read_text(encoding="utf-8").splitlines() if line.strip() and not line.lstrip().startswith("#")] if not requested or len(requested) != len(set(requested)): raise RuntimeError(f"Empty or duplicate capture allowlist: {captures_file}") unknown = sorted(set(requested) - set(available)) if unknown: raise RuntimeError(f"Capture allowlist contains unavailable captures: {unknown}") return requested def run_controller(root: Path, runtime: Path, workers: int, captures_file: Path | None = None) -> None: if workers < 1 or workers > 2: raise RuntimeError("Approved worker range is 1..2") state=root/"tmp/full-preprocess-v1.0"; state.mkdir(parents=True,exist_ok=True) lock=state/"controller.lock" fd=os.open(lock,os.O_CREAT|os.O_EXCL|os.O_WRONLY) os.write(fd,str(os.getpid()).encode()); os.close(fd) status_path=state/"status.json"; captures=selected_capture_names(root, captures_file) env=os.environ.copy() for key in ["OMP_NUM_THREADS","MKL_NUM_THREADS","OPENBLAS_NUM_THREADS","NUMEXPR_NUM_THREADS"]: env[key]="1" env["REINTERHAND_FFMPEG_THREADS"]="2" pending=list(captures); running={}; completed=[] try: while pending or running: while pending and len(running)