File size: 19,588 Bytes
81d9e86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""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)<workers:
                capture=pending.pop(0)
                cap_status=state/"captures"/capture/"status.json"
                if cap_status.exists() and json.loads(cap_status.read_text()).get("phase")=="complete":
                    completed.append(capture); continue
                logdir=state/"logs"; logdir.mkdir(parents=True,exist_ok=True)
                out=(logdir/f"{capture}.stdout.log").open("ab"); err=(logdir/f"{capture}.stderr.log").open("ab")
                cmd=[sys.executable,str(Path(__file__).resolve()),"capture-worker","--root",str(root),"--runtime",str(runtime),"--capture",capture]
                proc=subprocess.Popen(cmd,stdout=out,stderr=err,env=env,start_new_session=True)
                running[capture]=(proc,out,err)
            atomic_json(status_path,{"schema":"reinterhand-full-status/v1","phase":"running",
                "workers":workers,"running":{k:v[0].pid for k,v in running.items()},
                "pending":pending,"completed":completed,"capture_scope":captures,
                "updated_at":pilot.now()})
            time.sleep(10)
            for capture,(proc,out,err) in list(running.items()):
                code=proc.poll()
                if code is None: continue
                out.close(); err.close(); del running[capture]
                if code!=0: raise RuntimeError(f"Capture worker failed: {capture}, exit={code}")
                completed.append(capture)
        atomic_json(status_path,{"schema":"reinterhand-full-status/v1","phase":"complete",
            "workers":workers,"running":{},"pending":[],"completed":completed,
            "capture_scope":captures,"completed_at":pilot.now(),"updated_at":pilot.now()})
    except Exception as exc:
        for proc,out,err in running.values():
            if proc.poll() is None: proc.terminate()
            out.close(); err.close()
        atomic_json(status_path,{"schema":"reinterhand-full-status/v1","phase":"failed",
            "error_type":type(exc).__name__,"error":str(exc),"running":{},"pending":pending,
            "completed":completed,"capture_scope":captures,"updated_at":pilot.now()})
        raise
    finally:
        lock.unlink(missing_ok=True)


def parse_args():
    p=argparse.ArgumentParser(); sp=p.add_subparsers(dest="command",required=True)
    run=sp.add_parser("run"); run.add_argument("--root",type=Path,required=True); run.add_argument("--runtime",type=Path,required=True); run.add_argument("--workers",type=int,default=2); run.add_argument("--captures-file",type=Path)
    worker=sp.add_parser("capture-worker"); worker.add_argument("--root",type=Path,required=True); worker.add_argument("--runtime",type=Path,required=True); worker.add_argument("--capture",required=True)
    return p.parse_args()


def main():
    a=parse_args(); root=a.root.resolve(); runtime=a.runtime.resolve(); state=root/"tmp/full-preprocess-v1.0"
    if a.command=="run": run_controller(root,runtime,a.workers,a.captures_file.resolve() if a.captures_file else None)
    else: capture_worker(root,runtime,state,a.capture)


if __name__=="__main__": main()