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
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#!/usr/bin/env python3
"""Validate the public CSV files and build Viewer-friendly Parquet mirrors.

Run from anywhere with Python 3.9+ and pyarrow installed:

    python scripts/build_release.py

The script never rewrites the CSV files. It validates their schema and split
integrity, writes Parquet mirrors, and refreshes release metadata/checksums.
"""

from __future__ import annotations

import csv
import hashlib
import json
from collections import defaultdict
from pathlib import Path
from typing import Any

import pyarrow as pa
import pyarrow.parquet as pq


ROOT = Path(__file__).resolve().parents[1]
CSV_ROOT = ROOT / "csv"
VIEWER_ROOT = ROOT / "viewer"
METADATA_ROOT = ROOT / "metadata"
SPLITS = ("pretrain", "pretrain_test", "fewshot", "fewshot_test")

DATASETS: dict[str, dict[str, Any]] = {
    "AVE": {
        "columns": 3,
        "expected_rows": {
            "pretrain": 2367,
            "pretrain_test": 252,
            "fewshot": 1290,
            "fewshot_test": 142,
        },
        "source_labels": set(range(16)),
        "target_labels": set(range(16, 28)),
    },
    "Kinetics-Sounds": {
        "columns": 4,
        "expected_rows": {
            "pretrain": 13252,
            "pretrain_test": 1627,
            "fewshot": 7012,
            "fewshot_test": 1017,
        },
        "source_labels": set(range(19)),
        "target_labels": set(range(19, 32)),
    },
    "VGGSound100": {
        "columns": 4,
        "expected_rows": {
            "pretrain": 31081,
            "pretrain_test": 2920,
            "fewshot": 23823,
            "fewshot_test": 1971,
        },
        "source_labels": set(range(60)),
        "target_labels": set(range(60, 100)),
        "known_unavailable_labels": {14},
    },
}

# Recovered from the category mapping used by the original VGGSound100 data
# preparation code. The label-14 typo is retained in source_class_name below,
# while its normalized public name is "subway, metro".
VGGSOUND100_SOURCE_NAMES = [
    "playing theremin",
    "donkey, ass braying",
    "playing electronic organ",
    "zebra braying",
    "people eating noodle",
    "airplane flyby",
    "playing double bass",
    "cat growling",
    "footsteps on snow",
    "playing tennis",
    "black capped chickadee calling",
    "bouncing on trampoline",
    "playing steelpan",
    "waterfall burbling",
    "subway, metr",
    "people clapping",
    "chipmunk chirping",
    "chopping food",
    "people shuffling",
    "elk bugling",
    "alarm clock ringing",
    "people booing",
    "canary calling",
    "chopping wood",
    "people humming",
    "lathe spinning",
    "playing tuning fork",
    "playing violin, fiddle",
    "singing choir",
    "playing timbales",
    "children shouting",
    "chicken crowing",
    "car passing by",
    "driving motorcycle",
    "bull bellowing",
    "lawn mowing",
    "playing bugle",
    "mouse squeaking",
    "child singing",
    "playing tympani",
    "hair dryer drying",
    "basketball bounce",
    "driving snowmobile",
    "train whistling",
    "thunder",
    "dog bow-wow",
    "ocean burbling",
    "cuckoo bird calling",
    "sheep bleating",
    "splashing water",
    "air conditioning noise",
    "cattle mooing",
    "eagle screaming",
    "air horn",
    "playing bass guitar",
    "sloshing water",
    "tap dancing",
    "running electric fan",
    "playing ukulele",
    "playing guiro",
    "playing shofar",
    "people sniggering",
    "people whispering",
    "people finger snapping",
    "car engine idling",
    "bathroom ventilation fan running",
    "police car (siren)",
    "roller coaster running",
    "playing french horn",
    "swimming",
    "lighting firecrackers",
    "playing electric guitar",
    "playing castanets",
    "people babbling",
    "arc welding",
    "wood thrush calling",
    "wind rustling leaves",
    "playing darts",
    "planing timber",
    "crow cawing",
    "shot football",
    "writing on blackboard with chalk",
    "people slapping",
    "using sewing machines",
    "raining",
    "dog howling",
    "playing cello",
    "playing trumpet",
    "fox barking",
    "bowling impact",
    "people crowd",
    "pumping water",
    "ice cracking",
    "baby crying",
    "playing bass drum",
    "playing bongo",
    "tornado roaring",
    "playing steel guitar, slide guitar",
    "playing squash",
    "typing on typewriter",
]


def ave_source_name(clip_id: str) -> str:
    """Extract the AVE category suffix after the 11-character video ID."""

    if len(clip_id) < 13 or clip_id[11] != "_":
        raise ValueError(f"Unexpected AVE clip_id format: {clip_id!r}")
    return clip_id[12:]


def read_split(dataset: str, split: str) -> list[dict[str, Any]]:
    path = CSV_ROOT / dataset / f"{split}.csv"
    expected_columns = DATASETS[dataset]["columns"]
    records: list[dict[str, Any]] = []
    seen_ids: set[str] = set()

    with path.open("r", encoding="utf-8-sig", newline="") as handle:
        for line_number, row in enumerate(csv.reader(handle), start=1):
            if len(row) != expected_columns:
                raise ValueError(
                    f"{path}:{line_number}: expected {expected_columns} columns, "
                    f"found {len(row)}"
                )
            if any(value == "" for value in row):
                raise ValueError(f"{path}:{line_number}: blank field")

            clip_id, label_text, semantic_prompt = row[:3]
            try:
                label = int(label_text)
            except ValueError as exc:
                raise ValueError(
                    f"{path}:{line_number}: invalid integer label {label_text!r}"
                ) from exc

            if clip_id in seen_ids:
                raise ValueError(f"{path}:{line_number}: duplicate clip_id {clip_id!r}")
            seen_ids.add(clip_id)

            if dataset == "AVE":
                source_name = ave_source_name(clip_id)
                class_name = source_name.replace("_", " ")
            else:
                source_name = row[3]
                class_name = source_name

            records.append(
                {
                    "clip_id": clip_id,
                    "label": label,
                    "semantic_prompt": semantic_prompt,
                    "class_name": class_name,
                    "source_class_name": source_name,
                }
            )

    expected_rows = DATASETS[dataset]["expected_rows"][split]
    if len(records) != expected_rows:
        raise ValueError(f"{path}: expected {expected_rows} rows, found {len(records)}")
    return records


def validate_labels(
    dataset: str, records_by_split: dict[str, list[dict[str, Any]]]
) -> dict[int, str]:
    label_to_names: dict[int, set[str]] = defaultdict(set)
    for records in records_by_split.values():
        for record in records:
            label_to_names[record["label"]].add(record["source_class_name"])

    inconsistent = {
        label: sorted(names) for label, names in label_to_names.items() if len(names) != 1
    }
    if inconsistent:
        raise ValueError(f"{dataset}: labels map to multiple class names: {inconsistent}")

    observed = set(label_to_names)
    expected = DATASETS[dataset]["source_labels"] | DATASETS[dataset]["target_labels"]
    unavailable = DATASETS[dataset].get("known_unavailable_labels", set())
    if observed != expected - unavailable:
        raise ValueError(
            f"{dataset}: unexpected label coverage; missing={sorted(expected - observed)}, "
            f"extra={sorted(observed - expected)}"
        )

    return {label: next(iter(names)) for label, names in label_to_names.items()}


def validate_partition_integrity(
    dataset: str, records_by_split: dict[str, list[dict[str, Any]]]
) -> None:
    expected_source = DATASETS[dataset]["source_labels"]
    expected_target = DATASETS[dataset]["target_labels"]
    unavailable = DATASETS[dataset].get("known_unavailable_labels", set())

    for split in ("pretrain", "pretrain_test"):
        labels = {record["label"] for record in records_by_split[split]}
        if labels != expected_source - unavailable:
            raise ValueError(f"{dataset}/{split}: source label set mismatch")
    for split in ("fewshot", "fewshot_test"):
        labels = {record["label"] for record in records_by_split[split]}
        if labels != expected_target:
            raise ValueError(f"{dataset}/{split}: target label set mismatch")

    split_ids = {
        split: {record["clip_id"] for record in records}
        for split, records in records_by_split.items()
    }
    for index, left in enumerate(SPLITS):
        for right in SPLITS[index + 1 :]:
            overlap = split_ids[left] & split_ids[right]
            if overlap:
                examples = sorted(overlap)[:5]
                raise ValueError(
                    f"{dataset}: clip leakage between {left} and {right}: {examples}"
                )


def write_parquet(dataset: str, split: str, records: list[dict[str, Any]]) -> None:
    output_dir = VIEWER_ROOT / dataset
    output_dir.mkdir(parents=True, exist_ok=True)
    table = pa.table(
        {
            "clip_id": pa.array([record["clip_id"] for record in records], pa.string()),
            "label": pa.array([record["label"] for record in records], pa.int64()),
            "semantic_prompt": pa.array(
                [record["semantic_prompt"] for record in records], pa.string()
            ),
            "class_name": pa.array(
                [record["class_name"] for record in records], pa.string()
            ),
        }
    )
    output_path = output_dir / f"{split}.parquet"
    pq.write_table(
        table,
        output_path,
        compression="zstd",
        use_dictionary=["label", "class_name"],
        write_page_index=True,
    )

    # Read the artifact back and compare every exported cell. This catches
    # schema coercion or truncation before a release is staged.
    restored = pq.read_table(output_path).to_pydict()
    expected = {
        "clip_id": [record["clip_id"] for record in records],
        "label": [record["label"] for record in records],
        "semantic_prompt": [record["semantic_prompt"] for record in records],
        "class_name": [record["class_name"] for record in records],
    }
    if restored != expected:
        raise ValueError(f"{dataset}/{split}: Parquet round-trip mismatch")


def build_label_map(
    dataset: str, observed_names: dict[int, str]
) -> list[dict[str, Any]]:
    all_labels = sorted(
        DATASETS[dataset]["source_labels"] | DATASETS[dataset]["target_labels"]
    )
    unavailable = DATASETS[dataset].get("known_unavailable_labels", set())
    entries = []
    for label in all_labels:
        if dataset == "VGGSound100":
            source_name = VGGSOUND100_SOURCE_NAMES[label]
            class_name = "subway, metro" if label == 14 else source_name
        else:
            source_name = observed_names[label]
            class_name = source_name.replace("_", " ") if dataset == "AVE" else source_name

        entry: dict[str, Any] = {
            "label": label,
            "class_name": class_name,
            "source_class_name": source_name,
            "split_role": (
                "source" if label in DATASETS[dataset]["source_labels"] else "target"
            ),
            "available": label not in unavailable,
        }
        if label in unavailable:
            entry["note"] = "No obtainable media was available in the release snapshot."
        entries.append(entry)
    return entries


def sha256(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 write_checksums() -> None:
    included = []
    for directory in (CSV_ROOT, VIEWER_ROOT, METADATA_ROOT):
        included.extend(path for path in directory.rglob("*") if path.is_file())
    checksum_path = METADATA_ROOT / "checksums.sha256"
    included = [path for path in included if path != checksum_path]
    lines = [f"{sha256(path)}  {path.relative_to(ROOT).as_posix()}" for path in sorted(included)]
    checksum_path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")


def main() -> None:
    if len(VGGSOUND100_SOURCE_NAMES) != 100:
        raise ValueError("VGGSound100 label map must contain exactly 100 entries")

    METADATA_ROOT.mkdir(parents=True, exist_ok=True)
    all_label_maps: dict[str, list[dict[str, Any]]] = {}
    statistics: dict[str, Any] = {"release_total_rows": 0, "datasets": {}}

    for dataset, specification in DATASETS.items():
        records_by_split = {split: read_split(dataset, split) for split in SPLITS}
        validate_partition_integrity(dataset, records_by_split)
        observed_names = validate_labels(dataset, records_by_split)
        all_label_maps[dataset] = build_label_map(dataset, observed_names)

        split_statistics: dict[str, Any] = {}
        dataset_total = 0
        for split, records in records_by_split.items():
            write_parquet(dataset, split, records)
            row_count = len(records)
            dataset_total += row_count
            split_statistics[split] = {
                "rows": row_count,
                "labels": sorted({record["label"] for record in records}),
                "num_labels": len({record["label"] for record in records}),
            }

        statistics["datasets"][dataset] = {
            "rows": dataset_total,
            "source_classes_defined": len(specification["source_labels"]),
            "source_classes_available": len(
                specification["source_labels"]
                - specification.get("known_unavailable_labels", set())
            ),
            "target_classes": len(specification["target_labels"]),
            "splits": split_statistics,
        }
        statistics["release_total_rows"] += dataset_total

    (METADATA_ROOT / "label_maps.json").write_text(
        json.dumps(all_label_maps, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    (METADATA_ROOT / "dataset_statistics.json").write_text(
        json.dumps(statistics, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    write_checksums()
    print(
        f"Validated and built {statistics['release_total_rows']:,} rows "
        f"across {len(DATASETS)} datasets."
    )


if __name__ == "__main__":
    main()