yangwang825 commited on
Commit
20e025e
·
1 Parent(s): 905b61d

Create esc50.py

Browse files
Files changed (1) hide show
  1. esc50.py +84 -0
esc50.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import datasets
3
+ import typing as tp
4
+ from pathlib import Path
5
+
6
+ SAMPLE_RATE = 44_100
7
+ EXTENSION = '.wav'
8
+
9
+
10
+ class ESC50(datasets.GeneratorBasedBuilder):
11
+ """
12
+ The ESC50 dataset
13
+ """
14
+ def _info(self):
15
+ return datasets.DatasetInfo(
16
+ description='Environmental sound classification dataset',
17
+ features=datasets.Features(
18
+ {
19
+ # "filepath": datasets.Value("string"),
20
+ "audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
21
+ "label": datasets.ClassLabel(names=GENRES),
22
+ }
23
+ ),
24
+ )
25
+
26
+ def _split_generators(self, dl_manager):
27
+ data_dir = dl_manager.download_and_extract("ESC-50-master.zip")
28
+ return [
29
+ datasets.SplitGenerator(
30
+ name=datasets.Split.TRAIN,
31
+ gen_kwargs={
32
+ "data_dir": data_dir,
33
+ "split": 'train'
34
+ },
35
+ ),
36
+ ]
37
+
38
+ def _generate_examples(self, data_dir, split):
39
+ _, _walker = fast_scandir(data_dir, [EXTENSION], recursive=True)
40
+
41
+ for idx, fileid in enumerate(_walker):
42
+ yield idx, {
43
+ # 'filepath': fileid,
44
+ 'audio': fileid,
45
+ 'fold': default_find_fold(fileid),
46
+ 'label': default_find_classes(fileid)
47
+ }
48
+
49
+
50
+ def default_find_classes(audio_path):
51
+ id_ = Path(audio_path).stem.split('-')[-1]
52
+ return ESC50_ID2LABEL.get(int(id_))
53
+
54
+
55
+ def default_find_fold(audio_path):
56
+ fold = Path(audio_path).stem.split('-')[0]
57
+ return int(fold)
58
+
59
+
60
+ def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False):
61
+ # Scan files recursively faster than glob
62
+ # From github.com/drscotthawley/aeiou/blob/main/aeiou/core.py
63
+ subfolders, files = [], []
64
+
65
+ try: # hope to avoid 'permission denied' by this try
66
+ for f in os.scandir(path):
67
+ try: # 'hope to avoid too many levels of symbolic links' error
68
+ if f.is_dir():
69
+ subfolders.append(f.path)
70
+ elif f.is_file():
71
+ if os.path.splitext(f.name)[1].lower() in exts:
72
+ files.append(f.path)
73
+ except Exception:
74
+ pass
75
+ except Exception:
76
+ pass
77
+
78
+ if recursive:
79
+ for path in list(subfolders):
80
+ sf, f = fast_scandir(path, exts, recursive=recursive)
81
+ subfolders.extend(sf)
82
+ files.extend(f) # type: ignore
83
+
84
+ return subfolders, files