yangwang825 commited on
Commit
e18f7de
·
verified ·
1 Parent(s): 5057ea9

Update audioset.py

Browse files
Files changed (1) hide show
  1. audioset.py +151 -5
audioset.py CHANGED
@@ -5,14 +5,25 @@
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 = 32_000
18
 
@@ -27,6 +38,15 @@ ID2LABEL = json.load(
27
  LABEL2ID = {v:k for k, v in ID2LABEL.items()}
28
  CLASSES = list(set(LABEL2ID.keys()))
29
 
 
 
 
 
 
 
 
 
 
30
 
31
  class AudioSetConfig(datasets.BuilderConfig):
32
  """BuilderConfig for AudioSet."""
@@ -51,6 +71,18 @@ class AudioSet(datasets.GeneratorBasedBuilder):
51
  name="balanced",
52
  description="",
53
  ),
 
 
 
 
 
 
 
 
 
 
 
 
54
  ]
55
 
56
  DEFAULT_CONFIG_NAME = "balanced"
@@ -77,14 +109,34 @@ class AudioSet(datasets.GeneratorBasedBuilder):
77
  def _split_generators(self, dl_manager):
78
  """Returns SplitGenerators."""
79
  if self.config.name == 'balanced':
80
- archive_path = dl_manager.extract(_BALANCED_TRAIN_FILENAME)
81
- elif self.config.name == 'unbalanced':
82
- archive_path = dl_manager.extract(_UNBALANCED_TRAIN_FILENAME)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  test_archive_path = dl_manager.extract(_EVAL_FILENAME)
84
 
85
  return [
86
  datasets.SplitGenerator(
87
- name=datasets.Split.TRAIN, gen_kwargs={"archive_path": archive_path, "split": "train"}
88
  ),
89
  datasets.SplitGenerator(
90
  name=datasets.Split.TEST, gen_kwargs={"archive_path": test_archive_path, "split": "test"}
@@ -159,4 +211,98 @@ def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False):
159
  subfolders.extend(sf)
160
  files.extend(f) # type: ignore
161
 
162
- return subfolders, files
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  import os
7
  import json
8
+ import gzip
9
+ import shutil
10
+ import pathlib
11
+ import logging
12
  import textwrap
13
  import datasets
14
  import itertools
15
  import typing as tp
16
  import pandas as pd
17
+ import urllib.request
18
  from pathlib import Path
19
+ from copy import deepcopy
20
+ from tqdm.auto import tqdm
21
+ from rich.logging import RichHandler
22
  from huggingface_hub import hf_hub_download
23
 
24
+ logger = logging.getLogger(__name__)
25
+ logger.addHandler(RichHandler())
26
+ logger.setLevel(logging.INFO)
27
 
28
  SAMPLE_RATE = 32_000
29
 
 
38
  LABEL2ID = {v:k for k, v in ID2LABEL.items()}
39
  CLASSES = list(set(LABEL2ID.keys()))
40
 
41
+ # Cache location
42
+ VERSION = "0.0.1"
43
+ DEFAULT_XDG_CACHE_HOME = "~/.cache"
44
+ XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME)
45
+ DEFAULT_HF_CACHE_HOME = os.path.join(XDG_CACHE_HOME, "huggingface")
46
+ HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME))
47
+ DEFAULT_HF_DATASETS_CACHE = os.path.join(HF_CACHE_HOME, "datasets")
48
+ HF_DATASETS_CACHE = Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE))
49
+
50
 
51
  class AudioSetConfig(datasets.BuilderConfig):
52
  """BuilderConfig for AudioSet."""
 
71
  name="balanced",
72
  description="",
73
  ),
74
+ AudioSetConfig(
75
+ features=datasets.Features(
76
+ {
77
+ "file": datasets.Value("string"),
78
+ "audio": datasets.Audio(sampling_rate=SAMPLE_RATE),
79
+ "sound": datasets.Sequence(datasets.Value("string")),
80
+ "label": datasets.Sequence(datasets.features.ClassLabel(names=CLASSES)),
81
+ }
82
+ ),
83
+ name="unbalanced-part00",
84
+ description="",
85
+ ),
86
  ]
87
 
88
  DEFAULT_CONFIG_NAME = "balanced"
 
109
  def _split_generators(self, dl_manager):
110
  """Returns SplitGenerators."""
111
  if self.config.name == 'balanced':
112
+ train_archive_path = dl_manager.extract(_BALANCED_TRAIN_FILENAME)
113
+
114
+ elif self.config.name == 'unbalanced-part00':
115
+ for zip_type in ['zip', 'z01', 'z02']:
116
+ _UNBALANCED_TRAIN_FILENAME = f'unbalanced_train_segments_part00_partial.{zip_type}'
117
+ zip_file_url = f'https://huggingface.co/datasets/confit/audioset/resolve/main/unbalanced/{_UNBALANCED_TRAIN_FILENAME}'
118
+ _save_path = os.path.join(
119
+ HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION, _UNBALANCED_TRAIN_FILENAME
120
+ )
121
+ download_file(zip_file_url, _save_path)
122
+ logger.info(f"`{_UNBALANCED_TRAIN_FILENAME}` is downloaded to {_save_path}")
123
+
124
+ main_zip_filename = 'unbalanced_train_segments_part00_partial.zip'
125
+ concat_zip_filename = 'unbalanced_train_segments_part00_full.zip'
126
+ _input_file = os.path.join(HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION, main_zip_filename)
127
+ _output_file = os.path.join(HF_DATASETS_CACHE, 'confit___audioset/unbalanced', VERSION, concat_zip_filename)
128
+
129
+ if not os.path.exists(_output_file):
130
+ logger.info(f"Reassemble {_output_file} file")
131
+ os.system(f"zip -q -F {_input_file} --out {_output_file}")
132
+ train_archive_path = dl_manager.extract(_output_file)
133
+ logger.info(f"`{concat_zip_filename}` is downloaded to {train_archive_path}")
134
+
135
  test_archive_path = dl_manager.extract(_EVAL_FILENAME)
136
 
137
  return [
138
  datasets.SplitGenerator(
139
+ name=datasets.Split.TRAIN, gen_kwargs={"archive_path": train_archive_path, "split": "train"}
140
  ),
141
  datasets.SplitGenerator(
142
  name=datasets.Split.TEST, gen_kwargs={"archive_path": test_archive_path, "split": "test"}
 
211
  subfolders.extend(sf)
212
  files.extend(f) # type: ignore
213
 
214
+ return subfolders, files
215
+
216
+
217
+ def download_file(
218
+ source,
219
+ dest,
220
+ unpack=False,
221
+ dest_unpack=None,
222
+ replace_existing=False,
223
+ write_permissions=False,
224
+ ):
225
+ """Downloads the file from the given source and saves it in the given
226
+ destination path.
227
+ Arguments
228
+ ---------
229
+ source : path or url
230
+ Path of the source file. If the source is an URL, it downloads it from
231
+ the web.
232
+ dest : path
233
+ Destination path.
234
+ unpack : bool
235
+ If True, it unpacks the data in the dest folder.
236
+ dest_unpack: path
237
+ Path where to store the unpacked dataset
238
+ replace_existing : bool
239
+ If True, replaces the existing files.
240
+ write_permissions: bool
241
+ When set to True, all the files in the dest_unpack directory will be granted write permissions.
242
+ This option is active only when unpack=True.
243
+ """
244
+ class DownloadProgressBar(tqdm):
245
+ """DownloadProgressBar class."""
246
+
247
+ def update_to(self, b=1, bsize=1, tsize=None):
248
+ """Needed to support multigpu training."""
249
+ if tsize is not None:
250
+ self.total = tsize
251
+ self.update(b * bsize - self.n)
252
+
253
+ # Create the destination directory if it doesn't exist
254
+ dest_dir = pathlib.Path(dest).resolve().parent
255
+ dest_dir.mkdir(parents=True, exist_ok=True)
256
+ if "http" not in source:
257
+ shutil.copyfile(source, dest)
258
+
259
+ elif not os.path.isfile(dest) or (
260
+ os.path.isfile(dest) and replace_existing
261
+ ):
262
+ print(f"Downloading {source} to {dest}")
263
+ with DownloadProgressBar(
264
+ unit="B",
265
+ unit_scale=True,
266
+ miniters=1,
267
+ desc=source.split("/")[-1],
268
+ ) as t:
269
+ urllib.request.urlretrieve(
270
+ source, filename=dest, reporthook=t.update_to
271
+ )
272
+ else:
273
+ print(f"{dest} exists. Skipping download")
274
+
275
+ # Unpack if necessary
276
+ if unpack:
277
+ if dest_unpack is None:
278
+ dest_unpack = os.path.dirname(dest)
279
+ print(f"Extracting {dest} to {dest_unpack}")
280
+ # shutil unpack_archive does not work with tar.gz files
281
+ if (
282
+ source.endswith(".tar.gz")
283
+ or source.endswith(".tgz")
284
+ or source.endswith(".gz")
285
+ ):
286
+ out = dest.replace(".gz", "")
287
+ with gzip.open(dest, "rb") as f_in:
288
+ with open(out, "wb") as f_out:
289
+ shutil.copyfileobj(f_in, f_out)
290
+ else:
291
+ shutil.unpack_archive(dest, dest_unpack)
292
+ if write_permissions:
293
+ set_writing_permissions(dest_unpack)
294
+
295
+
296
+ def set_writing_permissions(folder_path):
297
+ """
298
+ This function sets user writing permissions to all the files in the given folder.
299
+ Arguments
300
+ ---------
301
+ folder_path : folder
302
+ Folder whose files will be granted write permissions.
303
+ """
304
+ for root, dirs, files in os.walk(folder_path):
305
+ for file_name in files:
306
+ file_path = os.path.join(root, file_name)
307
+ # Set writing permissions (mode 0o666) to the file
308
+ os.chmod(file_path, 0o666)