jp1924 commited on
Commit
9e5e474
1 Parent(s): 5dca98d

Delete AudioCaps.py

Browse files
Files changed (1) hide show
  1. AudioCaps.py +0 -205
AudioCaps.py DELETED
@@ -1,205 +0,0 @@
1
- # MIT License
2
-
3
- # Copyright (c) 2019 AudioCaps authors
4
-
5
- # Permission is hereby granted, free of charge, to any person obtaining a copy
6
- # of this software and associated documentation files (the "Software"), to deal
7
- # in the Software without restriction, including without limitation the rights
8
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- # copies of the Software, and to permit persons to whom the Software is
10
- # furnished to do so, subject to the following conditions:
11
-
12
- # The above copyright notice and this permission notice shall be included in all
13
- # copies or substantial portions of the Software.
14
-
15
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- # SOFTWARE.
22
-
23
-
24
- import datasets
25
- from pathlib import Path
26
- import pandas as pd
27
- import os
28
- from typing import Optional, List
29
- from multiprocessing import Lock, Process
30
- from tqdm import tqdm
31
-
32
- try:
33
- import yt_dlp
34
- except ImportError:
35
- raise ImportError("this code must need yt-dlp package, please run `pip install yt-dlp`")
36
-
37
-
38
- _CITATION = """\
39
- @inproceedings{audiocaps,
40
- title={AudioCaps: Generating Captions for Audios in The Wild},
41
- author={Kim, Chris Dongjoo and Kim, Byeongchang and Lee, Hyunmin and Kim, Gunhee},
42
- booktitle={NAACL-HLT},
43
- year={2019}
44
- }
45
- """
46
-
47
- _DESCRIPTION = """\
48
- We explore audio captioning: generating natural language description for any kind of audio in the wild. We contribute AudioCaps, a large-scale dataset of about 46K audio clips to human-written text pairs collected via crowdsourcing on the AudioSet dataset. The collected captions of AudioCaps are indeed faithful for audio inputs. We provide the source code of the models to explore what forms of audio representation and captioning models are effective for the audio captioning.
49
- """
50
-
51
- _HOMEPAGE = "https://github.com/cdjkim/audiocaps"
52
-
53
- _LICENSE = "MIT License"
54
-
55
-
56
- _URL = "https://raw.githubusercontent.com/cdjkim/audiocaps/master/dataset/"
57
- _URLs = {
58
- "train": _URL + "train.csv",
59
- "valid": _URL + "val.csv",
60
- "test": _URL + "test.csv",
61
- }
62
-
63
- YT_URL = "https://www.youtube.com/watch?v="
64
- DURATION = os.getenv("AUDIOCAPS_DURATION", 10)
65
-
66
-
67
- # TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
68
- class AudioCaps(datasets.GeneratorBasedBuilder):
69
- """Korean Naver movie review dataset."""
70
-
71
- VERSION = datasets.Version("1.0.0")
72
-
73
- def _info(self):
74
- return datasets.DatasetInfo(
75
- description=_DESCRIPTION,
76
- features=datasets.Features(
77
- {
78
- "audiocap_id": datasets.Value("int32"),
79
- "youtube_id": datasets.Value("string"),
80
- "start_time": datasets.Value("int32"),
81
- "audio": datasets.Audio(48000),
82
- "caption": datasets.Value("string"),
83
- }
84
- ),
85
- supervised_keys=None,
86
- homepage=_HOMEPAGE,
87
- license=_LICENSE,
88
- citation=_CITATION,
89
- )
90
-
91
- def _split_generators(self, dl_manager):
92
- downloaded_files = dl_manager.download_and_extract(_URLs)
93
- num_workers = os.getenv("AUDIOCAPS_NUM_WORKER", 4)
94
-
95
- for split, filepath in downloaded_files.items():
96
- download_dir = Path(filepath).parent
97
- save_dir = download_dir.joinpath("AudioCaps", split)
98
-
99
- df = pd.read_csv(filepath)
100
-
101
- df_chunks = self.df_to_n_chunks(df, num_workers)
102
- ps_ls = list()
103
- for i in range(num_workers):
104
- process = Process(
105
- target=self.yt_dlp_processor,
106
- args=(df_chunks[i], save_dir, i),
107
- )
108
- process.start()
109
- ps_ls.append(process)
110
-
111
- try:
112
- for ps in ps_ls:
113
- ps.join()
114
- except KeyboardInterrupt:
115
- for ps in ps_ls:
116
- ps.terminate()
117
- ps.join()
118
-
119
- return [
120
- datasets.SplitGenerator(
121
- name=datasets.Split.TRAIN,
122
- gen_kwargs={
123
- "filepath": downloaded_files["train"],
124
- "split": "train",
125
- },
126
- ),
127
- datasets.SplitGenerator(
128
- name=datasets.Split.VALIDATION,
129
- gen_kwargs={
130
- "filepath": downloaded_files["valid"],
131
- "split": "valid",
132
- },
133
- ),
134
- datasets.SplitGenerator(
135
- name=datasets.Split.TEST,
136
- gen_kwargs={
137
- "filepath": downloaded_files["test"],
138
- "split": "test",
139
- },
140
- ),
141
- ]
142
-
143
- # copied from https://github.com/prompteus/audio-captioning/blob/main/audiocap/download_audiocaps.py
144
- def yt_dlp_processor(
145
- self,
146
- df: pd.DataFrame,
147
- audios_dir: Path,
148
- pid: Optional[int] = 0,
149
- ):
150
- """
151
- download yt videos specified in df, can be used in a multiprocess manner,
152
- just specify lock parameter, so logging goes safe
153
- """
154
- print(f"### Download process number {pid} started")
155
- for row in tqdm(list(df.iterrows()), desc=f"dw_ps: {pid}"):
156
- wav_file = audios_dir.joinpath(f"""{row[1]["youtube_id"]}.wav""")
157
- if wav_file.exists():
158
- continue
159
-
160
- youtube_id = row[1]["youtube_id"]
161
- start_time = row[1]["start_time"]
162
- end_time = start_time + DURATION
163
-
164
- dw_url = f"{YT_URL}{youtube_id}"
165
-
166
- # Download full video of whatever format
167
- audio_name = os.path.join(audios_dir, f"{youtube_id}")
168
- os.system(
169
- f"""yt-dlp -S "asr:48000" -x --quiet --audio-format wav --external-downloader aria2c --external-downloader-args 'ffmpeg_i:-ss {start_time} -to {end_time}' -o '{audio_name}.%(ext)s' {dw_url}"""
170
- )
171
-
172
- def df_to_n_chunks(self, df: pd.DataFrame, n: int) -> List[pd.DataFrame]:
173
- chunk_size = len(df) // n + 1
174
- dfs = []
175
- for i in range(n):
176
- new_df = df.iloc[i * chunk_size : (i + 1) * chunk_size]
177
- dfs.append(new_df)
178
- return dfs
179
-
180
- def _generate_examples(self, filepath, split):
181
- rm_flag = os.getenv("AUDIOCAPS_RM_AUDIO_FILE", False)
182
- save_flag = os.getenv("AUDIOCAPS_SAVE_TO_BYTE", False)
183
-
184
- df = pd.read_csv(filepath)
185
- download_dir = Path(filepath).parent
186
- save_dir = download_dir.joinpath("AudioCaps", split)
187
-
188
- for id_, row in df.iterrows():
189
- wav_file = save_dir.joinpath(f"""{row["youtube_id"]}.wav""")
190
- if not wav_file.exists():
191
- continue
192
- audio = wav_file.read_bytes() if save_flag else str(wav_file)
193
- if rm_flag:
194
- # rm file
195
- os.remove(wav_file)
196
- yield id_, {
197
- "audiocap_id": row["audiocap_id"],
198
- "youtube_id": row["youtube_id"],
199
- "start_time": row["start_time"],
200
- "audio": audio,
201
- "caption": row["caption"],
202
- }
203
- if rm_flag:
204
- # rm dir
205
- os.remove(save_dir)