Create audioset.py
Browse files- audioset.py +154 -0
audioset.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
|
3 |
+
"""AudioSet sound event classification dataset."""
|
4 |
+
|
5 |
+
|
6 |
+
import os
|
7 |
+
import json
|
8 |
+
import textwrap
|
9 |
+
import datasets
|
10 |
+
import itertools
|
11 |
+
import typing as tp
|
12 |
+
import pandas as pd
|
13 |
+
from pathlib import Path
|
14 |
+
from huggingface_hub import hf_hub_download
|
15 |
+
|
16 |
+
|
17 |
+
SAMPLE_RATE = 22_050
|
18 |
+
|
19 |
+
_BALANCED_TRAIN_FILENAME = 'balanced_train_segments.zip'
|
20 |
+
_EVAL_FILENAME = 'eval_segments.zip'
|
21 |
+
|
22 |
+
ID2LABEL = json.load(
|
23 |
+
open(hf_hub_download("huggingface/label-files", "audioset-id2label.json", repo_type="dataset"), "r")
|
24 |
+
)
|
25 |
+
LABEL2ID = {v:k for k, v in ID2LABEL.items()}
|
26 |
+
CLASSES = list(set(LABEL2ID.keys()))
|
27 |
+
|
28 |
+
|
29 |
+
class AudioSetConfig(datasets.BuilderConfig):
|
30 |
+
"""BuilderConfig for AudioSet."""
|
31 |
+
|
32 |
+
def __init__(self, features, **kwargs):
|
33 |
+
super(AudioSetConfig, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs)
|
34 |
+
self.features = features
|
35 |
+
|
36 |
+
|
37 |
+
class AudioSet(datasets.GeneratorBasedBuilder):
|
38 |
+
|
39 |
+
BUILDER_CONFIGS = [
|
40 |
+
AudioSetConfig(
|
41 |
+
features=datasets.Features(
|
42 |
+
{
|
43 |
+
"file": datasets.Value("string"),
|
44 |
+
"audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
|
45 |
+
"label": datasets.Sequence(datasets.ClassLabel(CLASSES)),
|
46 |
+
}
|
47 |
+
),
|
48 |
+
name="balanced",
|
49 |
+
description="",
|
50 |
+
),
|
51 |
+
]
|
52 |
+
|
53 |
+
def _info(self):
|
54 |
+
return datasets.DatasetInfo(
|
55 |
+
description="",
|
56 |
+
features=self.config.features,
|
57 |
+
supervised_keys=None,
|
58 |
+
homepage="",
|
59 |
+
citation="",
|
60 |
+
task_templates=None,
|
61 |
+
)
|
62 |
+
|
63 |
+
def _preprocess_metadata_csv(self, csv_file):
|
64 |
+
df = pd.read_csv(csv_file, skiprows=2, sep=', ', engine='python')
|
65 |
+
df.rename(columns={'positive_labels': 'ids'}, inplace=True)
|
66 |
+
df['ids'] = [label.strip('\"').split(',') for label in df['ids']]
|
67 |
+
df['filename'] = (
|
68 |
+
'Y' + df['# YTID'] + '.wav'
|
69 |
+
)
|
70 |
+
return df[['filename', 'ids']]
|
71 |
+
|
72 |
+
def _split_generators(self, dl_manager):
|
73 |
+
"""Returns SplitGenerators."""
|
74 |
+
if self.config.name == 'balanced':
|
75 |
+
archive_path = dl_manager.extract(_BALANCED_TRAIN_FILENAME)
|
76 |
+
elif self.config.name == 'unbalanced':
|
77 |
+
archive_path = dl_manager.extract(_UNBALANCED_TRAIN_FILENAME)
|
78 |
+
test_archive_path = dl_manager.extract(_EVAL_FILENAME)
|
79 |
+
|
80 |
+
return [
|
81 |
+
datasets.SplitGenerator(
|
82 |
+
name=datasets.Split.TRAIN, gen_kwargs={"archive_path": archive_path, "split": "train"}
|
83 |
+
),
|
84 |
+
datasets.SplitGenerator(
|
85 |
+
name=datasets.Split.TEST, gen_kwargs={"archive_path": test_archive_path, "split": "test"}
|
86 |
+
),
|
87 |
+
]
|
88 |
+
|
89 |
+
def _generate_examples(self, archive_path, split=None):
|
90 |
+
extensions = ['.wav']
|
91 |
+
|
92 |
+
test_metadata_csv = 'metadata/eval_segments.csv'
|
93 |
+
if self.config.name == 'balanced':
|
94 |
+
train_metadata_csv = 'metadata/balanced_train_segments.csv'
|
95 |
+
elif self.config.name == 'unbalanced':
|
96 |
+
train_metadata_csv = 'metadata/unbalanced_train_segments.csv'
|
97 |
+
train_metadata_df = self._preprocess_metadata_csv(train_metadata_csv) # ['filename', 'ids']
|
98 |
+
test_metadata_df = self._preprocess_metadata_csv(test_metadata_csv) # ['filename', 'ids']
|
99 |
+
|
100 |
+
class_labels_indices_df = pd.read_csv(
|
101 |
+
'metadata/class_labels_indices.csv'
|
102 |
+
) # ['index', 'mid', 'display_name']
|
103 |
+
mid2label = {
|
104 |
+
row['mid']:row['display_name'] for idx, row in class_labels_indices_df.iterrows()
|
105 |
+
}
|
106 |
+
|
107 |
+
def default_find_classes(audio_path):
|
108 |
+
fileid = Path(audio_path).name
|
109 |
+
ids = metadata_df.query(f'filename=="{fileid}"')['ids'].values.tolist()
|
110 |
+
ids = [
|
111 |
+
mid2label.get(mid, None) for mid in flatten(ids)
|
112 |
+
]
|
113 |
+
return ids
|
114 |
+
|
115 |
+
_walker = fast_scandir(archive_path, extensions, recursive=True)
|
116 |
+
|
117 |
+
for guid, audio_path in enumerate(_walker):
|
118 |
+
yield guid, {
|
119 |
+
"id": str(guid),
|
120 |
+
"file": audio_path,
|
121 |
+
"audio": audio_path,
|
122 |
+
"label": default_find_classes(audio_path),
|
123 |
+
}
|
124 |
+
|
125 |
+
|
126 |
+
def flatten(list2d):
|
127 |
+
return list(itertools.chain.from_iterable(list2d))
|
128 |
+
|
129 |
+
|
130 |
+
def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False):
|
131 |
+
# Scan files recursively faster than glob
|
132 |
+
# From github.com/drscotthawley/aeiou/blob/main/aeiou/core.py
|
133 |
+
subfolders, files = [], []
|
134 |
+
|
135 |
+
try: # hope to avoid 'permission denied' by this try
|
136 |
+
for f in os.scandir(path):
|
137 |
+
try: # 'hope to avoid too many levels of symbolic links' error
|
138 |
+
if f.is_dir():
|
139 |
+
subfolders.append(f.path)
|
140 |
+
elif f.is_file():
|
141 |
+
if os.path.splitext(f.name)[1].lower() in exts:
|
142 |
+
files.append(f.path)
|
143 |
+
except Exception:
|
144 |
+
pass
|
145 |
+
except Exception:
|
146 |
+
pass
|
147 |
+
|
148 |
+
if recursive:
|
149 |
+
for path in list(subfolders):
|
150 |
+
sf, f = fast_scandir(path, exts, recursive=recursive)
|
151 |
+
subfolders.extend(sf)
|
152 |
+
files.extend(f) # type: ignore
|
153 |
+
|
154 |
+
return subfolders, files
|