File size: 7,125 Bytes
b03465f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the prepared MatrixCity Hugging Face dataset directory."""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import sys
from collections import Counter
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]


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


def fail(errors: list[str], message: str) -> None:
    errors.append(message)


def validate_metadata(errors: list[str]) -> Counter:
    metadata_path = ROOT / "data" / "metadata.jsonl"
    if not metadata_path.is_file():
        fail(errors, "Missing data/metadata.jsonl")
        return Counter()

    counts: Counter = Counter()
    sample_ids: set[str] = set()
    video_paths: set[str] = set()
    with metadata_path.open("r", encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            try:
                row = json.loads(line)
            except json.JSONDecodeError as error:
                fail(errors, f"metadata line {line_number}: {error}")
                continue

            sample_id = row.get("sample_id")
            if not sample_id or sample_id in sample_ids:
                fail(errors, f"metadata line {line_number}: missing/duplicate sample_id {sample_id!r}")
            sample_ids.add(sample_id)

            file_name = row.get("file_name")
            if not file_name or file_name in video_paths:
                fail(errors, f"metadata line {line_number}: missing/duplicate file_name {file_name!r}")
                continue
            video_paths.add(file_name)
            video_path = ROOT / "data" / Path(file_name)
            if not video_path.is_file():
                fail(errors, f"metadata line {line_number}: missing video {file_name}")

            annotations = row.get("annotations") or []
            has_annotations = bool(row.get("has_annotations"))
            if len(annotations) != row.get("annotation_frame_count"):
                fail(errors, f"{sample_id}: annotation_frame_count mismatch")
            if has_annotations and len(annotations) != row.get("frame_count"):
                fail(errors, f"{sample_id}: video/annotation frame count mismatch")
            if not has_annotations and annotations:
                fail(errors, f"{sample_id}: unannotated record contains frame annotations")

            expected_ids = list(range(1, len(annotations) + 1))
            actual_ids = [annotation.get("frame_id") for annotation in annotations]
            if actual_ids != expected_ids:
                fail(errors, f"{sample_id}: frame IDs are not contiguous and one-based")

            width = row.get("width")
            height = row.get("height")
            bbox_count = 0
            usable_count = 0
            for annotation in annotations:
                bbox = annotation.get("bbox_xywh")
                has_bbox = bool(annotation.get("has_bbox"))
                if has_bbox != (bbox is not None):
                    fail(errors, f"{sample_id} frame {annotation.get('frame_id')}: has_bbox mismatch")
                    continue
                if bbox is None:
                    continue
                bbox_count += 1
                if not annotation.get("source_marked_invalid"):
                    usable_count += 1
                if not isinstance(bbox, list) or len(bbox) != 4:
                    fail(errors, f"{sample_id} frame {annotation.get('frame_id')}: malformed bbox")
                    continue
                x, y, box_width, box_height = bbox
                if min(x, y, box_width, box_height) < 0 or box_width <= 0 or box_height <= 0:
                    fail(errors, f"{sample_id} frame {annotation.get('frame_id')}: invalid bbox values")
                if x + box_width > width or y + box_height > height:
                    fail(errors, f"{sample_id} frame {annotation.get('frame_id')}: bbox out of bounds")
            if bbox_count != row.get("bbox_frame_count"):
                fail(errors, f"{sample_id}: bbox_frame_count mismatch")
            if usable_count != row.get("usable_bbox_frame_count"):
                fail(errors, f"{sample_id}: usable_bbox_frame_count mismatch")

            annotation_path = row.get("annotation_path")
            if has_annotations:
                if not annotation_path or not (ROOT / Path(annotation_path)).is_file():
                    fail(errors, f"{sample_id}: missing canonical annotation CSV")
            elif annotation_path is not None:
                fail(errors, f"{sample_id}: unannotated record has annotation_path")

            counts["videos"] += 1
            counts["annotated_videos"] += has_annotations
            counts["annotation_rows"] += len(annotations)
            counts["bbox_rows"] += bbox_count
            counts["usable_bbox_rows"] += usable_count
            counts[f"subset:{row.get('subset')}"] += 1

    disk_videos = set(
        path.relative_to(ROOT / "data").as_posix()
        for path in (ROOT / "data" / "videos").rglob("*.mp4")
    )
    extras = sorted(disk_videos - video_paths)
    if extras:
        fail(errors, f"{len(extras)} unreferenced MP4 files; first: {extras[0]}")
    return counts


def validate_manifest(errors: list[str], checksums: bool) -> Counter:
    manifest_path = ROOT / "manifests" / "files.csv"
    counts: Counter = Counter()
    if not manifest_path.is_file():
        fail(errors, "Missing manifests/files.csv")
        return counts
    with manifest_path.open("r", encoding="utf-8", newline="") as handle:
        for row in csv.DictReader(handle):
            path = ROOT / Path(row["path"])
            if not path.is_file():
                fail(errors, f"Manifest file missing: {row['path']}")
                continue
            if path.stat().st_size != int(row["size_bytes"]):
                fail(errors, f"Manifest size mismatch: {row['path']}")
            if checksums and sha256(path) != row["sha256"]:
                fail(errors, f"Manifest SHA-256 mismatch: {row['path']}")
            counts[f"manifest:{row['role']}"] += 1
    return counts


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--checksums", action="store_true", help="Recompute every payload SHA-256.")
    args = parser.parse_args()
    errors: list[str] = []
    counts = validate_metadata(errors)
    counts.update(validate_manifest(errors, args.checksums))

    if errors:
        print(f"FAILED: {len(errors)} issue(s)", file=sys.stderr)
        for error in errors[:100]:
            print(f"- {error}", file=sys.stderr)
        if len(errors) > 100:
            print(f"- ... {len(errors) - 100} more", file=sys.stderr)
        return 1

    mode = "structure and checksums" if args.checksums else "structure"
    print(f"PASS: {mode}")
    for key in sorted(counts):
        print(f"{key}: {counts[key]}")
    return 0


if __name__ == "__main__":
    sys.exit(main())