bofenghuang commited on
Commit
920af5f
1 Parent(s): 96b8638

Update interface

Browse files
Files changed (3) hide show
  1. app.py +1 -1
  2. requirements.txt +6 -2
  3. run_demo_low_api_openai.py +309 -0
app.py CHANGED
@@ -1 +1 @@
1
- run_demo_multi_models.py
 
1
+ run_demo_low_api_openai.py
requirements.txt CHANGED
@@ -1,3 +1,7 @@
1
  git+https://github.com/huggingface/transformers
2
- torch
3
- pytube
 
 
 
 
 
1
  git+https://github.com/huggingface/transformers
2
+ git+https://github.com/openai/whisper.git
3
+ nltk
4
+ pandas
5
+ psutil
6
+ pytube
7
+ torch
run_demo_low_api_openai.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 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 pandas as pd
13
+ import psutil
14
+ import pytube as pt
15
+ import torch
16
+ import whisper
17
+ from huggingface_hub import hf_hub_download, model_info
18
+ from transformers.utils.logging import disable_progress_bar
19
+
20
+ import nltk
21
+ nltk.download("punkt")
22
+
23
+ from nltk.tokenize import sent_tokenize
24
+
25
+ warnings.filterwarnings("ignore")
26
+ disable_progress_bar()
27
+
28
+ DEFAULT_MODEL_NAME = "bofenghuang/whisper-large-v2-cv11-german"
29
+ CHECKPOINT_FILENAME = "checkpoint_openai.pt"
30
+
31
+ GEN_KWARGS = {
32
+ "task": "transcribe",
33
+ "language": "de",
34
+ # "without_timestamps": True,
35
+ # decode options
36
+ # "beam_size": 5,
37
+ # "patience": 2,
38
+ # disable fallback
39
+ # "compression_ratio_threshold": None,
40
+ # "logprob_threshold": None,
41
+ # vad threshold
42
+ # "no_speech_threshold": None,
43
+ }
44
+
45
+ logging.basicConfig(
46
+ format="%(asctime)s [%(levelname)s] [%(name)s] %(message)s",
47
+ datefmt="%Y-%m-%dT%H:%M:%SZ",
48
+ )
49
+ logger = logging.getLogger(__name__)
50
+ logger.setLevel(logging.DEBUG)
51
+
52
+ # device = 0 if torch.cuda.is_available() else "cpu"
53
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
54
+ logger.info(f"Model will be loaded on device `{device}`")
55
+
56
+ cached_models = {}
57
+
58
+
59
+ def format_timestamp(seconds):
60
+ return str(datetime.timedelta(seconds=round(seconds)))
61
+
62
+
63
+ def _return_yt_html_embed(yt_url):
64
+ video_id = yt_url.split("?v=")[-1]
65
+ HTML_str = (
66
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>' " </center>"
67
+ )
68
+ return HTML_str
69
+
70
+
71
+ def download_audio_from_youtube(yt_url, downloaded_filename="audio.wav"):
72
+ yt = pt.YouTube(yt_url)
73
+ stream = yt.streams.filter(only_audio=True)[0]
74
+ # stream.download(filename="audio.mp3")
75
+ stream.download(filename=downloaded_filename)
76
+ return downloaded_filename
77
+
78
+
79
+ def download_video_from_youtube(yt_url, downloaded_filename="video.mp4"):
80
+ yt = pt.YouTube(yt_url)
81
+ stream = yt.streams.filter(progressive=True, file_extension="mp4").order_by("resolution").desc().first()
82
+ stream.download(filename=downloaded_filename)
83
+ logger.info(f"Download YouTube video from {yt_url}")
84
+ return downloaded_filename
85
+
86
+
87
+ def _print_memory_info():
88
+ memory = psutil.virtual_memory()
89
+ logger.info(
90
+ f"Memory info - Free: {memory.available / (1024 ** 3):.2f} Gb, used: {memory.percent}%, total: {memory.total / (1024 ** 3):.2f} Gb"
91
+ )
92
+
93
+
94
+ def _print_cuda_memory_info():
95
+ used_mem, tot_mem = torch.cuda.mem_get_info()
96
+ logger.info(
97
+ 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"
98
+ )
99
+
100
+
101
+ def print_memory_info():
102
+ _print_memory_info()
103
+ _print_cuda_memory_info()
104
+
105
+
106
+ def maybe_load_cached_pipeline(model_name):
107
+ model = cached_models.get(model_name)
108
+ if model is None:
109
+ downloaded_model_path = hf_hub_download(repo_id=model_name, filename=CHECKPOINT_FILENAME)
110
+
111
+ model = whisper.load_model(downloaded_model_path, device=device)
112
+ logger.info(f"`{model_name}` has been loaded on device `{device}`")
113
+
114
+ print_memory_info()
115
+
116
+ cached_models[model_name] = model
117
+ return model
118
+
119
+
120
+ def infer(model, filename, with_timestamps, return_df=False):
121
+ if with_timestamps:
122
+ model_outputs = model.transcribe(filename, **GEN_KWARGS)
123
+ if return_df:
124
+ model_outputs_df = pd.DataFrame(model_outputs["segments"])
125
+ # print(model_outputs)
126
+ # print(model_outputs_df)
127
+ # print(model_outputs_df.info(verbose=True))
128
+ model_outputs_df = model_outputs_df[["start", "end", "text"]]
129
+ model_outputs_df["start"] = model_outputs_df["start"].map(format_timestamp)
130
+ model_outputs_df["end"] = model_outputs_df["end"].map(format_timestamp)
131
+ model_outputs_df["text"] = model_outputs_df["text"].str.strip()
132
+ return model_outputs_df
133
+ else:
134
+ return "\n\n".join(
135
+ [
136
+ f'Segment {segment["id"]+1} from {segment["start"]:.2f}s to {segment["end"]:.2f}s:\n{segment["text"].strip()}'
137
+ for segment in model_outputs["segments"]
138
+ ]
139
+ )
140
+ else:
141
+ text = model.transcribe(filename, without_timestamps=True, **GEN_KWARGS)["text"]
142
+ if return_df:
143
+ return pd.DataFrame({"text": sent_tokenize(text)})
144
+ else:
145
+ return text
146
+
147
+
148
+ def transcribe(microphone, file_upload, with_timestamps, 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 = model.transcribe(file, **GEN_KWARGS)["text"]
163
+ # text = infer(model, file, with_timestamps)
164
+ text = infer(model, file, with_timestamps, return_df=True)
165
+
166
+ logger.info(f'Transcription by `{model_name}`:\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
167
+
168
+ # return warn_output + text
169
+ return text
170
+
171
+
172
+ def yt_transcribe(yt_url, with_timestamps, model_name=DEFAULT_MODEL_NAME):
173
+ # html_embed_str = _return_yt_html_embed(yt_url)
174
+ audio_file_path = download_audio_from_youtube(yt_url)
175
+
176
+ model = maybe_load_cached_pipeline(model_name)
177
+ # text = model.transcribe("audio.mp3", **GEN_KWARGS)["text"]
178
+ # text = infer(model, audio_file_path, with_timestamps)
179
+ text = infer(model, audio_file_path, with_timestamps, return_df=True)
180
+
181
+ logger.info(f'Transcription by `{model_name}` of "{yt_url}":\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
182
+
183
+ # return html_embed_str, text
184
+ return text
185
+
186
+
187
+ def video_transcribe(video_file_path, with_timestamps, model_name=DEFAULT_MODEL_NAME):
188
+ if video_file_path is None:
189
+ raise ValueError("Failed to transcribe video as no video_file_path has been defined")
190
+
191
+ audio_file_path = re.sub(r"\.mp4$", ".wav", video_file_path)
192
+ os.system(f'ffmpeg -i "{video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file_path}"')
193
+
194
+ model = maybe_load_cached_pipeline(model_name)
195
+ # text = model.transcribe("audio.mp3", **GEN_KWARGS)["text"]
196
+ text = infer(model, audio_file_path, with_timestamps, return_df=True)
197
+
198
+ logger.info(f'Transcription by `{model_name}`:\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
199
+
200
+ return text
201
+
202
+
203
+ # load default model
204
+ maybe_load_cached_pipeline(DEFAULT_MODEL_NAME)
205
+
206
+ # default_text_output_df = pd.DataFrame(columns=["start", "end", "text"])
207
+ default_text_output_df = pd.DataFrame(columns=["text"])
208
+
209
+ with gr.Blocks() as demo:
210
+
211
+ with gr.Tab("Transcribe Audio"):
212
+ gr.Markdown(
213
+ f"""
214
+ <div>
215
+ <h1 style='text-align: center'>Whisper German Demo 🇩🇪 : Transcribe Audio</h1>
216
+ </div>
217
+ Transcribe long-form microphone or audio inputs!
218
+
219
+ Demo uses the fine-tuned checkpoint: <a href='https://huggingface.co/{DEFAULT_MODEL_NAME}' target='_blank'><b>{DEFAULT_MODEL_NAME}</b></a> to transcribe audio files of arbitrary length.
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(
244
+ transcribe, inputs=[microphone_input, upload_input, with_timestamps_input], outputs=text_output_df2
245
+ )
246
+
247
+ # with gr.Tab("Transcribe YouTube"):
248
+ # gr.Markdown(
249
+ # f"""
250
+ # <div>
251
+ # <h1 style='text-align: center'>Whisper German Demo 🇩🇪 : Transcribe YouTube</h1>
252
+ # </div>
253
+ # Transcribe long-form YouTube videos!
254
+
255
+ # 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.
256
+ # """
257
+ # )
258
+
259
+ # yt_link_input2 = gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL")
260
+ # with_timestamps_input2 = gr.Checkbox(label="With timestamps?", value=True)
261
+
262
+ # yt_transcribe_btn = gr.Button("Transcribe YouTube")
263
+
264
+ # # yt_text_output = gr.outputs.Textbox(label="Transcription")
265
+ # text_output_df3 = gr.DataFrame(
266
+ # value=default_text_output_df,
267
+ # label="Transcription",
268
+ # row_count=(0, "dynamic"),
269
+ # max_rows=10,
270
+ # wrap=True,
271
+ # overflow_row_behaviour="paginate",
272
+ # )
273
+ # # yt_html_output = gr.outputs.HTML(label="YouTube Page")
274
+
275
+ # yt_transcribe_btn.click(yt_transcribe, inputs=[yt_link_input2, with_timestamps_input2], outputs=[text_output_df3])
276
+
277
+ with gr.Tab("Transcribe Video"):
278
+ gr.Markdown(
279
+ f"""
280
+ <div>
281
+ <h1 style='text-align: center'>Whisper German Demo 🇩🇪 : Transcribe Video</h1>
282
+ </div>
283
+ Transcribe long-form YouTube videos or uploaded video inputs!
284
+
285
+ 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.
286
+ """
287
+ )
288
+
289
+ yt_link_input = gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL")
290
+ download_youtube_btn = gr.Button("Download Youtube video")
291
+ downloaded_video_output = gr.Video(label="Video file", mirror_webcam=False)
292
+ download_youtube_btn.click(download_video_from_youtube, inputs=[yt_link_input], outputs=[downloaded_video_output])
293
+
294
+ with_timestamps_input3 = gr.Checkbox(label="With timestamps?", value=True)
295
+ video_transcribe_btn = gr.Button("Transcribe video")
296
+ text_output_df = gr.DataFrame(
297
+ value=default_text_output_df,
298
+ label="Transcription",
299
+ row_count=(0, "dynamic"),
300
+ max_rows=10,
301
+ wrap=True,
302
+ overflow_row_behaviour="paginate",
303
+ )
304
+
305
+ video_transcribe_btn.click(video_transcribe, inputs=[downloaded_video_output, with_timestamps_input3], outputs=[text_output_df])
306
+
307
+ # demo.launch(server_name="0.0.0.0", debug=True)
308
+ # demo.launch(server_name="0.0.0.0", debug=True, share=True)
309
+ demo.launch(enable_queue=True)