ovieyra21 commited on
Commit
7b0dc9d
·
verified ·
1 Parent(s): 6fc3227

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +314 -0
app.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import gradio as gr
4
+ import yt_dlp as youtube_dl
5
+ import numpy as np
6
+ from datasets import Dataset, Audio
7
+ from scipy.io import wavfile
8
+
9
+ from transformers import pipeline
10
+ from transformers.pipelines.audio_utils import ffmpeg_read
11
+
12
+ import tempfile
13
+ import os
14
+ import time
15
+ import demucs.api
16
+
17
+ MODEL_NAME = "openai/whisper-large-v3" # "patrickvonplaten/wav2vec2-large-960h-lv60-self-4-gram" #
18
+ DEMUCS_MODEL_NAME = "htdemucs_ft"
19
+ BATCH_SIZE = 8
20
+ FILE_LIMIT_MB = 1000
21
+ YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
22
+
23
+ device = 0 if torch.cuda.is_available() else "cpu"
24
+
25
+ pipe = pipeline(
26
+ task="automatic-speech-recognition",
27
+ model=MODEL_NAME,
28
+ chunk_length_s=30,
29
+ device=device,
30
+ )
31
+
32
+ separator = demucs.api.Separator(model = DEMUCS_MODEL_NAME, )
33
+
34
+ def separate_vocal(path):
35
+ origin, separated = separator.separate_audio_file(path)
36
+ demucs.api.save_audio(separated["vocals"], path, samplerate=separator.samplerate)
37
+ return path
38
+
39
+
40
+ def transcribe(inputs_path, task, use_demucs, dataset_name, oauth_token: gr.OAuthToken | None, progress=gr.Progress()):
41
+ if inputs_path is None:
42
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
43
+ if dataset_name is None:
44
+ raise gr.Error("No dataset name submitted! Please submit a dataset name. Should be in the format : <user>/<dataset_name> or <org>/<dataset_name>. Also accepts <dataset_name>, which will default to the namespace of the logged-in user.")
45
+
46
+ if oauth_token is None:
47
+ gr.Warning("Make sure to click and login before using this demo.")
48
+ return [["transcripts will appear here"]], ""
49
+
50
+ total_step = 4
51
+ current_step = 0
52
+
53
+ current_step += 1
54
+ progress((current_step, total_step), desc="Transcribe using Whisper.")
55
+
56
+ sampling_rate, inputs = wavfile.read(inputs_path)
57
+
58
+ out = pipe(inputs_path, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
59
+
60
+ text = out["text"]
61
+
62
+ current_step += 1
63
+ progress((current_step, total_step), desc="Merge chunks.")
64
+ chunks = naive_postprocess_whisper_chunks(out["chunks"], inputs, sampling_rate)
65
+
66
+ current_step += 1
67
+ progress((current_step, total_step), desc="Create dataset.")
68
+
69
+
70
+ transcripts = []
71
+ audios = []
72
+ with tempfile.TemporaryDirectory() as tmpdirname:
73
+ for i,chunk in enumerate(progress.tqdm(chunks, desc="Creating dataset (and clean audio if asked for)")):
74
+
75
+ # TODO: make sure 1D or 2D?
76
+ arr = chunk["audio"]
77
+ path = os.path.join(tmpdirname, f"{i}.wav")
78
+ wavfile.write(path, sampling_rate, arr)
79
+
80
+ if use_demucs == "separate-audio":
81
+ # use demucs tp separate vocals
82
+ print(f"Separating vocals #{i}")
83
+ path = separate_vocal(path)
84
+
85
+ audios.append(path)
86
+ transcripts.append(chunk["text"])
87
+
88
+ dataset = Dataset.from_dict({"audio": audios, "text": transcripts}).cast_column("audio", Audio())
89
+
90
+ current_step += 1
91
+ progress((current_step, total_step), desc="Push dataset.")
92
+ dataset.push_to_hub(dataset_name, token=oauth_token.token if oauth_token else oauth_token)
93
+
94
+ return [[transcript] for transcript in transcripts], text
95
+
96
+
97
+ def _return_yt_html_embed(yt_url):
98
+ video_id = yt_url.split("?v=")[-1]
99
+ HTML_str = (
100
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
101
+ " </center>"
102
+ )
103
+ return HTML_str
104
+
105
+ def download_yt_audio(yt_url, filename):
106
+ info_loader = youtube_dl.YoutubeDL()
107
+
108
+ try:
109
+ info = info_loader.extract_info(yt_url, download=False)
110
+ except youtube_dl.utils.DownloadError as err:
111
+ raise gr.Error(str(err))
112
+
113
+ file_length = info["duration_string"]
114
+ file_h_m_s = file_length.split(":")
115
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
116
+
117
+ if len(file_h_m_s) == 1:
118
+ file_h_m_s.insert(0, 0)
119
+ if len(file_h_m_s) == 2:
120
+ file_h_m_s.insert(0, 0)
121
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
122
+
123
+ if file_length_s > YT_LENGTH_LIMIT_S:
124
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
125
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
126
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
127
+
128
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
129
+
130
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
131
+ try:
132
+ ydl.download([yt_url])
133
+ except youtube_dl.utils.ExtractorError as err:
134
+ raise gr.Error(str(err))
135
+
136
+
137
+ def yt_transcribe(yt_url, task, use_demucs, dataset_name, oauth_token: gr.OAuthToken | None, max_filesize=75.0, dataset_sampling_rate = 24000,
138
+ progress=gr.Progress()):
139
+
140
+ if yt_url is None:
141
+ raise gr.Error("No youtube link submitted! Please put a working link.")
142
+ if dataset_name is None:
143
+ raise gr.Error("No dataset name submitted! Please submit a dataset name. Should be in the format : <user>/<dataset_name> or <org>/<dataset_name>. Also accepts <dataset_name>, which will default to the namespace of the logged-in user.")
144
+
145
+ total_step = 5
146
+ current_step = 0
147
+
148
+ html_embed_str = _return_yt_html_embed(yt_url)
149
+
150
+ if oauth_token is None:
151
+ gr.Warning("Make sure to click and login before using this demo.")
152
+ return html_embed_str, [["transcripts will appear here"]], ""
153
+
154
+ current_step += 1
155
+ progress((current_step, total_step), desc="Load video.")
156
+
157
+ with tempfile.TemporaryDirectory() as tmpdirname:
158
+ filepath = os.path.join(tmpdirname, "video.mp4")
159
+
160
+ download_yt_audio(yt_url, filepath)
161
+ with open(filepath, "rb") as f:
162
+ inputs_path = f.read()
163
+
164
+ inputs = ffmpeg_read(inputs_path, pipe.feature_extractor.sampling_rate)
165
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
166
+
167
+ current_step += 1
168
+ progress((current_step, total_step), desc="Transcribe using Whisper.")
169
+ out = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
170
+
171
+ text = out["text"]
172
+
173
+ inputs = ffmpeg_read(inputs_path, dataset_sampling_rate)
174
+
175
+ current_step += 1
176
+ progress((current_step, total_step), desc="Merge chunks.")
177
+ chunks = naive_postprocess_whisper_chunks(out["chunks"], inputs, dataset_sampling_rate)
178
+
179
+ current_step += 1
180
+ progress((current_step, total_step), desc="Create dataset.")
181
+
182
+ transcripts = []
183
+ audios = []
184
+ with tempfile.TemporaryDirectory() as tmpdirname:
185
+ for i,chunk in enumerate(progress.tqdm(chunks, desc="Creating dataset (and clean audio if asked for).")):
186
+
187
+ # TODO: make sure 1D or 2D?
188
+ arr = chunk["audio"]
189
+ path = os.path.join(tmpdirname, f"{i}.wav")
190
+ wavfile.write(path, dataset_sampling_rate, arr)
191
+
192
+ if use_demucs == "separate-audio":
193
+ # use demucs tp separate vocals
194
+ print(f"Separating vocals #{i}")
195
+ path = separate_vocal(path)
196
+
197
+ audios.append(path)
198
+ transcripts.append(chunk["text"])
199
+
200
+ dataset = Dataset.from_dict({"audio": audios, "text": transcripts}).cast_column("audio", Audio())
201
+
202
+ current_step += 1
203
+ progress((current_step, total_step), desc="Push dataset.")
204
+ dataset.push_to_hub(dataset_name, token=oauth_token.token if oauth_token else oauth_token)
205
+
206
+
207
+ return html_embed_str, [[transcript] for transcript in transcripts], text
208
+
209
+
210
+ def naive_postprocess_whisper_chunks(chunks, audio_array, sampling_rate, stop_chars = ".!:;?", min_duration = 5):
211
+ # merge chunks as long as merged audio duration is lower than min_duration and that a stop character is not met
212
+ # return list of dictionnaries (text, audio)
213
+ # min duration is in seconds
214
+ min_duration = int(min_duration * sampling_rate)
215
+
216
+
217
+ new_chunks = []
218
+ while chunks:
219
+ current_chunk = chunks.pop(0)
220
+
221
+ begin, end = current_chunk["timestamp"]
222
+ begin, end = int(begin*sampling_rate), int(end*sampling_rate)
223
+
224
+ current_dur = end-begin
225
+
226
+ text = current_chunk["text"]
227
+
228
+
229
+ chunk_to_concat = [audio_array[begin:end]]
230
+ while chunks and (text[-1] not in stop_chars or (current_dur<min_duration)):
231
+ ch = chunks.pop(0)
232
+ begin, end = ch["timestamp"]
233
+ begin, end = int(begin*sampling_rate), int(end*sampling_rate)
234
+ current_dur += end-begin
235
+
236
+ text = "".join([text, ch["text"]])
237
+
238
+ # TODO: add silence ?
239
+ chunk_to_concat.append(audio_array[begin:end])
240
+
241
+
242
+ new_chunks.append({
243
+ "text": text.strip(),
244
+ "audio": np.concatenate(chunk_to_concat),
245
+ })
246
+ print(f"LENGTH CHUNK #{len(new_chunks)}: {current_dur/sampling_rate}s")
247
+
248
+ return new_chunks
249
+
250
+
251
+
252
+ css = """
253
+ #intro{
254
+ max-width: 100%;
255
+ text-align: center;
256
+ margin: 0 auto;
257
+ }
258
+ """
259
+ with gr.Blocks(css=css) as demo:
260
+ with gr.Row():
261
+ gr.LoginButton()
262
+ gr.LogoutButton()
263
+
264
+ with gr.Tab("YouTube"):
265
+ gr.Markdown("Create your own TTS dataset using Youtube", elem_id="intro")
266
+ gr.Markdown(
267
+ "This demo allows use to create a text-to-speech dataset from an input audio snippet and push it to hub to keep track of it."
268
+ f"Demo uses the checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to automatically transcribe audio files"
269
+ " of arbitrary length. It then merge chunks of audio and push it to the hub."
270
+ )
271
+ with gr.Row():
272
+ with gr.Column():
273
+ audio_youtube = gr.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL")
274
+ task_youtube = gr.Radio(["transcribe", "translate"], label="Task", value="transcribe")
275
+ cleaning_youtube = gr.Radio(["no-post-processing", "separate-audio"], label="Audio separation and cleaning (takes longer - use it if your samples are not cleaned (background noise and music))", value="separate-audio")
276
+ textbox_youtube = gr.Textbox(lines=1, placeholder="Place your new dataset name here. Should be in the format : <user>/<dataset_name> or <org>/<dataset_name>. Also accepts <dataset_name>, which will default to the namespace of the logged-in user.", label="Dataset name")
277
+
278
+ with gr.Row():
279
+ clear_youtube = gr.ClearButton([audio_youtube, task_youtube, cleaning_youtube, textbox_youtube])
280
+ submit_youtube = gr.Button("Submit")
281
+
282
+ with gr.Column():
283
+ html_youtube = gr.HTML()
284
+ dataset_youtube = gr.Dataset(label="Transcribed samples.",components=["text"], headers=["Transcripts"], samples=[["transcripts will appear here"]])
285
+ transcript_youtube = gr.Textbox(label="Transcription")
286
+
287
+ with gr.Tab("Microphone or Audio file"):
288
+ gr.Markdown("Create your own TTS dataset using your own recordings", elem_id="intro")
289
+ gr.Markdown(
290
+ "This demo allows use to create a text-to-speech dataset from an input audio snippet and push it to hub to keep track of it."
291
+ f"Demo uses the checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to automatically transcribe audio files"
292
+ " of arbitrary length. It then merge chunks of audio and push it to the hub."
293
+ )
294
+ with gr.Row():
295
+ with gr.Column():
296
+ audio_file = gr.Audio(type="filepath")
297
+ task_file = gr.Radio(["transcribe", "translate"], label="Task", value="transcribe")
298
+ cleaning_file = gr.Radio(["no-post-processing", "separate-audio"], label="Audio separation and cleaning (takes longer - use it if your samples are not cleaned (background noise and music))", value="separate-audio")
299
+ textbox_file = gr.Textbox(lines=1, placeholder="Place your new dataset name here. Should be in the format : <user>/<dataset_name> or <org>/<dataset_name>. Also accepts <dataset_name>, which will default to the namespace of the logged-in user.", label="Dataset name")
300
+
301
+ with gr.Row():
302
+ clear_file = gr.ClearButton([audio_file, task_file, cleaning_file, textbox_file])
303
+ submit_file = gr.Button("Submit")
304
+
305
+ with gr.Column():
306
+ dataset_file = gr.Dataset(label="Transcribed samples.", components=["text"], headers=["Transcripts"], samples=[["transcripts will appear here"]])
307
+ transcript_file = gr.Textbox(label="Transcription")
308
+
309
+
310
+
311
+ submit_file.click(transcribe, inputs=[audio_file, task_file, cleaning_file, textbox_file], outputs=[dataset_file, transcript_file])
312
+ submit_youtube.click(yt_transcribe, inputs=[audio_youtube, task_youtube, cleaning_youtube, textbox_youtube], outputs=[html_youtube, dataset_youtube, transcript_youtube])
313
+
314
+ demo.launch(debug=True)