Rthur2003 commited on
Commit
bfbcec4
·
1 Parent(s): 621b77e

feat: add SONICS dataset loader for AURIS training pipeline

Browse files
Files changed (1) hide show
  1. app/training/dataset_loader.py +171 -0
app/training/dataset_loader.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SONICS dataset loader for AURIS training pipeline.
3
+
4
+ Downloads AI-generated and human-composed music samples
5
+ from the SONICS dataset on HuggingFace, saves audio files
6
+ to disk, and creates a CSV manifest for training.
7
+
8
+ SONICS: ~97K tracks from multiple AI generators and human sources.
9
+ Paper: "SONICS: Synthetic Or Not — Identifying Counterfeit Songs"
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import csv
15
+ import io
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Optional
20
+
21
+ import numpy as np
22
+ import soundfile as sf
23
+
24
+
25
+ def load_sonics(
26
+ output_dir: str | Path,
27
+ max_samples: int = 20_000,
28
+ split: str = "train",
29
+ seed: int = 42,
30
+ ) -> Path:
31
+ """
32
+ Download SONICS dataset and create training manifest.
33
+
34
+ Args:
35
+ output_dir: Directory to save audio files and manifest.
36
+ max_samples: Maximum total samples (balanced AI/human).
37
+ split: Dataset split to use.
38
+ seed: Random seed for reproducibility.
39
+
40
+ Returns:
41
+ Path to the manifest CSV file.
42
+ """
43
+ from datasets import load_dataset
44
+
45
+ output_dir = Path(output_dir)
46
+ audio_dir = output_dir / "audio"
47
+ audio_dir.mkdir(parents=True, exist_ok=True)
48
+
49
+ manifest_path = output_dir / "manifest.csv"
50
+
51
+ print(f"Loading SONICS dataset (split={split})...")
52
+ ds = load_dataset(
53
+ "awesomejjay/sonics",
54
+ split=split,
55
+ streaming=True,
56
+ trust_remote_code=True,
57
+ )
58
+
59
+ half = max_samples // 2
60
+ ai_count = 0
61
+ human_count = 0
62
+ total = 0
63
+
64
+ with open(manifest_path, "w", newline="", encoding="utf-8") as f:
65
+ writer = csv.DictWriter(f, fieldnames=[
66
+ "file_path", "label", "label_int",
67
+ "generator", "duration_sec", "sample_rate",
68
+ ])
69
+ writer.writeheader()
70
+
71
+ for sample in ds:
72
+ # Determine label
73
+ is_ai = sample.get("is_ai", None)
74
+ label_str = sample.get("label", "")
75
+ generator = sample.get("generator", "unknown")
76
+
77
+ if is_ai is None:
78
+ # Try to infer from label field
79
+ if isinstance(label_str, str):
80
+ is_ai = label_str.lower() in (
81
+ "ai", "fake", "generated", "synthetic",
82
+ )
83
+ elif isinstance(label_str, (int, float)):
84
+ is_ai = bool(label_str)
85
+ else:
86
+ continue
87
+
88
+ # Balance classes
89
+ if is_ai and ai_count >= half:
90
+ continue
91
+ if not is_ai and human_count >= half:
92
+ continue
93
+
94
+ # Extract audio
95
+ audio_data = sample.get("audio", None)
96
+ if audio_data is None:
97
+ continue
98
+
99
+ array = audio_data.get("array", None)
100
+ sr = audio_data.get("sampling_rate", 16000)
101
+
102
+ if array is None or len(array) < sr:
103
+ continue # Skip very short clips
104
+
105
+ # Save audio file
106
+ label_tag = "ai" if is_ai else "human"
107
+ filename = f"{label_tag}_{total:06d}.wav"
108
+ filepath = audio_dir / filename
109
+
110
+ audio_array = np.array(array, dtype=np.float32)
111
+
112
+ # Truncate to 30 seconds max to save space
113
+ max_len = sr * 30
114
+ if len(audio_array) > max_len:
115
+ audio_array = audio_array[:max_len]
116
+
117
+ duration = len(audio_array) / sr
118
+
119
+ sf.write(str(filepath), audio_array, sr)
120
+
121
+ writer.writerow({
122
+ "file_path": str(filepath),
123
+ "label": label_tag,
124
+ "label_int": 1 if is_ai else 0,
125
+ "generator": generator,
126
+ "duration_sec": round(duration, 2),
127
+ "sample_rate": sr,
128
+ })
129
+
130
+ if is_ai:
131
+ ai_count += 1
132
+ else:
133
+ human_count += 1
134
+ total += 1
135
+
136
+ if total % 100 == 0:
137
+ print(
138
+ f" [{total}/{max_samples}] "
139
+ f"AI={ai_count}, Human={human_count}"
140
+ )
141
+
142
+ if ai_count >= half and human_count >= half:
143
+ break
144
+
145
+ print(
146
+ f"\nDataset ready: {total} samples "
147
+ f"(AI={ai_count}, Human={human_count})"
148
+ )
149
+ print(f"Manifest: {manifest_path}")
150
+ print(f"Audio dir: {audio_dir}")
151
+
152
+ return manifest_path
153
+
154
+
155
+ def load_manifest(manifest_path: str | Path) -> list[dict]:
156
+ """Load manifest CSV into list of dicts."""
157
+ rows = []
158
+ with open(manifest_path, "r", encoding="utf-8") as f:
159
+ reader = csv.DictReader(f)
160
+ for row in reader:
161
+ row["label_int"] = int(row["label_int"])
162
+ row["duration_sec"] = float(row["duration_sec"])
163
+ row["sample_rate"] = int(row["sample_rate"])
164
+ rows.append(row)
165
+ return rows
166
+
167
+
168
+ if __name__ == "__main__":
169
+ out = sys.argv[1] if len(sys.argv) > 1 else "data/sonics"
170
+ n = int(sys.argv[2]) if len(sys.argv) > 2 else 2000
171
+ load_sonics(out, max_samples=n)