yangwang825 commited on
Commit
37adfc4
·
verified ·
1 Parent(s): 3b4cc8b

Create irmas.py

Browse files
Files changed (1) hide show
  1. irmas.py +157 -0
irmas.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ """IRMAS dataset."""
4
+
5
+ import os
6
+ import re
7
+ import textwrap
8
+ import datasets
9
+ import itertools
10
+ import typing as tp
11
+ from pathlib import Path
12
+
13
+ SAMPLE_RATE = 44_100
14
+
15
+ _IRMAS_TRAIN_SET_URL = 'https://zenodo.org/record/1290750/files/IRMAS-TrainingData.zip'
16
+ _IRMAS_TEST_SET_PART1_URL = 'https://zenodo.org/record/1290750/files/IRMAS-TestingData-Part1.zip'
17
+ _IRMAS_TEST_SET_PART2_URL = 'https://zenodo.org/record/1290750/files/IRMAS-TestingData-Part2.zip'
18
+ _IRMAS_TEST_SET_PART3_URL = 'https://zenodo.org/record/1290750/files/IRMAS-TestingData-Part3.zip'
19
+
20
+
21
+ INSTRUMENTS = [
22
+ 'cel', 'cla', 'flu', 'gac', 'gel', 'org', 'pia', 'sax', 'tru', 'vio', 'voi'
23
+ ]
24
+
25
+
26
+ class IRMASConfig(datasets.BuilderConfig):
27
+ """BuilderConfig for IRMAS."""
28
+
29
+ def __init__(self, features, **kwargs):
30
+ super(IRMASConfig, self).__init__(version=datasets.Version("0.0.1", ""), **kwargs)
31
+ self.features = features
32
+
33
+
34
+ class IRMAS(datasets.GeneratorBasedBuilder):
35
+
36
+ BUILDER_CONFIGS = [
37
+ IRMASConfig(
38
+ features=datasets.Features(
39
+ {
40
+ "file": datasets.Value("string"),
41
+ "audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
42
+ "instrument": datasets.Sequence(datasets.Value("string")),
43
+ "label": datasets.Sequence(datasets.ClassLabel(names=INSTRUMENTS)),
44
+ }
45
+ ),
46
+ name="irmas",
47
+ description=textwrap.dedent(
48
+ """\
49
+ IRMAS is intended to be used for training and testing methods for the automatic recognition of predominant instruments in musical audio.
50
+ The instruments considered are: cello, clarinet, flute, acoustic guitar, electric guitar, organ, piano, saxophone, trumpet, violin, and human singing voice.
51
+ """
52
+ ),
53
+ ),
54
+ ]
55
+
56
+ def _info(self):
57
+ return datasets.DatasetInfo(
58
+ description="",
59
+ features=self.config.features,
60
+ supervised_keys=None,
61
+ homepage="https://zenodo.org/records/1290750",
62
+ citation="""
63
+ @inproceedings{bosch2012comparison,
64
+ title={A Comparison of Sound Segregation Techniques for Predominant Instrument Recognition in Musical Audio Signals.},
65
+ author={Bosch, Juan J and Janer, Jordi and Fuhrmann, Ferdinand and Herrera, Perfecto},
66
+ booktitle={ISMIR},
67
+ pages={559--564},
68
+ year={2012}
69
+ }
70
+ """,
71
+ task_templates=None,
72
+ )
73
+
74
+ def _split_generators(self, dl_manager):
75
+ """Returns SplitGenerators."""
76
+ train_archive_path = dl_manager.download_and_extract(_IRMAS_TRAIN_SET_URL)
77
+ test_archive_part1_path = dl_manager.download_and_extract(_IRMAS_TEST_SET_PART1_URL)
78
+ test_archive_part2_path = dl_manager.download_and_extract(_IRMAS_TEST_SET_PART2_URL)
79
+ test_archive_part3_path = dl_manager.download_and_extract(_IRMAS_TEST_SET_PART3_URL)
80
+
81
+ extensions = ['.wav']
82
+ _, _train_walker = fast_scandir(train_archive_path, extensions, recursive=True)
83
+ _test_walker = []
84
+ for part in [test_archive_part1_path, test_archive_part2_path, test_archive_part3_path]:
85
+ _, _walker = fast_scandir(part, extensions, recursive=True)
86
+ _test_walker.extend(_walker)
87
+
88
+ return [
89
+ datasets.SplitGenerator(
90
+ name=datasets.Split.TRAIN, gen_kwargs={"audio_filepaths": _train_walker, "split": "train"}
91
+ ),
92
+ datasets.SplitGenerator(
93
+ name=datasets.Split.TEST, gen_kwargs={"audio_filepaths": _test_walker, "split": "test"}
94
+ ),
95
+ ]
96
+
97
+ def _generate_examples(self, audio_filepaths, split=None):
98
+
99
+ def extract_bracketed_items(filename):
100
+ # Regex pattern to find text inside square brackets
101
+ pattern = r'\[([^\]]+)\]'
102
+ # Find all occurrences of the pattern
103
+ items = re.findall(pattern, filename)
104
+ return items
105
+
106
+ if split == 'train':
107
+ for guid, audio_path in enumerate(audio_filepaths):
108
+ labels = extract_bracketed_items(audio_path)
109
+ labels = [label for label in labels if label in INSTRUMENTS]
110
+ yield guid, {
111
+ "id": str(guid),
112
+ "file": audio_path,
113
+ "audio": audio_path,
114
+ "instrument": labels,
115
+ "label": labels
116
+ }
117
+
118
+ elif split == 'test':
119
+ for guid, audio_path in enumerate(audio_filepaths):
120
+ labels = []
121
+ with open(audio_path.replace('.wav', '.txt'), 'r') as f:
122
+ for line in f:
123
+ labels.append(line.strip())
124
+ yield guid, {
125
+ "id": str(guid),
126
+ "file": audio_path,
127
+ "audio": audio_path,
128
+ "instrument": labels,
129
+ "label": labels
130
+ }
131
+
132
+
133
+ def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False):
134
+ # Scan files recursively faster than glob
135
+ # From github.com/drscotthawley/aeiou/blob/main/aeiou/core.py
136
+ subfolders, files = [], []
137
+
138
+ try: # hope to avoid 'permission denied' by this try
139
+ for f in os.scandir(path):
140
+ try: # 'hope to avoid too many levels of symbolic links' error
141
+ if f.is_dir():
142
+ subfolders.append(f.path)
143
+ elif f.is_file():
144
+ if os.path.splitext(f.name)[1].lower() in exts:
145
+ files.append(f.path)
146
+ except Exception:
147
+ pass
148
+ except Exception:
149
+ pass
150
+
151
+ if recursive:
152
+ for path in list(subfolders):
153
+ sf, f = fast_scandir(path, exts, recursive=recursive)
154
+ subfolders.extend(sf)
155
+ files.extend(f) # type: ignore
156
+
157
+ return subfolders, files