Hezep commited on
Commit
0d09cd5
·
verified ·
1 Parent(s): ddadc9f

Delete audiomarathon.py

Browse files
Files changed (1) hide show
  1. audiomarathon.py +0 -338
audiomarathon.py DELETED
@@ -1,338 +0,0 @@
1
- """
2
- AudioMarathon Dataset Loading Script for Hugging Face
3
- 支持10个音频理解任务的数据集加载
4
- """
5
-
6
- import datasets
7
- import json
8
- import os
9
- import glob
10
- from pathlib import Path
11
-
12
- _CITATION = """
13
- @misc{audio_marathon_2025,
14
- title={AudioMarathon: A Comprehensive Audio Understanding Benchmark},
15
- author={Your Team},
16
- year={2025}
17
- }
18
- """
19
-
20
- _DESCRIPTION = """
21
- AudioMarathon is a comprehensive multi-task audio understanding benchmark containing 10 tasks:
22
-
23
- 1. **RACE**: Reading Comprehension QA from audio
24
- 2. **HAD**: Half-truth Audio Detection (authenticity classification)
25
- 3. **GTZAN**: Music Genre Classification
26
- 4. **TAU**: Acoustic Scene Classification
27
- 5. **VESUS**: Emotion Recognition from speech
28
- 6. **SLUE**: Named Entity Recognition from speech
29
- 7. **DESED**: Sound Event Detection
30
- 8. **VoxCeleb-Gender**: Speaker Gender Identification
31
- 9. **VoxCeleb-Age**: Speaker Age Classification
32
- 10. **LibriSpeech**: Automatic Speech Recognition (ASR)
33
-
34
- Total: ~6,000 audio samples, 60GB data
35
- """
36
-
37
- _HOMEPAGE = "https://github.com/your-repo/audio-marathon"
38
- _LICENSE = "CC-BY-4.0"
39
-
40
- # 数据文件路径映射
41
- _URLS = {
42
- "race": "Dataset/race_audio/race_benchmark.json",
43
- "had": "Dataset/HAD/concatenated_audio/had_audio_classification_task.json",
44
- "gtzan": "Dataset/GTZAN/concatenated_audio/music_genre_classification_meta.json",
45
- "tau": "Dataset/TAU/acoustic_scene_task_meta.json",
46
- "vesus": "Dataset/VESUS/audio_emotion_dataset.json",
47
- "slue": "Dataset/SLUE/merged_audio_data.json",
48
- "desed": "Dataset/DESED/DESED_dataset/concatenated_audio/desed_sound_event_detection_task.json",
49
- "voxceleb_gender": "Dataset/VoxCeleb/concatenated_audio/gender_id_task_meta.json",
50
- "voxceleb_age": "Dataset/VoxCeleb/concatenated_audio_age/age_classification_task_meta.json",
51
- "librispeech": "Dataset/librispeech-long", # 目录而非JSON
52
- }
53
-
54
-
55
- class AudioMarathonConfig(datasets.BuilderConfig):
56
- """BuilderConfig for AudioMarathon."""
57
-
58
- def __init__(self, **kwargs):
59
- super(AudioMarathonConfig, self).__init__(**kwargs)
60
-
61
-
62
- class AudioMarathon(datasets.GeneratorBasedBuilder):
63
- """AudioMarathon Dataset - 10个音频理解任务"""
64
-
65
- VERSION = datasets.Version("1.0.0")
66
-
67
- BUILDER_CONFIGS = [
68
- AudioMarathonConfig(name="race", version=VERSION,
69
- description="Reading comprehension from audio"),
70
- AudioMarathonConfig(name="had", version=VERSION,
71
- description="Half-truth audio detection"),
72
- AudioMarathonConfig(name="gtzan", version=VERSION,
73
- description="Music genre classification"),
74
- AudioMarathonConfig(name="tau", version=VERSION,
75
- description="Acoustic scene classification"),
76
- AudioMarathonConfig(name="vesus", version=VERSION,
77
- description="Emotion recognition"),
78
- AudioMarathonConfig(name="slue", version=VERSION,
79
- description="Named entity recognition"),
80
- AudioMarathonConfig(name="desed", version=VERSION,
81
- description="Sound event detection"),
82
- AudioMarathonConfig(name="voxceleb_gender", version=VERSION,
83
- description="Speaker gender identification"),
84
- AudioMarathonConfig(name="voxceleb_age", version=VERSION,
85
- description="Speaker age classification"),
86
- AudioMarathonConfig(name="librispeech", version=VERSION,
87
- description="Automatic speech recognition"),
88
- AudioMarathonConfig(name="all", version=VERSION,
89
- description="All 10 tasks combined"),
90
- ]
91
-
92
- DEFAULT_CONFIG_NAME = "all"
93
-
94
- def _info(self):
95
- """定义数据集特征"""
96
- features = datasets.Features({
97
- "audio": datasets.Audio(sampling_rate=16000),
98
- "question": datasets.Value("string"),
99
- "options": datasets.Sequence(datasets.Value("string")),
100
- "answer": datasets.Value("string"),
101
- "task_name": datasets.Value("string"),
102
- "dataset_name": datasets.Value("string"),
103
- "uniq_id": datasets.Value("int32"),
104
- "metadata": datasets.Value("string"), # JSON string for flexible metadata
105
- })
106
-
107
- return datasets.DatasetInfo(
108
- description=_DESCRIPTION,
109
- features=features,
110
- homepage=_HOMEPAGE,
111
- license=_LICENSE,
112
- citation=_CITATION,
113
- )
114
-
115
- def _split_generators(self, dl_manager):
116
- """下载并组织数据分片 - 只返回test分片"""
117
- config_name = self.config.name
118
-
119
- # 根据配置选择要加载的任务
120
- if config_name == "all":
121
- tasks_to_load = list(_URLS.keys())
122
- else:
123
- tasks_to_load = [config_name]
124
-
125
- # 准备数据文件路径(不使用dl_manager.download,直接使用本地路径)
126
- data_paths = {}
127
- for task in tasks_to_load:
128
- if task in _URLS:
129
- # 如果是相对路径,转换为绝对路径
130
- path = _URLS[task]
131
- if not os.path.isabs(path):
132
- # 假设脚本在AudioMarathon目录下
133
- base_dir = os.path.dirname(os.path.abspath(__file__))
134
- path = os.path.join(base_dir, path)
135
- data_paths[task] = path
136
-
137
- # 只返回test分片,不返回train和validation
138
- return [
139
- datasets.SplitGenerator(
140
- name=datasets.Split.TEST,
141
- gen_kwargs={
142
- "data_paths": data_paths,
143
- },
144
- ),
145
- ]
146
-
147
- def _generate_examples(self, data_paths):
148
- """生成数据样本"""
149
- idx = 0
150
-
151
- for task_name, data_path in data_paths.items():
152
- print(f"Loading task: {task_name} from {data_path}")
153
-
154
- if task_name == "librispeech":
155
- # LibriSpeech特殊处理:从目录结构加载
156
- for example in self._load_librispeech(data_path):
157
- yield idx, example
158
- idx += 1
159
- else:
160
- # 其他任务:从JSON加载
161
- for example in self._load_from_json(task_name, data_path):
162
- yield idx, example
163
- idx += 1
164
-
165
- def _load_from_json(self, task_name, json_path):
166
- """从JSON文件加载数据"""
167
- if not os.path.exists(json_path):
168
- print(f"Warning: JSON file not found: {json_path}")
169
- return
170
-
171
- try:
172
- with open(json_path, 'r', encoding='utf-8') as f:
173
- data = json.load(f)
174
- except Exception as e:
175
- print(f"Error loading {json_path}: {e}")
176
- return
177
-
178
- # 获取基础目录(用于构建音频文件路径)
179
- base_dir = os.path.dirname(json_path)
180
-
181
- # 根据数据格式提取样本列表
182
- if isinstance(data, list):
183
- samples = data
184
- elif isinstance(data, dict):
185
- # DESED的特殊格式
186
- if "tasks" in data:
187
- samples = data["tasks"]
188
- # HAD的特殊格式
189
- elif "samples" in data:
190
- samples = data["samples"]
191
- else:
192
- print(f"Warning: Unknown JSON format for {task_name}")
193
- return
194
- else:
195
- print(f"Warning: Unexpected data type for {task_name}")
196
- return
197
-
198
- print(f" Found {len(samples)} samples in {task_name}")
199
-
200
- # 处理每个样本
201
- for sample in samples:
202
- # 构建音频完整路径
203
- audio_rel_path = sample.get("path", "")
204
- if not audio_rel_path:
205
- continue
206
-
207
- audio_path = os.path.join(base_dir, audio_rel_path)
208
-
209
- # 跳过不存在的文件
210
- if not os.path.exists(audio_path):
211
- print(f"Warning: Audio file not found: {audio_path}")
212
- continue
213
-
214
- # 提取options(支持多种格式)
215
- options = []
216
- if "options" in sample:
217
- options = sample["options"]
218
- else:
219
- # 从choice_a, choice_b等构建
220
- for choice in ["choice_a", "choice_b", "choice_c", "choice_d", "choice_e"]:
221
- if choice in sample:
222
- options.append(sample[choice])
223
-
224
- # 提取答案
225
- answer = sample.get("answer", sample.get("answer_gt", ""))
226
-
227
- # 构建元数据
228
- metadata = {
229
- k: v for k, v in sample.items()
230
- if k not in ["path", "question", "options", "answer", "answer_gt",
231
- "choice_a", "choice_b", "choice_c", "choice_d", "choice_e"]
232
- }
233
-
234
- yield {
235
- "audio": audio_path,
236
- "question": sample.get("question", ""),
237
- "options": options,
238
- "answer": answer,
239
- "task_name": sample.get("task_name", task_name),
240
- "dataset_name": sample.get("dataset_name", task_name.upper()),
241
- "uniq_id": sample.get("uniq_id", -1),
242
- "metadata": json.dumps(metadata, ensure_ascii=False)
243
- }
244
-
245
- def _load_librispeech(self, data_dir):
246
- """加载LibriSpeech数据"""
247
-
248
- if not os.path.exists(data_dir):
249
- print(f"Warning: LibriSpeech directory not found: {data_dir}")
250
- return
251
-
252
- # 可能的LibriSpeech子目录
253
- possible_subdirs = [
254
- "test-clean",
255
- "test-other",
256
- "dev-clean",
257
- "dev-other",
258
- ]
259
-
260
- # 查找说话人目录
261
- speaker_dirs = []
262
-
263
- # 检查是否直接包含说话人文件夹(数字命名)
264
- direct_speakers = sorted([
265
- d for d in glob.glob(os.path.join(data_dir, "*"))
266
- if os.path.isdir(d) and os.path.basename(d).isdigit()
267
- ])
268
-
269
- if direct_speakers:
270
- speaker_dirs = direct_speakers
271
- else:
272
- # 检查子目录
273
- for subdir in possible_subdirs:
274
- subdir_path = os.path.join(data_dir, subdir)
275
- if os.path.exists(subdir_path):
276
- speakers = sorted([
277
- d for d in glob.glob(os.path.join(subdir_path, "*"))
278
- if os.path.isdir(d) and os.path.basename(d).isdigit()
279
- ])
280
- speaker_dirs.extend(speakers)
281
-
282
- if not speaker_dirs:
283
- print(f"Warning: No speaker directories found in {data_dir}")
284
- return
285
-
286
- print(f" Found {len(speaker_dirs)} speakers in LibriSpeech")
287
-
288
- # 处理每个说话人目录
289
- sample_idx = 0
290
- for speaker_dir in speaker_dirs:
291
- speaker_id = os.path.basename(speaker_dir)
292
-
293
- # 查找章节目录
294
- chapter_dirs = sorted([
295
- d for d in glob.glob(os.path.join(speaker_dir, "*"))
296
- if os.path.isdir(d)
297
- ])
298
-
299
- for chapter_dir in chapter_dirs:
300
- chapter_id = os.path.basename(chapter_dir)
301
-
302
- # 查找转录文件
303
- trans_file = os.path.join(chapter_dir, f"{speaker_id}-{chapter_id}.trans.txt")
304
- if not os.path.exists(trans_file):
305
- continue
306
-
307
- # 读取转录文本
308
- transcripts = {}
309
- try:
310
- with open(trans_file, 'r', encoding='utf-8') as f:
311
- for line in f:
312
- parts = line.strip().split(' ', 1)
313
- if len(parts) == 2:
314
- utt_id, text = parts
315
- transcripts[utt_id] = text
316
- except Exception as e:
317
- print(f"Error reading {trans_file}: {e}")
318
- continue
319
-
320
- # 查找对应的音频文件
321
- for utt_id, transcript in transcripts.items():
322
- audio_file = os.path.join(chapter_dir, f"{utt_id}.flac")
323
- if os.path.exists(audio_file):
324
- yield {
325
- "audio": audio_file,
326
- "question": "Transcribe this audio accurately. Remove hesitation words like 'um', 'uh'.",
327
- "options": [], # ASR任务通常没有选项
328
- "answer": transcript,
329
- "task_name": "Automatic_Speech_Recognition",
330
- "dataset_name": "LibriSpeech",
331
- "uniq_id": sample_idx,
332
- "metadata": json.dumps({
333
- "speaker_id": speaker_id,
334
- "chapter_id": chapter_id,
335
- "utterance_id": utt_id
336
- })
337
- }
338
- sample_idx += 1