File size: 5,370 Bytes
e5a0703
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Strict-ish schema validator for mux_assets.jsonl.

Usage:
  python scripts/validate_schema.py
"""

from __future__ import annotations

import json
import os
import re
from typing import Any, Dict, List, Tuple

JSONL_PATH = os.path.join("data", "mux_assets.jsonl")

NONEMPTY_STR_FIELDS = [
    "asset_id",
    "upload_id",
    "title",
    "external_id",
    "creator_id",
    "status",
    "video_quality",
    "resolution_tier",
    "aspect_ratio",
    "encoding_tier",
    "mp4_support",
    "playback_policy",
    "playback_id_public",
    "video_track_id",
    "audio_track_id",
    "audio_language_code",
]

BOOL_FIELDS = [
    "normalize_audio",
    "audio_primary",
]

INT_FIELDS = [
    "max_width",
    "max_height",
    "max_frame_rate",
    "audio_channels",
    "created_at_unix",
]

FLOAT_FIELDS = [
    "duration_seconds",
]

REQUIRED_FIELDS = set(NONEMPTY_STR_FIELDS + BOOL_FIELDS + INT_FIELDS + FLOAT_FIELDS + ["raw_mux_json"])
ASPECT_RATIO_RE = re.compile(r"^\d+:\d+$")


def load_jsonl(path: str) -> List[Dict[str, Any]]:
    rows: List[Dict[str, Any]] = []
    with open(path, "r", encoding="utf-8") as f:
        for i, line in enumerate(f, start=1):
            line = line.strip()
            if not line:
                continue
            try:
                rows.append(json.loads(line))
            except json.JSONDecodeError as e:
                raise SystemExit(f"[ERROR] Invalid JSON on line {i}: {e}") from e
    return rows


def validate_all(rows: List[Dict[str, Any]]) -> Tuple[bool, List[str]]:
    errors: List[str] = []

    for idx, row in enumerate(rows):
        missing = [k for k in REQUIRED_FIELDS if k not in row]
        if missing:
            errors.append(f"Row {idx}: missing required fields: {missing}")
            continue

        # types
        for k in NONEMPTY_STR_FIELDS:
            v = row.get(k)
            if not isinstance(v, str) or not v.strip():
                errors.append(f"Row {idx}: field '{k}' must be a non-empty string.")

        for k in BOOL_FIELDS:
            if not isinstance(row.get(k), bool):
                errors.append(f"Row {idx}: field '{k}' must be a boolean.")

        for k in INT_FIELDS:
            if not isinstance(row.get(k), int):
                errors.append(f"Row {idx}: field '{k}' must be an integer.")

        for k in FLOAT_FIELDS:
            if not isinstance(row.get(k), (int, float)):
                errors.append(f"Row {idx}: field '{k}' must be a number (float).")

        if not isinstance(row.get("raw_mux_json"), dict):
            errors.append(f"Row {idx}: field 'raw_mux_json' must be an object/dict.")
            continue

        # ranges / sanity
        if row["duration_seconds"] <= 0:
            errors.append(f"Row {idx}: duration_seconds must be > 0.")

        if row["max_width"] <= 0 or row["max_height"] <= 0:
            errors.append(f"Row {idx}: max_width/max_height must be > 0.")

        if row["max_frame_rate"] <= 0 or row["max_frame_rate"] > 240:
            errors.append(f"Row {idx}: max_frame_rate looks invalid (expected 1..240).")

        if row["audio_channels"] <= 0 or row["audio_channels"] > 16:
            errors.append(f"Row {idx}: audio_channels looks invalid (expected 1..16).")

        if not ASPECT_RATIO_RE.match(row["aspect_ratio"]):
            errors.append(f"Row {idx}: aspect_ratio must match 'W:H' like '16:9'.")

        if row["playback_policy"] not in ("public", "signed"):
            errors.append(f"Row {idx}: playback_policy should be 'public' or 'signed'.")

        # internal consistency checks (light)
        raw = row["raw_mux_json"]
        raw_id = raw.get("id")
        if isinstance(raw_id, str) and raw_id != row["asset_id"]:
            errors.append(f"Row {idx}: raw_mux_json.id != asset_id")

        tracks = raw.get("tracks", [])
        if not isinstance(tracks, list) or not tracks:
            errors.append(f"Row {idx}: raw_mux_json.tracks must be a non-empty list.")
            continue

        track_ids = {t.get("id") for t in tracks if isinstance(t, dict)}
        if row["video_track_id"] not in track_ids:
            errors.append(f"Row {idx}: video_track_id not found in raw_mux_json.tracks.")
        if row["audio_track_id"] not in track_ids:
            errors.append(f"Row {idx}: audio_track_id not found in raw_mux_json.tracks.")

        playback_ids = raw.get("playback_ids", [])
        if isinstance(playback_ids, list) and playback_ids:
            pb0 = playback_ids[0]
            if isinstance(pb0, dict):
                if pb0.get("id") != row["playback_id_public"]:
                    errors.append(f"Row {idx}: raw_mux_json.playback_ids[0].id != playback_id_public")
                if pb0.get("policy") != row["playback_policy"]:
                    errors.append(f"Row {idx}: raw_mux_json.playback_ids[0].policy != playback_policy")

    return (len(errors) == 0), errors


def main() -> None:
    if not os.path.exists(JSONL_PATH):
        raise SystemExit(f"[ERROR] Missing file: {JSONL_PATH}")

    rows = load_jsonl(JSONL_PATH)
    ok, errors = validate_all(rows)

    if ok:
        print(f"[OK] Schema validated: {len(rows)} row(s).")
        return

    print("[FAIL] Schema validation errors:")
    for e in errors:
        print(" -", e)
    raise SystemExit(1)


if __name__ == "__main__":
    main()