File size: 4,321 Bytes
b0b8755
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the streaming-readable XS-VID v2 release annotation contract."""

from __future__ import annotations

import argparse
import hashlib
import json
import math
from collections import Counter
from pathlib import Path

from build_unified_annotations import JsonArrayReader


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


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("annotation", type=Path)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    counts: dict[str, int] = {}
    ids: dict[str, set[int]] = {}
    image_sizes: dict[int, tuple[int, int]] = {}
    tracks: dict[int, dict] = {}
    errors: list[str] = []
    for collection in ("videos", "images", "annotations", "categories", "tracks"):
        values: set[int] = set()
        previous_id = -1
        for record in JsonArrayReader(args.annotation, collection):
            record_id = record.get("id")
            if not isinstance(record_id, int):
                errors.append(f"{collection} record without integer id")
                continue
            if record_id in values:
                errors.append(f"duplicate {collection} id {record_id}")
            if record_id <= previous_id:
                errors.append(f"non-increasing {collection} id {record_id}")
            values.add(record_id)
            previous_id = record_id
            if collection == "annotations":
                if not isinstance(record.get("track_id"), int):
                    errors.append(f"annotation {record_id} lacks integer track_id")
            elif collection == "tracks":
                tracks[record_id] = record
            elif collection == "images":
                image_sizes[record_id] = (record.get("width", 0), record.get("height", 0))
        counts[collection] = len(values)
        ids[collection] = values

    dangling = Counter()
    for image in JsonArrayReader(args.annotation, "images"):
        if image.get("video_id") not in ids["videos"]:
            dangling["image_video"] += 1
    for ann in JsonArrayReader(args.annotation, "annotations"):
        if ann.get("image_id") not in ids["images"]:
            dangling["annotation_image"] += 1
        if ann.get("video_id") not in ids["videos"]:
            dangling["annotation_video"] += 1
        if ann.get("category_id") not in ids["categories"]:
            dangling["annotation_category"] += 1
        if ann.get("track_id") not in ids["tracks"]:
            dangling["annotation_track"] += 1
        else:
            track = tracks[ann["track_id"]]
            if track.get("video_id") != ann.get("video_id"):
                dangling["annotation_track_video"] += 1
            if track.get("category_id") != ann.get("category_id"):
                dangling["annotation_track_category"] += 1
        bbox = ann.get("bbox")
        image_size = image_sizes.get(ann.get("image_id"))
        if not isinstance(bbox, list) or len(bbox) != 4 or image_size is None:
            dangling["annotation_bbox"] += 1
        elif not all(isinstance(value, (int, float)) and math.isfinite(value) for value in bbox):
            dangling["annotation_bbox"] += 1
        else:
            x, y, width, height = bbox
            image_width, image_height = image_size
            if width <= 0 or height <= 0 or x < 0 or y < 0 or x + width > image_width or y + height > image_height:
                dangling["annotation_bbox"] += 1
    for name, count in dangling.items():
        if count:
            errors.append(f"{count} dangling {name} references")

    result = {
        "annotation": args.annotation.name,
        "sha256": sha256(args.annotation),
        "bytes": args.annotation.stat().st_size,
        "counts": counts,
        "dangling_references": dict(dangling),
        "valid": not errors,
        "errors": errors,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    if errors:
        raise SystemExit("; ".join(errors[:5]))


if __name__ == "__main__":
    main()