File size: 4,733 Bytes
3752dc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f9328b
3752dc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Materialize selected GLB files from a mounted source tree."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
from pathlib import Path
from typing import Any, Iterator

def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open('rb') as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b''):
            digest.update(chunk)
    return digest.hexdigest()

def iter_records(manifest: Path) -> Iterator[dict[str, Any]]:
    with manifest.open('r', encoding='utf-8') as handle:
        for line_no, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                record = json.loads(line)
            except json.JSONDecodeError as exc:
                raise RuntimeError(f'{manifest}:{line_no}: invalid JSON: {exc}') from exc
            yield record

def resolve_source(source_root: Path, relative_path: str) -> Path:
    relative = Path(relative_path)
    if relative.is_absolute() or '..' in relative.parts:
        raise RuntimeError(f'unsafe manifest path: {relative_path}')
    candidates = [source_root / relative]
    if relative.parts and relative.parts[0] == 'meshes':
        candidates.append(source_root / Path(*relative.parts[1:]))
    for candidate in candidates:
        if candidate.is_file():
            return candidate
    raise FileNotFoundError(f'source mesh not found for {relative_path}')

def materialize_record(record: dict[str, Any], source_root: Path, output_root: Path, verify_only: bool) -> tuple[int, int]:
    group_key = record.get('group_key')
    stages = record.get('stages')
    if not isinstance(group_key, str) or not isinstance(stages, list):
        raise RuntimeError('manifest record is missing group_key or stages')
    copied = 0
    for stage in stages:
        mesh = stage.get('mesh') if isinstance(stage, dict) else None
        if not isinstance(mesh, dict):
            raise RuntimeError(f'missing mesh metadata for {group_key}')
        relative_path = mesh.get('path')
        expected = mesh.get('sha256')
        if not isinstance(relative_path, str) or not isinstance(expected, str):
            raise RuntimeError(f'invalid mesh metadata for {group_key}')
        source = resolve_source(source_root, relative_path)
        actual = sha256_file(source)
        if actual != expected:
            raise RuntimeError(f'checksum mismatch for {relative_path}: expected {expected}, got {actual}')
        if not verify_only:
            destination = output_root / relative_path
            destination.parent.mkdir(parents=True, exist_ok=True)
            temporary = destination.with_name(destination.name + '.partial')
            with source.open('rb') as src, temporary.open('wb') as dst:
                shutil.copyfileobj(src, dst, length=1024 * 1024)
            os.replace(temporary, destination)
        copied += 1
    return 1, copied

def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--manifest', type=Path, required=True, help='Sanitized EVA01-Edit three-stage JSONL manifest')
    parser.add_argument('--source-root', type=Path, required=True, help='Mounted source mesh root or its parent dataset root')
    parser.add_argument('--output-root', type=Path, default=Path('.'), help='Output dataset root')
    parser.add_argument('--group-key', action='append', help='Materialize only this group; may be repeated')
    parser.add_argument('--max-groups', type=int, help='Stop after this many selected groups')
    parser.add_argument('--verify-only', action='store_true', help='Verify source existence and checksums without copying')
    args = parser.parse_args()
    if args.max_groups is not None and args.max_groups < 1:
        parser.error('--max-groups must be positive')
    selected = set(args.group_key or [])
    groups, meshes = 0, 0
    for record in iter_records(args.manifest):
        group_key = record.get('group_key')
        if selected and group_key not in selected:
            continue
        if args.max_groups is not None and groups >= args.max_groups:
            break
        group_count, mesh_count = materialize_record(record, args.source_root, args.output_root, args.verify_only)
        groups += group_count
        meshes += mesh_count
    if selected and groups != len(selected):
        missing = sorted(selected - {r.get('group_key') for r in iter_records(args.manifest)})
        raise RuntimeError(f'requested group(s) were not found: {missing}')
    print(json.dumps({'groups': groups, 'mesh_files': meshes, 'verify_only': args.verify_only}, indent=2))

if __name__ == '__main__':
    main()