File size: 4,366 Bytes
cb8518a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3


from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path


SCENE_EXTENSIONS = (".blend", ".glb", ".gltf")


def find_scene(sample_dir: Path) -> Path | None:
    for extension in SCENE_EXTENSIONS:
        path = sample_dir / f"scene{extension}"
        if path.is_file():
            return path
    return None


def load_manifest(path: Path) -> list[dict]:
    rows: list[dict] = []
    seen: set[str] = set()
    for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        if not line.strip():
            continue
        row = json.loads(line)
        sample_id = row.get("id") or row.get("sample_id")
        if not sample_id:
            raise ValueError(f"missing id at {path}:{line_number}")
        sample_id = str(sample_id)
        if sample_id in seen:
            raise ValueError(f"duplicate sample id at {path}:{line_number}: {sample_id}")
        seen.add(sample_id)
        row["id"] = sample_id
        rows.append(row)
    if not rows:
        raise ValueError(f"manifest has no samples: {path}")
    return rows


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


def validate(
    data_root: Path,
    manifest_path: Path,
    models: list[str],
    *,
    check_sha256: bool,
    allow_missing_models: bool,
) -> list[str]:
    rows = load_manifest(manifest_path)
    issues: list[str] = []

    for row in rows:
        sample_id = row["id"]
        gt_dir = data_root / "gt" / sample_id
        gt_scene = find_scene(gt_dir)
        if gt_scene is None:
            issues.append(f"{sample_id}: missing GT scene.blend|scene.glb|scene.gltf")
            continue

        if check_sha256:
            metadata_path = gt_dir / "metadata.json"
            if not metadata_path.is_file():
                issues.append(f"{sample_id}: missing metadata.json for checksum validation")
            else:
                metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
                for filename, expected in metadata.get("files", {}).items():
                    asset = gt_dir / filename
                    if not asset.is_file():
                        issues.append(f"{sample_id}: missing checksummed file {filename}")
                    elif sha256(asset) != expected:
                        issues.append(f"{sample_id}: checksum mismatch for {filename}")

        for model in models:
            if find_scene(data_root / model / sample_id) is None:
                message = f"{sample_id}: missing {model} scene.blend|scene.glb|scene.gltf"
                if not allow_missing_models:
                    issues.append(message)

    return issues


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--data_root",
        required=True,
        help="Dataset root containing gt/ and optional model submission directories.",
    )
    parser.add_argument("--track_manifest", required=True)
    parser.add_argument("--models", default="", help="Comma-separated submission directories under data_root")
    parser.add_argument("--check_sha256", action="store_true")
    parser.add_argument("--allow_missing_models", action="store_true")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    data_root = Path(args.data_root).resolve()
    manifest_path = Path(args.track_manifest).resolve()
    models = [model.strip() for model in args.models.split(",") if model.strip()]

    try:
        issues = validate(
            data_root,
            manifest_path,
            models,
            check_sha256=args.check_sha256,
            allow_missing_models=args.allow_missing_models,
        )
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print(f"[FAIL] {exc}")
        return 1

    if issues:
        print(f"[FAIL] {len(issues)} issue(s)")
        for issue in issues:
            print(f"  - {issue}")
        return 1

    print(f"[OK] {manifest_path}")
    print(f"[OK] models={models or ['GT only']} sha256={args.check_sha256}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())