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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert Music4All raw files into a Hugging Face Dataset."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, Iterable, List, Optional
|
| 10 |
+
|
| 11 |
+
from datasets import Audio, Dataset, DatasetDict, Features, Sequence, Value
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args() -> argparse.Namespace:
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description="Build a Hugging Face dataset from Music4All raw files."
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
"--data-dir",
|
| 20 |
+
type=Path,
|
| 21 |
+
default=Path("."),
|
| 22 |
+
help="Folder containing id_*.csv, audios/, and lyrics/.",
|
| 23 |
+
)
|
| 24 |
+
parser.add_argument(
|
| 25 |
+
"--output-dir",
|
| 26 |
+
type=Path,
|
| 27 |
+
default=Path("hf_music4all"),
|
| 28 |
+
help="Output directory for DatasetDict.save_to_disk().",
|
| 29 |
+
)
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
"--val-size",
|
| 32 |
+
type=float,
|
| 33 |
+
default=0.0,
|
| 34 |
+
help="Validation split size as a fraction of total dataset, e.g. 0.05.",
|
| 35 |
+
)
|
| 36 |
+
parser.add_argument(
|
| 37 |
+
"--test-size",
|
| 38 |
+
type=float,
|
| 39 |
+
default=0.0,
|
| 40 |
+
help="Test split size as a fraction of total dataset, e.g. 0.1.",
|
| 41 |
+
)
|
| 42 |
+
parser.add_argument(
|
| 43 |
+
"--seed",
|
| 44 |
+
type=int,
|
| 45 |
+
default=42,
|
| 46 |
+
help="Random seed used for split generation.",
|
| 47 |
+
)
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--max-rows",
|
| 50 |
+
type=int,
|
| 51 |
+
default=None,
|
| 52 |
+
help="Optional cap for quick debugging.",
|
| 53 |
+
)
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--no-audio",
|
| 56 |
+
action="store_true",
|
| 57 |
+
help="Do not include the audio column.",
|
| 58 |
+
)
|
| 59 |
+
parser.add_argument(
|
| 60 |
+
"--no-lyrics",
|
| 61 |
+
action="store_true",
|
| 62 |
+
help="Do not include the lyrics column.",
|
| 63 |
+
)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--strict",
|
| 66 |
+
action="store_true",
|
| 67 |
+
help="Fail if required metadata rows are missing for an id.",
|
| 68 |
+
)
|
| 69 |
+
return parser.parse_args()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def read_tsv_to_map(path: Path) -> Dict[str, Dict[str, str]]:
|
| 73 |
+
with path.open("r", encoding="utf-8", newline="") as f:
|
| 74 |
+
reader = csv.DictReader(f, delimiter="\t")
|
| 75 |
+
table: Dict[str, Dict[str, str]] = {}
|
| 76 |
+
for row in reader:
|
| 77 |
+
song_id = row.pop("id")
|
| 78 |
+
table[song_id] = row
|
| 79 |
+
return table
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def parse_csv_list(raw: str) -> List[str]:
|
| 83 |
+
if not raw:
|
| 84 |
+
return []
|
| 85 |
+
return [item.strip() for item in raw.split(",") if item.strip()]
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def maybe_float(raw: Optional[str]) -> Optional[float]:
|
| 89 |
+
if raw is None or raw == "":
|
| 90 |
+
return None
|
| 91 |
+
return float(raw)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def maybe_int(raw: Optional[str]) -> Optional[int]:
|
| 95 |
+
if raw is None or raw == "":
|
| 96 |
+
return None
|
| 97 |
+
return int(float(raw))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def read_text_if_exists(path: Path) -> Optional[str]:
|
| 101 |
+
if not path.exists():
|
| 102 |
+
return None
|
| 103 |
+
return path.read_text(encoding="utf-8")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def iter_examples(
|
| 107 |
+
data_dir: Path,
|
| 108 |
+
include_audio: bool,
|
| 109 |
+
include_lyrics: bool,
|
| 110 |
+
strict: bool,
|
| 111 |
+
max_rows: Optional[int],
|
| 112 |
+
) -> Iterable[Dict[str, object]]:
|
| 113 |
+
metadata = read_tsv_to_map(data_dir / "id_metadata.csv")
|
| 114 |
+
genres = read_tsv_to_map(data_dir / "id_genres.csv")
|
| 115 |
+
tags = read_tsv_to_map(data_dir / "id_tags.csv")
|
| 116 |
+
langs = read_tsv_to_map(data_dir / "id_lang.csv")
|
| 117 |
+
|
| 118 |
+
info_path = data_dir / "id_information.csv"
|
| 119 |
+
with info_path.open("r", encoding="utf-8", newline="") as f:
|
| 120 |
+
reader = csv.DictReader(f, delimiter="\t")
|
| 121 |
+
for idx, info in enumerate(reader):
|
| 122 |
+
if max_rows is not None and idx >= max_rows:
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
song_id = info["id"]
|
| 126 |
+
meta = metadata.get(song_id)
|
| 127 |
+
genre_row = genres.get(song_id)
|
| 128 |
+
tag_row = tags.get(song_id)
|
| 129 |
+
lang_row = langs.get(song_id)
|
| 130 |
+
|
| 131 |
+
if strict and (
|
| 132 |
+
meta is None or genre_row is None or tag_row is None or lang_row is None
|
| 133 |
+
):
|
| 134 |
+
raise KeyError(f"Missing one or more metadata rows for id={song_id}")
|
| 135 |
+
|
| 136 |
+
meta = meta or {}
|
| 137 |
+
genre_row = genre_row or {}
|
| 138 |
+
tag_row = tag_row or {}
|
| 139 |
+
lang_row = lang_row or {}
|
| 140 |
+
|
| 141 |
+
row: Dict[str, object] = {
|
| 142 |
+
"id": song_id,
|
| 143 |
+
"artist": info.get("artist", ""),
|
| 144 |
+
"song": info.get("song", ""),
|
| 145 |
+
"album_name": info.get("album_name", ""),
|
| 146 |
+
"spotify_id": meta.get("spotify_id", ""),
|
| 147 |
+
"popularity": maybe_float(meta.get("popularity")),
|
| 148 |
+
"release": maybe_int(meta.get("release")),
|
| 149 |
+
"danceability": maybe_float(meta.get("danceability")),
|
| 150 |
+
"energy": maybe_float(meta.get("energy")),
|
| 151 |
+
"key": maybe_int(meta.get("key")),
|
| 152 |
+
"mode": maybe_int(meta.get("mode")),
|
| 153 |
+
"valence": maybe_float(meta.get("valence")),
|
| 154 |
+
"tempo": maybe_float(meta.get("tempo")),
|
| 155 |
+
"duration_ms": maybe_int(meta.get("duration_ms")),
|
| 156 |
+
"genres": parse_csv_list(genre_row.get("genres", "")),
|
| 157 |
+
"tags": parse_csv_list(tag_row.get("tags", "")),
|
| 158 |
+
"lang": lang_row.get("lang", ""),
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
if include_lyrics:
|
| 162 |
+
lyrics_path = data_dir / "lyrics" / f"{song_id}.txt"
|
| 163 |
+
row["lyrics"] = read_text_if_exists(lyrics_path)
|
| 164 |
+
|
| 165 |
+
if include_audio:
|
| 166 |
+
audio_relpath = Path("audios") / f"{song_id}.mp3"
|
| 167 |
+
audio_path = data_dir / audio_relpath
|
| 168 |
+
row["audio"] = str(audio_relpath) if audio_path.exists() else None
|
| 169 |
+
|
| 170 |
+
yield row
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def make_features(include_audio: bool, include_lyrics: bool) -> Features:
|
| 174 |
+
fields = {
|
| 175 |
+
"id": Value("string"),
|
| 176 |
+
"artist": Value("string"),
|
| 177 |
+
"song": Value("string"),
|
| 178 |
+
"album_name": Value("string"),
|
| 179 |
+
"spotify_id": Value("string"),
|
| 180 |
+
"popularity": Value("float32"),
|
| 181 |
+
"release": Value("int32"),
|
| 182 |
+
"danceability": Value("float32"),
|
| 183 |
+
"energy": Value("float32"),
|
| 184 |
+
"key": Value("int32"),
|
| 185 |
+
"mode": Value("int32"),
|
| 186 |
+
"valence": Value("float32"),
|
| 187 |
+
"tempo": Value("float32"),
|
| 188 |
+
"duration_ms": Value("int32"),
|
| 189 |
+
"genres": Sequence(Value("string")),
|
| 190 |
+
"tags": Sequence(Value("string")),
|
| 191 |
+
"lang": Value("string"),
|
| 192 |
+
}
|
| 193 |
+
if include_lyrics:
|
| 194 |
+
fields["lyrics"] = Value("string")
|
| 195 |
+
if include_audio:
|
| 196 |
+
fields["audio"] = Audio(decode=False)
|
| 197 |
+
return Features(fields)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def make_splits(
|
| 201 |
+
dataset: Dataset, val_size: float, test_size: float, seed: int
|
| 202 |
+
) -> DatasetDict:
|
| 203 |
+
if val_size < 0 or test_size < 0:
|
| 204 |
+
raise ValueError("--val-size and --test-size must be >= 0.")
|
| 205 |
+
if val_size + test_size >= 1:
|
| 206 |
+
raise ValueError("--val-size + --test-size must be < 1.")
|
| 207 |
+
|
| 208 |
+
if val_size == 0 and test_size == 0:
|
| 209 |
+
return DatasetDict({"train": dataset})
|
| 210 |
+
|
| 211 |
+
train_ds = dataset
|
| 212 |
+
splits: Dict[str, Dataset] = {}
|
| 213 |
+
|
| 214 |
+
if test_size > 0:
|
| 215 |
+
first = train_ds.train_test_split(test_size=test_size, seed=seed)
|
| 216 |
+
train_ds = first["train"]
|
| 217 |
+
splits["test"] = first["test"]
|
| 218 |
+
|
| 219 |
+
if val_size > 0:
|
| 220 |
+
val_ratio_from_remaining = val_size / (1.0 - test_size)
|
| 221 |
+
second = train_ds.train_test_split(
|
| 222 |
+
test_size=val_ratio_from_remaining, seed=seed
|
| 223 |
+
)
|
| 224 |
+
train_ds = second["train"]
|
| 225 |
+
splits["validation"] = second["test"]
|
| 226 |
+
|
| 227 |
+
splits["train"] = train_ds
|
| 228 |
+
|
| 229 |
+
ordered = {}
|
| 230 |
+
for name in ("train", "validation", "test"):
|
| 231 |
+
if name in splits:
|
| 232 |
+
ordered[name] = splits[name]
|
| 233 |
+
return DatasetDict(ordered)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def main() -> None:
|
| 237 |
+
args = parse_args()
|
| 238 |
+
data_dir = args.data_dir.resolve()
|
| 239 |
+
output_dir = args.output_dir.resolve()
|
| 240 |
+
include_audio = not args.no_audio
|
| 241 |
+
include_lyrics = not args.no_lyrics
|
| 242 |
+
|
| 243 |
+
dataset = Dataset.from_generator(
|
| 244 |
+
iter_examples,
|
| 245 |
+
num_proc=4,
|
| 246 |
+
gen_kwargs={
|
| 247 |
+
"data_dir": data_dir,
|
| 248 |
+
"include_audio": include_audio,
|
| 249 |
+
"include_lyrics": include_lyrics,
|
| 250 |
+
"strict": args.strict,
|
| 251 |
+
"max_rows": args.max_rows,
|
| 252 |
+
},
|
| 253 |
+
features=make_features(include_audio, include_lyrics),
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
dataset_dict = make_splits(
|
| 257 |
+
dataset=dataset,
|
| 258 |
+
val_size=args.val_size,
|
| 259 |
+
test_size=args.test_size,
|
| 260 |
+
seed=args.seed,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 264 |
+
dataset_dict.save_to_disk(str(output_dir))
|
| 265 |
+
|
| 266 |
+
print("Saved HF DatasetDict to:", output_dir)
|
| 267 |
+
for split_name, split in dataset_dict.items():
|
| 268 |
+
print(f"{split_name}: {len(split)} rows")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
if __name__ == "__main__":
|
| 272 |
+
main()
|