Spaces:
Runtime error
Runtime error
bofenghuang
commited on
Commit
β’
b66d7e7
1
Parent(s):
76e0282
Update layout
Browse files- .gitignore +2 -0
- app.py +1 -1
- requirements.txt +1 -1
- run_demo_layout.py +313 -0
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
*.wav
|
2 |
+
*.mp4
|
app.py
CHANGED
@@ -1 +1 @@
|
|
1 |
-
|
|
|
1 |
+
run_demo_layout.py
|
requirements.txt
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
transformers
|
2 |
torch
|
3 |
# torchaudio
|
4 |
librosa
|
|
|
1 |
+
git+https://github.com/huggingface/transformers.git
|
2 |
torch
|
3 |
# torchaudio
|
4 |
librosa
|
run_demo_layout.py
ADDED
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#! /usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2023 Bofeng Huang
|
4 |
+
|
5 |
+
import datetime
|
6 |
+
import logging
|
7 |
+
import os
|
8 |
+
import re
|
9 |
+
import warnings
|
10 |
+
|
11 |
+
import gradio as gr
|
12 |
+
import librosa
|
13 |
+
|
14 |
+
# import nltk
|
15 |
+
import pandas as pd
|
16 |
+
import psutil
|
17 |
+
import pytube as pt
|
18 |
+
import torch
|
19 |
+
|
20 |
+
# import torchaudio
|
21 |
+
from transformers import pipeline, Wav2Vec2ProcessorWithLM, AutoModelForCTC
|
22 |
+
from transformers.utils.logging import disable_progress_bar
|
23 |
+
|
24 |
+
# nltk.download("punkt")
|
25 |
+
# from nltk.tokenize import sent_tokenize
|
26 |
+
|
27 |
+
warnings.filterwarnings("ignore")
|
28 |
+
disable_progress_bar()
|
29 |
+
|
30 |
+
DEFAULT_MODEL_NAME = "bofenghuang/asr-wav2vec2-ctc-french"
|
31 |
+
SAMPLE_RATE = 16_000
|
32 |
+
|
33 |
+
GEN_KWARGS = {
|
34 |
+
"chunk_length_s": 30,
|
35 |
+
"stride_length_s": 5,
|
36 |
+
}
|
37 |
+
|
38 |
+
logging.basicConfig(
|
39 |
+
format="%(asctime)s [%(levelname)s] [%(name)s] %(message)s",
|
40 |
+
datefmt="%Y-%m-%dT%H:%M:%SZ",
|
41 |
+
)
|
42 |
+
logger = logging.getLogger(__name__)
|
43 |
+
logger.setLevel(logging.DEBUG)
|
44 |
+
|
45 |
+
# device = 0 if torch.cuda.is_available() else "cpu"
|
46 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
47 |
+
logger.info(f"Model will be loaded on device `{device}`")
|
48 |
+
|
49 |
+
cached_models = {}
|
50 |
+
|
51 |
+
|
52 |
+
def _return_yt_html_embed(yt_url):
|
53 |
+
video_id = yt_url.split("?v=")[-1]
|
54 |
+
HTML_str = (
|
55 |
+
f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
|
56 |
+
" </center>"
|
57 |
+
)
|
58 |
+
return HTML_str
|
59 |
+
|
60 |
+
|
61 |
+
def download_audio_from_youtube(yt_url, downloaded_filename="audio.wav"):
|
62 |
+
yt = pt.YouTube(yt_url)
|
63 |
+
stream = yt.streams.filter(only_audio=True)[0]
|
64 |
+
# stream.download(filename="audio.mp3")
|
65 |
+
stream.download(filename=downloaded_filename)
|
66 |
+
return downloaded_filename
|
67 |
+
|
68 |
+
|
69 |
+
def download_video_from_youtube(yt_url, downloaded_filename="video.mp4"):
|
70 |
+
yt = pt.YouTube(yt_url)
|
71 |
+
stream = yt.streams.filter(progressive=True, file_extension="mp4").order_by("resolution").desc().first()
|
72 |
+
stream.download(filename=downloaded_filename)
|
73 |
+
logger.info(f"Download YouTube video from {yt_url}")
|
74 |
+
return downloaded_filename
|
75 |
+
|
76 |
+
|
77 |
+
def _print_memory_info():
|
78 |
+
memory = psutil.virtual_memory()
|
79 |
+
logger.info(
|
80 |
+
f"Memory info - Free: {memory.available / (1024 ** 3):.2f} Gb, used: {memory.percent}%, total: {memory.total / (1024 ** 3):.2f} Gb"
|
81 |
+
)
|
82 |
+
|
83 |
+
|
84 |
+
def _print_cuda_memory_info():
|
85 |
+
used_mem, tot_mem = torch.cuda.mem_get_info()
|
86 |
+
logger.info(
|
87 |
+
f"CUDA memory info - Free: {used_mem / 1024 ** 3:.2f} Gb, used: {(tot_mem - used_mem) / 1024 ** 3:.2f} Gb, total: {tot_mem / 1024 ** 3:.2f} Gb"
|
88 |
+
)
|
89 |
+
|
90 |
+
|
91 |
+
def print_memory_info():
|
92 |
+
_print_memory_info()
|
93 |
+
_print_cuda_memory_info()
|
94 |
+
|
95 |
+
|
96 |
+
def maybe_load_cached_pipeline(model_name):
|
97 |
+
model = cached_models.get(model_name)
|
98 |
+
if model is None:
|
99 |
+
pipe = pipeline(model=model_name, device=device)
|
100 |
+
|
101 |
+
# model = AutoModelForCTC.from_pretrained(model_name).to(device)
|
102 |
+
# processor = Wav2Vec2ProcessorWithLM.from_pretrained(model_name)
|
103 |
+
# pipe = pipeline(
|
104 |
+
# "automatic-speech-recognition",
|
105 |
+
# model=model,
|
106 |
+
# tokenizer=processor.tokenizer,
|
107 |
+
# feature_extractor=processor.feature_extractor,
|
108 |
+
# decoder=processor.decoder,
|
109 |
+
# )
|
110 |
+
|
111 |
+
logger.info(f"`{model_name}` has been loaded on device `{device}`")
|
112 |
+
|
113 |
+
print_memory_info()
|
114 |
+
|
115 |
+
cached_models[model_name] = pipe
|
116 |
+
return model
|
117 |
+
|
118 |
+
|
119 |
+
def process_audio_file(audio_file):
|
120 |
+
# waveform, sample_rate = torchaudio.load(audio_file)
|
121 |
+
# waveform = waveform.squeeze(axis=0) # mono
|
122 |
+
# # resample
|
123 |
+
# if sample_rate != SAMPLE_RATE:
|
124 |
+
# resampler = torchaudio.transforms.Resample(sample_rate, SAMPLE_RATE)
|
125 |
+
# waveform = resampler(waveform)
|
126 |
+
|
127 |
+
waveform, sample_rate = librosa.load(audio_file, mono=True)
|
128 |
+
|
129 |
+
# resample
|
130 |
+
if sample_rate != SAMPLE_RATE:
|
131 |
+
waveform = librosa.resample(waveform, orig_sr=sample_rate, target_sr=SAMPLE_RATE)
|
132 |
+
|
133 |
+
return waveform
|
134 |
+
|
135 |
+
|
136 |
+
def infer(model, filename, return_df=False):
|
137 |
+
audio_data = process_audio_file(filename)
|
138 |
+
|
139 |
+
text = model(audio_data, **GEN_KWARGS)["text"]
|
140 |
+
|
141 |
+
if return_df:
|
142 |
+
# return pd.DataFrame({"text": sent_tokenize(text)})
|
143 |
+
return pd.DataFrame({"text": [text]})
|
144 |
+
else:
|
145 |
+
return text
|
146 |
+
|
147 |
+
|
148 |
+
def transcribe(microphone, file_upload, model_name=DEFAULT_MODEL_NAME):
|
149 |
+
warn_output = ""
|
150 |
+
if (microphone is not None) and (file_upload is not None):
|
151 |
+
warn_output = (
|
152 |
+
"WARNING: You've uploaded an audio file and used the microphone. "
|
153 |
+
"The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
|
154 |
+
)
|
155 |
+
|
156 |
+
elif (microphone is None) and (file_upload is None):
|
157 |
+
return "ERROR: You have to either use the microphone or upload an audio file"
|
158 |
+
|
159 |
+
file = microphone if microphone is not None else file_upload
|
160 |
+
|
161 |
+
model = maybe_load_cached_pipeline(model_name)
|
162 |
+
text = infer(model, file, return_df=True)
|
163 |
+
|
164 |
+
logger.info(f'Transcription by `{model_name}`:\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
|
165 |
+
|
166 |
+
# return warn_output + text
|
167 |
+
return text
|
168 |
+
|
169 |
+
|
170 |
+
def yt_transcribe(yt_url, model_name=DEFAULT_MODEL_NAME):
|
171 |
+
# html_embed_str = _return_yt_html_embed(yt_url)
|
172 |
+
audio_file_path = download_audio_from_youtube(yt_url)
|
173 |
+
|
174 |
+
model = maybe_load_cached_pipeline(model_name)
|
175 |
+
text = infer(model, audio_file_path, return_df=True)
|
176 |
+
|
177 |
+
logger.info(
|
178 |
+
f'Transcription by `{model_name}` of "{yt_url}":\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n'
|
179 |
+
)
|
180 |
+
|
181 |
+
# return html_embed_str, text
|
182 |
+
return text
|
183 |
+
|
184 |
+
|
185 |
+
def video_transcribe(video_file_path, model_name=DEFAULT_MODEL_NAME):
|
186 |
+
if video_file_path is None:
|
187 |
+
raise ValueError("Failed to transcribe video as no video_file_path has been defined")
|
188 |
+
|
189 |
+
audio_file_path = re.sub(r"\.mp4$", ".wav", video_file_path)
|
190 |
+
os.system(
|
191 |
+
f'ffmpeg -hide_banner -loglevel error -y -i "{video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file_path}"'
|
192 |
+
)
|
193 |
+
|
194 |
+
model = maybe_load_cached_pipeline(model_name)
|
195 |
+
text = infer(model, audio_file_path, return_df=True)
|
196 |
+
|
197 |
+
logger.info(f'Transcription by `{model_name}`:\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
|
198 |
+
|
199 |
+
return text
|
200 |
+
|
201 |
+
|
202 |
+
# load default model
|
203 |
+
maybe_load_cached_pipeline(DEFAULT_MODEL_NAME)
|
204 |
+
|
205 |
+
# default_text_output_df = pd.DataFrame(columns=["start", "end", "text"])
|
206 |
+
default_text_output_df = pd.DataFrame(columns=["text"])
|
207 |
+
|
208 |
+
with gr.Blocks() as demo:
|
209 |
+
with gr.Tab("Transcribe Audio"):
|
210 |
+
gr.Markdown(
|
211 |
+
f"""
|
212 |
+
<div>
|
213 |
+
<h1 style='text-align: center'>Speech-to-Text in French: Transcribe Audio</h1>
|
214 |
+
</div>
|
215 |
+
Transcribe long-form microphone or audio inputs!
|
216 |
+
|
217 |
+
Demo uses the fine-tuned wav2vec2 model <a href='https://huggingface.co/{DEFAULT_MODEL_NAME}' target='_blank'><b>{DEFAULT_MODEL_NAME}</b></a> and π€ Transformers to transcribe audio files of arbitrary length.
|
218 |
+
|
219 |
+
To achieve improved accuracy and well-punctuated text, please use the [Whisper demo](https://huggingface.co/spaces/bofenghuang/whisper-demo-french).
|
220 |
+
"""
|
221 |
+
)
|
222 |
+
|
223 |
+
microphone_input = gr.inputs.Audio(source="microphone", type="filepath", label="Record", optional=True)
|
224 |
+
upload_input = gr.inputs.Audio(source="upload", type="filepath", label="Upload File", optional=True)
|
225 |
+
# with_timestamps_input = gr.Checkbox(label="With timestamps?")
|
226 |
+
|
227 |
+
microphone_transcribe_btn = gr.Button("Transcribe Audio")
|
228 |
+
|
229 |
+
# gr.Markdown('''
|
230 |
+
# Here you will get generated transcrit.
|
231 |
+
# ''')
|
232 |
+
|
233 |
+
# microphone_text_output = gr.outputs.Textbox(label="Transcription")
|
234 |
+
text_output_df2 = gr.DataFrame(
|
235 |
+
value=default_text_output_df,
|
236 |
+
label="Transcription",
|
237 |
+
row_count=(0, "dynamic"),
|
238 |
+
max_rows=10,
|
239 |
+
wrap=True,
|
240 |
+
overflow_row_behaviour="paginate",
|
241 |
+
)
|
242 |
+
|
243 |
+
microphone_transcribe_btn.click(transcribe, inputs=[microphone_input, upload_input], outputs=text_output_df2)
|
244 |
+
|
245 |
+
# with gr.Tab("Transcribe YouTube"):
|
246 |
+
# gr.Markdown(
|
247 |
+
# f"""
|
248 |
+
# <div>
|
249 |
+
# <h1 style='text-align: center'>Speech-to-Text in French: Transcribe YouTube</h1>
|
250 |
+
# </div>
|
251 |
+
# Transcribe long-form YouTube videos!
|
252 |
+
|
253 |
+
# Demo uses the fine-tuned checkpoint: <a href='https://huggingface.co/{DEFAULT_MODEL_NAME}' target='_blank'><b>{DEFAULT_MODEL_NAME}</b></a> to transcribe video files of arbitrary length.
|
254 |
+
# """
|
255 |
+
# )
|
256 |
+
|
257 |
+
# yt_link_input2 = gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL")
|
258 |
+
# with_timestamps_input2 = gr.Checkbox(label="With timestamps?", value=True)
|
259 |
+
|
260 |
+
# yt_transcribe_btn = gr.Button("Transcribe YouTube")
|
261 |
+
|
262 |
+
# # yt_text_output = gr.outputs.Textbox(label="Transcription")
|
263 |
+
# text_output_df3 = gr.DataFrame(
|
264 |
+
# value=default_text_output_df,
|
265 |
+
# label="Transcription",
|
266 |
+
# row_count=(0, "dynamic"),
|
267 |
+
# max_rows=10,
|
268 |
+
# wrap=True,
|
269 |
+
# overflow_row_behaviour="paginate",
|
270 |
+
# )
|
271 |
+
# # yt_html_output = gr.outputs.HTML(label="YouTube Page")
|
272 |
+
|
273 |
+
# yt_transcribe_btn.click(yt_transcribe, inputs=[yt_link_input2, with_timestamps_input2], outputs=[text_output_df3])
|
274 |
+
|
275 |
+
with gr.Tab("Transcribe Video"):
|
276 |
+
gr.Markdown(
|
277 |
+
f"""
|
278 |
+
<div>
|
279 |
+
<h1 style='text-align: center'>Speech-to-Text in French: Transcribe Video</h1>
|
280 |
+
</div>
|
281 |
+
Transcribe long-form YouTube videos or uploaded video inputs!
|
282 |
+
|
283 |
+
Demo uses the fine-tuned wav2vec2 model <a href='https://huggingface.co/{DEFAULT_MODEL_NAME}' target='_blank'><b>{DEFAULT_MODEL_NAME}</b></a> and π€ Transformers to transcribe audio files of arbitrary length.
|
284 |
+
|
285 |
+
To achieve improved accuracy and well-punctuated text, please use the [Whisper demo](https://huggingface.co/spaces/bofenghuang/whisper-demo-french).
|
286 |
+
"""
|
287 |
+
)
|
288 |
+
|
289 |
+
yt_link_input = gr.inputs.Textbox(
|
290 |
+
lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"
|
291 |
+
)
|
292 |
+
download_youtube_btn = gr.Button("Download Youtube video")
|
293 |
+
downloaded_video_output = gr.Video(label="Video file", mirror_webcam=False)
|
294 |
+
download_youtube_btn.click(
|
295 |
+
download_video_from_youtube, inputs=[yt_link_input], outputs=[downloaded_video_output]
|
296 |
+
)
|
297 |
+
|
298 |
+
# with_timestamps_input3 = gr.Checkbox(label="With timestamps?", value=True)
|
299 |
+
video_transcribe_btn = gr.Button("Transcribe video")
|
300 |
+
text_output_df = gr.DataFrame(
|
301 |
+
value=default_text_output_df,
|
302 |
+
label="Transcription",
|
303 |
+
row_count=(0, "dynamic"),
|
304 |
+
max_rows=10,
|
305 |
+
wrap=True,
|
306 |
+
overflow_row_behaviour="paginate",
|
307 |
+
)
|
308 |
+
|
309 |
+
video_transcribe_btn.click(video_transcribe, inputs=[downloaded_video_output], outputs=[text_output_df])
|
310 |
+
|
311 |
+
demo.launch(server_name="0.0.0.0", debug=True)
|
312 |
+
# demo.launch(server_name="0.0.0.0", debug=True, share=True)
|
313 |
+
# demo.launch(enable_queue=True)
|