Update app.py
Browse files
app.py
CHANGED
@@ -1,10 +1,21 @@
|
|
1 |
import torch
|
2 |
import gradio as gr
|
3 |
-
|
|
|
|
|
4 |
from scipy.io import wavfile
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
MODEL_NAME = "openai/whisper-large-
|
|
|
7 |
BATCH_SIZE = 8
|
|
|
|
|
8 |
|
9 |
device = 0 if torch.cuda.is_available() else "cpu"
|
10 |
|
@@ -15,30 +26,217 @@ pipe = pipeline(
|
|
15 |
device=device,
|
16 |
)
|
17 |
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
if inputs_path is None:
|
20 |
raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
|
|
|
|
23 |
out = pipe(inputs_path, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
|
24 |
text = out["text"]
|
25 |
|
26 |
-
|
|
|
|
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
-
demo.launch()
|
|
|
1 |
import torch
|
2 |
import gradio as gr
|
3 |
+
import yt_dlp as youtube_dl
|
4 |
+
import numpy as np
|
5 |
+
from datasets import Dataset, Audio
|
6 |
from scipy.io import wavfile
|
7 |
+
from transformers import pipeline
|
8 |
+
from transformers.pipelines.audio_utils import ffmpeg_read
|
9 |
+
import tempfile
|
10 |
+
import os
|
11 |
+
import time
|
12 |
+
import demucs.api
|
13 |
|
14 |
+
MODEL_NAME = "openai/whisper-large-v2"
|
15 |
+
DEMUCS_MODEL_NAME = "htdemucs_ft"
|
16 |
BATCH_SIZE = 8
|
17 |
+
FILE_LIMIT_MB = 1000
|
18 |
+
YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
|
19 |
|
20 |
device = 0 if torch.cuda.is_available() else "cpu"
|
21 |
|
|
|
26 |
device=device,
|
27 |
)
|
28 |
|
29 |
+
separator = demucs.api.Separator(model=DEMUCS_MODEL_NAME)
|
30 |
+
|
31 |
+
def separate_vocal(path):
|
32 |
+
origin, separated = separator.separate_audio_file(path)
|
33 |
+
demucs.api.save_audio(separated["vocals"], path, samplerate=separator.samplerate)
|
34 |
+
return path
|
35 |
+
|
36 |
+
def transcribe(inputs_path, task, use_demucs, dataset_name, oauth_token, progress=gr.Progress()):
|
37 |
if inputs_path is None:
|
38 |
raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
|
39 |
+
if not dataset_name:
|
40 |
+
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.")
|
41 |
+
if oauth_token is None:
|
42 |
+
raise gr.Error("No OAuth token submitted! Please login to use this demo.")
|
43 |
+
|
44 |
+
total_step = 4
|
45 |
+
current_step = 0
|
46 |
|
47 |
+
current_step += 1
|
48 |
+
progress((current_step, total_step), desc="Transcribe using Whisper.")
|
49 |
+
sampling_rate, inputs = wavfile.read(inputs_path)
|
50 |
out = pipe(inputs_path, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
|
51 |
text = out["text"]
|
52 |
|
53 |
+
current_step += 1
|
54 |
+
progress((current_step, total_step), desc="Merge chunks.")
|
55 |
+
chunks = naive_postprocess_whisper_chunks(out["chunks"], inputs, sampling_rate)
|
56 |
|
57 |
+
current_step += 1
|
58 |
+
progress((current_step, total_step), desc="Create dataset.")
|
59 |
+
transcripts = []
|
60 |
+
audios = []
|
61 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
62 |
+
for i, chunk in enumerate(progress.tqdm(chunks, desc="Creating dataset (and clean audio if asked for)")):
|
63 |
+
arr = chunk["audio"]
|
64 |
+
path = os.path.join(tmpdirname, f"{i}.wav")
|
65 |
+
wavfile.write(path, sampling_rate, arr)
|
66 |
+
|
67 |
+
if use_demucs == "separate-audio":
|
68 |
+
print(f"Separating vocals #{i}")
|
69 |
+
path = separate_vocal(path)
|
70 |
+
|
71 |
+
audios.append(path)
|
72 |
+
transcripts.append(chunk["text"])
|
73 |
+
|
74 |
+
dataset = Dataset.from_dict({"audio": audios, "text": transcripts}).cast_column("audio", Audio())
|
75 |
+
|
76 |
+
current_step += 1
|
77 |
+
progress((current_step, total_step), desc="Push dataset.")
|
78 |
+
dataset.push_to_hub(dataset_name, token=oauth_token.token if oauth_token else oauth_token)
|
79 |
+
|
80 |
+
return [[transcript] for transcript in transcripts], text
|
81 |
+
|
82 |
+
def _return_yt_html_embed(yt_url):
|
83 |
+
video_id = yt_url.split("?v=")[-1]
|
84 |
+
HTML_str = (
|
85 |
+
f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
|
86 |
+
" </center>"
|
87 |
)
|
88 |
+
return HTML_str
|
89 |
+
|
90 |
+
def download_yt_audio(yt_url, filename):
|
91 |
+
info_loader = youtube_dl.YoutubeDL()
|
92 |
+
|
93 |
+
try:
|
94 |
+
info = info_loader.extract_info(yt_url, download=False)
|
95 |
+
except youtube_dl.utils.DownloadError as err:
|
96 |
+
raise gr.Error(str(err))
|
97 |
+
|
98 |
+
file_length = info["duration_string"]
|
99 |
+
file_h_m_s = file_length.split(":")
|
100 |
+
file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
|
101 |
+
|
102 |
+
if len(file_h_m_s) == 1:
|
103 |
+
file_h_m_s.insert(0, 0)
|
104 |
+
if len(file_h_m_s) == 2:
|
105 |
+
file_h_m_s.insert(0, 0)
|
106 |
+
file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
|
107 |
+
|
108 |
+
if file_length_s > YT_LENGTH_LIMIT_S:
|
109 |
+
yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
|
110 |
+
file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
|
111 |
+
raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
|
112 |
+
|
113 |
+
ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
|
114 |
+
|
115 |
+
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
116 |
+
try:
|
117 |
+
ydl.download([yt_url])
|
118 |
+
except youtube_dl.utils.ExtractorError as err:
|
119 |
+
raise gr.Error(str(err))
|
120 |
+
|
121 |
+
def yt_transcribe(yt_url, task, use_demucs, dataset_name, oauth_token, max_filesize=75.0, dataset_sampling_rate=24000, progress=gr.Progress()):
|
122 |
+
if yt_url is None:
|
123 |
+
raise gr.Error("No YouTube link submitted! Please put a working link.")
|
124 |
+
if not dataset_name:
|
125 |
+
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.")
|
126 |
+
if oauth_token is None:
|
127 |
+
raise gr.Error("No OAuth token submitted! Please login to use this demo.")
|
128 |
+
|
129 |
+
total_step = 5
|
130 |
+
current_step = 0
|
131 |
+
|
132 |
+
html_embed_str = _return_yt_html_embed(yt_url)
|
133 |
+
current_step += 1
|
134 |
+
progress((current_step, total_step), desc="Load video.")
|
135 |
+
|
136 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
137 |
+
filepath = os.path.join(tmpdirname, "video.mp4")
|
138 |
+
|
139 |
+
download_yt_audio(yt_url, filepath)
|
140 |
+
inputs = ffmpeg_read(filepath, pipe.feature_extractor.sampling_rate)
|
141 |
+
inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
|
142 |
+
|
143 |
+
current_step += 1
|
144 |
+
progress((current_step, total_step), desc="Transcribe using Whisper.")
|
145 |
+
out = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
|
146 |
+
text = out["text"]
|
147 |
+
|
148 |
+
inputs = ffmpeg_read(filepath, dataset_sampling_rate)
|
149 |
+
|
150 |
+
current_step += 1
|
151 |
+
progress((current_step, total_step), desc="Merge chunks.")
|
152 |
+
chunks = naive_postprocess_whisper_chunks(out["chunks"], inputs, dataset_sampling_rate)
|
153 |
+
|
154 |
+
current_step += 1
|
155 |
+
progress((current_step, total_step), desc="Create dataset.")
|
156 |
+
transcripts = []
|
157 |
+
audios = []
|
158 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
159 |
+
for i, chunk in enumerate(progress.tqdm(chunks, desc="Creating dataset (and clean audio if asked for)")):
|
160 |
+
arr = chunk["audio"]
|
161 |
+
path = os.path.join(tmpdirname, f"{i}.wav")
|
162 |
+
wavfile.write(path, dataset_sampling_rate, arr)
|
163 |
+
|
164 |
+
if use_demucs == "separate-audio":
|
165 |
+
print(f"Separating vocals #{i}")
|
166 |
+
path = separate_vocal(path)
|
167 |
+
|
168 |
+
audios.append(path)
|
169 |
+
transcripts.append(chunk["text"])
|
170 |
+
|
171 |
+
dataset = Dataset.from_dict({"audio": audios, "text": transcripts}).cast_column("audio", Audio())
|
172 |
+
|
173 |
+
current_step += 1
|
174 |
+
progress((current_step, total_step), desc="Push dataset.")
|
175 |
+
dataset.push_to_hub(dataset_name, token=oauth_token.token if oauth_token else oauth_token)
|
176 |
+
|
177 |
+
return html_embed_str, [[transcript] for transcript in transcripts], text
|
178 |
+
|
179 |
+
def naive_postprocess_whisper_chunks(chunks, audio_array, sampling_rate, stop_chars=".!:;?", min_duration=5):
|
180 |
+
min_duration = int(min_duration * sampling_rate)
|
181 |
+
new_chunks = []
|
182 |
+
while chunks:
|
183 |
+
current_chunk = chunks.pop(0)
|
184 |
+
begin, end = current_chunk["timestamp"]
|
185 |
+
begin, end = int(begin * sampling_rate), int(end * sampling_rate)
|
186 |
+
current_dur = end - begin
|
187 |
+
text = current_chunk["text"]
|
188 |
+
chunk_to_concat = [audio_array[begin:end]]
|
189 |
+
while chunks and (text[-1] not in stop_chars or (current_dur < min_duration)):
|
190 |
+
ch = chunks.pop(0)
|
191 |
+
begin, end = ch["timestamp"]
|
192 |
+
begin, end = int(begin * sampling_rate), int(end * sampling_rate)
|
193 |
+
current_dur += end - begin
|
194 |
+
text = "".join([text, ch["text"]])
|
195 |
+
chunk_to_concat.append(audio_array[begin:end])
|
196 |
+
new_chunks.append({
|
197 |
+
"text": text.strip(),
|
198 |
+
"audio": np.concatenate(chunk_to_concat),
|
199 |
+
})
|
200 |
+
return new_chunks
|
201 |
+
|
202 |
+
with gr.Blocks() as demo:
|
203 |
+
with gr.Tab("Local file"):
|
204 |
+
with gr.Row():
|
205 |
+
with gr.Column():
|
206 |
+
local_audio_input = gr.Audio(source="upload", type="filepath", label="Upload Audio")
|
207 |
+
task_input = gr.Dropdown(choices=["transcribe", "translate"], value="transcribe", label="Task")
|
208 |
+
use_demucs_input = gr.Dropdown(choices=["do-nothing", "separate-audio"], value="do-nothing", label="Audio preprocessing")
|
209 |
+
dataset_name_input = gr.Textbox(label="Dataset name")
|
210 |
+
hf_token = gr.Textbox(label="HuggingFace Token")
|
211 |
+
submit_local_button = gr.Button("Transcribe")
|
212 |
+
with gr.Column():
|
213 |
+
local_output_text = gr.Dataframe(label="Transcripts")
|
214 |
+
local_output_full_text = gr.Textbox(label="Full Text")
|
215 |
+
|
216 |
+
submit_local_button.click(
|
217 |
+
transcribe,
|
218 |
+
inputs=[local_audio_input, task_input, use_demucs_input, dataset_name_input, hf_token],
|
219 |
+
outputs=[local_output_text, local_output_full_text],
|
220 |
+
)
|
221 |
+
|
222 |
+
with gr.Tab("YouTube video"):
|
223 |
+
with gr.Row():
|
224 |
+
with gr.Column():
|
225 |
+
yt_url_input = gr.Textbox(label="YouTube URL")
|
226 |
+
yt_task_input = gr.Dropdown(choices=["transcribe", "translate"], value="transcribe", label="Task")
|
227 |
+
yt_use_demucs_input = gr.Dropdown(choices=["do-nothing", "separate-audio"], value="do-nothing", label="Audio preprocessing")
|
228 |
+
yt_dataset_name_input = gr.Textbox(label="Dataset name")
|
229 |
+
yt_hf_token = gr.Textbox(label="HuggingFace Token")
|
230 |
+
submit_yt_button = gr.Button("Transcribe")
|
231 |
+
with gr.Column():
|
232 |
+
yt_html_embed_str = gr.HTML()
|
233 |
+
yt_output_text = gr.Dataframe(label="Transcripts")
|
234 |
+
yt_output_full_text = gr.Textbox(label="Full Text")
|
235 |
+
|
236 |
+
submit_yt_button.click(
|
237 |
+
yt_transcribe,
|
238 |
+
inputs=[yt_url_input, yt_task_input, yt_use_demucs_input, yt_dataset_name_input, yt_hf_token],
|
239 |
+
outputs=[yt_html_embed_str, yt_output_text, yt_output_full_text],
|
240 |
+
)
|
241 |
|
242 |
+
demo.launch(share=True)
|