SMP_FSAVC_Dataset / scripts /build_release.py
Zephyrus-H's picture
Initial release of SMP-FSAVC dataset
ee2574f verified
Raw
History Blame Contribute Delete
14.5 kB
#!/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()