File size: 9,647 Bytes
07c047e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09c9937
07c047e
 
 
 
 
a3bf1a0
 
 
 
e191dc7
a3bf1a0
e191dc7
07c047e
09c9937
07c047e
 
 
 
 
 
 
a3bf1a0
 
 
 
e191dc7
a3bf1a0
e191dc7
07c047e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
599088a
 
07c047e
599088a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07c047e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# coding=utf-8

"""DCASE2018 Task3 Bird Audio Detection dataset."""


import os
import gzip
import shutil
import pathlib
import logging
import datasets
import typing as tp
import pandas as pd
import urllib.request
from pathlib import Path
from copy import deepcopy
from tqdm.auto import tqdm
from rich.logging import RichHandler

logger = logging.getLogger(__name__)
logger.addHandler(RichHandler())
logger.setLevel(logging.INFO)

VERSION = "0.0.1"

SAMPLE_RATE = 44_100

# Cache location
DEFAULT_XDG_CACHE_HOME = "~/.cache"
XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME)
DEFAULT_HF_CACHE_HOME = os.path.join(XDG_CACHE_HOME, "huggingface")
HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME))
DEFAULT_HF_DATASETS_CACHE = os.path.join(HF_CACHE_HOME, "datasets")
HF_DATASETS_CACHE = Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE))


class DCASE2018Task3KConfig(datasets.BuilderConfig):
    """BuilderConfig for DCASE2018 Task3."""
    
    def __init__(self, features, **kwargs):
        super(DCASE2018Task3KConfig, self).__init__(version=datasets.Version(VERSION, ""), **kwargs)
        self.features = features


class DCASE2018Task3(datasets.GeneratorBasedBuilder):

    BUILDER_CONFIGS = [
        DCASE2018Task3KConfig(
            features=datasets.Features(
                {
                    "file": datasets.Value("string"),
                    "audio": datasets.Audio(sampling_rate=None),
                    "label": datasets.features.ClassLabel(names=['absence', 'presence']), 
                }
            ),
            name="hidaka2022investigation", 
            description="",
        ), 
    ]

    DEFAULT_CONFIG_NAME = "hidaka2022investigation"

    def _info(self):
        return datasets.DatasetInfo(
            description="",
            features=self.config.features,
            supervised_keys=None,
            homepage="https://dcase.community/challenge2018/task-bird-audio-detection",
            citation="",
            task_templates=None,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        extensions = ['.wav']
        
        # Development sets
        train_audio_paths = []
        for _filename in ['ff1010bird_wav.zip', 'BirdVox-DCASE-20k.zip']:
            DEV_URL = f'https://huggingface.co/datasets/confit/dcase2018-task3/resolve/main/{_filename}'
            _dev_save_path = os.path.join(
                HF_DATASETS_CACHE, 'confit___dcase2018-task3/hidaka2022investigation', VERSION
            )
            download_file(
                source=DEV_URL, 
                dest=os.path.join(_dev_save_path, _filename), 
                unpack=True, 
                dest_unpack=os.path.join(_dev_save_path, 'extracted', _filename.split('.zip')[0]), 
            )
            train_archive_path = os.path.join(_dev_save_path, 'extracted', _filename.split('.zip')[0])
            _, _walker = fast_scandir(train_archive_path, extensions, recursive=True)
            train_audio_paths.extend(_walker)

        # Evaluation set
        EVAL_URL = 'https://huggingface.co/datasets/confit/dcase2018-task3/resolve/main/warblrb10k_public_wav.zip'
        _eval_save_path = os.path.join(
            HF_DATASETS_CACHE, 'confit___dcase2018-task3/hidaka2022investigation', VERSION
        )
        _filename = 'warblrb10k_public_wav.zip'
        download_file(
            source=EVAL_URL, 
            dest=os.path.join(_eval_save_path, _filename), 
            unpack=True, 
            dest_unpack=os.path.join(_eval_save_path, 'extracted', 'warblrb10k_public_wav'), 
        )
        test_archive_path = os.path.join(_eval_save_path, 'extracted', 'warblrb10k_public_wav')
        _, test_audio_paths = fast_scandir(test_archive_path, extensions, recursive=True)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN, gen_kwargs={"audio_paths": train_audio_paths, "split": "train"}
            ), 
            datasets.SplitGenerator(
                name=datasets.Split.TEST, gen_kwargs={"audio_paths": test_audio_paths, "split": "test"}
            ), 
        ]

    def _generate_examples(self, audio_paths, split=None):
        if split == 'train':
            _df1 = pd.read_csv('https://huggingface.co/datasets/confit/dcase2018-task3/raw/main/BirdVoxDCASE20k_csvpublic.csv')
            _df2 = pd.read_csv('https://huggingface.co/datasets/confit/dcase2018-task3/raw/main/ff1010bird_metadata_2018.csv')
            metadata_df = pd.concat([_df1, _df2]).reset_index(drop=True)
        elif split == 'test':
            metadata_df = pd.read_csv('https://huggingface.co/datasets/confit/dcase2018-task3/raw/main/warblrb10k_public_metadata_2018.csv')

        fileid2class = {}
        for idx, row in metadata_df.iterrows():
            has_bird = row['hasbird']
            if int(has_bird) == 1:
                label = 'presence'
            elif int(has_bird) == 0:
                label = 'absence'
            fileid2class[f"{row['itemid']}.wav"] = label # this filename doesn't have suffix

        for guid, audio_path in enumerate(audio_paths):
            fileid = Path(audio_path).name
            label = fileid2class.get(fileid)
            yield guid, {
                "id": str(guid),
                "file": audio_path, 
                "audio": audio_path, 
                "label": label, 
            }


def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False):
    # Scan files recursively faster than glob
    # From github.com/drscotthawley/aeiou/blob/main/aeiou/core.py
    subfolders, files = [], []

    try:  # hope to avoid 'permission denied' by this try
        for f in os.scandir(path):
            try:  # 'hope to avoid too many levels of symbolic links' error
                if f.is_dir():
                    subfolders.append(f.path)
                elif f.is_file():
                    if os.path.splitext(f.name)[1].lower() in exts:
                        files.append(f.path)
            except Exception:
                pass
    except Exception:
        pass

    if recursive:
        for path in list(subfolders):
            sf, f = fast_scandir(path, exts, recursive=recursive)
            subfolders.extend(sf)
            files.extend(f)  # type: ignore

    return subfolders, files


def download_file(
    source,
    dest,
    unpack=False,
    dest_unpack=None,
    replace_existing=False,
    write_permissions=False,
):
    """Downloads the file from the given source and saves it in the given
    destination path.
     Arguments
    ---------
    source : path or url
        Path of the source file. If the source is an URL, it downloads it from
        the web.
    dest : path
        Destination path.
    unpack : bool
        If True, it unpacks the data in the dest folder.
    dest_unpack: path
        Path where to store the unpacked dataset
    replace_existing : bool
        If True, replaces the existing files.
    write_permissions: bool
        When set to True, all the files in the dest_unpack directory will be granted write permissions.
        This option is active only when unpack=True.
    """
    class DownloadProgressBar(tqdm):
        """DownloadProgressBar class."""

        def update_to(self, b=1, bsize=1, tsize=None):
            """Needed to support multigpu training."""
            if tsize is not None:
                self.total = tsize
            self.update(b * bsize - self.n)

    # Create the destination directory if it doesn't exist
    dest_dir = pathlib.Path(dest).resolve().parent
    dest_dir.mkdir(parents=True, exist_ok=True)
    if "http" not in source:
        shutil.copyfile(source, dest)

    elif not os.path.isfile(dest) or (
        os.path.isfile(dest) and replace_existing
    ):
        logger.info(f"Downloading {source} to {dest}")
        with DownloadProgressBar(
            unit="B",
            unit_scale=True,
            miniters=1,
            desc=source.split("/")[-1],
        ) as t:
            urllib.request.urlretrieve(
                source, filename=dest, reporthook=t.update_to
            )
    else:
        logger.info(f"{dest} exists. Skipping download")

    # Unpack if necessary
    if unpack:
        if dest_unpack is None:
            dest_unpack = os.path.dirname(dest)
        if os.path.exists(dest_unpack):
            logger.info(f"{dest_unpack} already exists. Skipping extraction")
        else:
            logger.info(f"Extracting {dest} to {dest_unpack}")
            # shutil unpack_archive does not work with tar.gz files
            if (
                source.endswith(".tar.gz")
                or source.endswith(".tgz")
                or source.endswith(".gz")
            ):
                out = dest.replace(".gz", "")
                with gzip.open(dest, "rb") as f_in:
                    with open(out, "wb") as f_out:
                        shutil.copyfileobj(f_in, f_out)
            else:
                shutil.unpack_archive(dest, dest_unpack)
            if write_permissions:
                set_writing_permissions(dest_unpack)


def set_writing_permissions(folder_path):
    """
    This function sets user writing permissions to all the files in the given folder.
    Arguments
    ---------
    folder_path : folder
        Folder whose files will be granted write permissions.
    """
    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            # Set writing permissions (mode 0o666) to the file
            os.chmod(file_path, 0o666)