bofenghuang commited on
Commit
2eface4
β€’
1 Parent(s): 8ac5039

Use ct2 for inference

Browse files
app.py CHANGED
@@ -1 +1 @@
1
- run_demo_low_api_openai.py
 
1
+ run_demo_ct2.py
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
- git+https://github.com/huggingface/transformers
2
  git+https://github.com/openai/whisper.git
 
3
  nltk
4
  pandas
5
  psutil
 
1
+ git+https://github.com/huggingface/transformers.git
2
  git+https://github.com/openai/whisper.git
3
+ git+https://github.com/guillaumekln/faster-whisper.git
4
  nltk
5
  pandas
6
  psutil
run_demo_ct2.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 faster_whisper import WhisperModel
18
+ from huggingface_hub import hf_hub_download, snapshot_download
19
+ from transformers.utils.logging import disable_progress_bar
20
+
21
+ import nltk
22
+ nltk.download("punkt")
23
+
24
+ from nltk.tokenize import sent_tokenize
25
+
26
+ warnings.filterwarnings("ignore")
27
+ disable_progress_bar()
28
+
29
+ # DEFAULT_MODEL_NAME = "bofenghuang/whisper-large-v2-cv11-french"
30
+ DEFAULT_MODEL_NAME = "bofenghuang/whisper-large-v2-cv11-french-ct2"
31
+ # CHECKPOINT_FILENAME = "checkpoint_openai.pt"
32
+
33
+ GEN_KWARGS = {
34
+ "task": "transcribe",
35
+ "language": "fr",
36
+ # "without_timestamps": True,
37
+ # decode options
38
+ # "beam_size": 5,
39
+ # "patience": 2,
40
+ # disable fallback
41
+ # "compression_ratio_threshold": None,
42
+ # "logprob_threshold": None,
43
+ # vad threshold
44
+ # "no_speech_threshold": None,
45
+ }
46
+
47
+ logging.basicConfig(
48
+ format="%(asctime)s [%(levelname)s] [%(name)s] %(message)s",
49
+ datefmt="%Y-%m-%dT%H:%M:%SZ",
50
+ )
51
+ logger = logging.getLogger(__name__)
52
+ logger.setLevel(logging.DEBUG)
53
+
54
+ # device = 0 if torch.cuda.is_available() else "cpu"
55
+ # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
56
+ device = "cuda" if torch.cuda.is_available() else "cpu"
57
+ logger.info(f"Model will be loaded on device `{device}`")
58
+
59
+ cached_models = {}
60
+
61
+
62
+ def format_timestamp(seconds):
63
+ return str(datetime.timedelta(seconds=round(seconds)))
64
+
65
+
66
+ def _return_yt_html_embed(yt_url):
67
+ video_id = yt_url.split("?v=")[-1]
68
+ HTML_str = (
69
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>' " </center>"
70
+ )
71
+ return HTML_str
72
+
73
+
74
+ def download_audio_from_youtube(yt_url, downloaded_filename="audio.wav"):
75
+ yt = pt.YouTube(yt_url)
76
+ stream = yt.streams.filter(only_audio=True)[0]
77
+ # stream.download(filename="audio.mp3")
78
+ stream.download(filename=downloaded_filename)
79
+ return downloaded_filename
80
+
81
+
82
+ def download_video_from_youtube(yt_url, downloaded_filename="video.mp4"):
83
+ yt = pt.YouTube(yt_url)
84
+ stream = yt.streams.filter(progressive=True, file_extension="mp4").order_by("resolution").desc().first()
85
+ stream.download(filename=downloaded_filename)
86
+ logger.info(f"Download YouTube video from {yt_url}")
87
+ return downloaded_filename
88
+
89
+
90
+ def _print_memory_info():
91
+ memory = psutil.virtual_memory()
92
+ logger.info(
93
+ f"Memory info - Free: {memory.available / (1024 ** 3):.2f} Gb, used: {memory.percent}%, total: {memory.total / (1024 ** 3):.2f} Gb"
94
+ )
95
+
96
+
97
+ def _print_cuda_memory_info():
98
+ used_mem, tot_mem = torch.cuda.mem_get_info()
99
+ logger.info(
100
+ 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"
101
+ )
102
+
103
+
104
+ def print_memory_info():
105
+ _print_memory_info()
106
+ _print_cuda_memory_info()
107
+
108
+
109
+ def maybe_load_cached_pipeline(model_name):
110
+ model = cached_models.get(model_name)
111
+ if model is None:
112
+ # downloaded_model_path = hf_hub_download(repo_id=model_name, filename=CHECKPOINT_FILENAME)
113
+ downloaded_model_path = snapshot_download(repo_id=model_name)
114
+
115
+ # model = whisper.load_model(downloaded_model_path, device=device)
116
+ model = WhisperModel(downloaded_model_path, device=device, compute_type="float16")
117
+ logger.info(f"`{model_name}` has been loaded on device `{device}`")
118
+
119
+ print_memory_info()
120
+
121
+ cached_models[model_name] = model
122
+ return model
123
+
124
+
125
+ def infer(model, filename, with_timestamps, return_df=False):
126
+ if with_timestamps:
127
+ # model_outputs = model.transcribe(filename, **GEN_KWARGS)
128
+ model_outputs, _ = model.transcribe(filename, **GEN_KWARGS)
129
+ model_outputs = [segment._asdict() for segment in model_outputs]
130
+ if return_df:
131
+ # model_outputs_df = pd.DataFrame(model_outputs["segments"])
132
+ model_outputs_df = pd.DataFrame(model_outputs)
133
+ # print(model_outputs)
134
+ # print(model_outputs_df)
135
+ # print(model_outputs_df.info(verbose=True))
136
+ model_outputs_df = model_outputs_df[["start", "end", "text"]]
137
+ model_outputs_df["start"] = model_outputs_df["start"].map(format_timestamp)
138
+ model_outputs_df["end"] = model_outputs_df["end"].map(format_timestamp)
139
+ model_outputs_df["text"] = model_outputs_df["text"].str.strip()
140
+ return model_outputs_df
141
+ else:
142
+ return "\n\n".join(
143
+ [
144
+ f'Segment {segment["id"]+1} from {segment["start"]:.2f}s to {segment["end"]:.2f}s:\n{segment["text"].strip()}'
145
+ # for segment in model_outputs["segments"]
146
+ for segment in model_outputs
147
+ ]
148
+ )
149
+ else:
150
+ # text = model.transcribe(filename, without_timestamps=True, **GEN_KWARGS)["text"]
151
+ model_outputs, _ = model.transcribe(filename, without_timestamps=True, **GEN_KWARGS)
152
+ model_outputs = list(model_outputs)
153
+ text = model_outputs[0].text
154
+ if return_df:
155
+ return pd.DataFrame({"text": sent_tokenize(text)})
156
+ else:
157
+ return text
158
+
159
+
160
+ def transcribe(microphone, file_upload, with_timestamps, model_name=DEFAULT_MODEL_NAME):
161
+ warn_output = ""
162
+ if (microphone is not None) and (file_upload is not None):
163
+ warn_output = (
164
+ "WARNING: You've uploaded an audio file and used the microphone. "
165
+ "The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
166
+ )
167
+
168
+ elif (microphone is None) and (file_upload is None):
169
+ return "ERROR: You have to either use the microphone or upload an audio file"
170
+
171
+ file = microphone if microphone is not None else file_upload
172
+
173
+ model = maybe_load_cached_pipeline(model_name)
174
+ # text = model.transcribe(file, **GEN_KWARGS)["text"]
175
+ # text = infer(model, file, with_timestamps)
176
+ text = infer(model, file, with_timestamps, return_df=True)
177
+
178
+ logger.info(f'Transcription by `{model_name}`:\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
179
+
180
+ # return warn_output + text
181
+ return text
182
+
183
+
184
+ def yt_transcribe(yt_url, with_timestamps, model_name=DEFAULT_MODEL_NAME):
185
+ # html_embed_str = _return_yt_html_embed(yt_url)
186
+ audio_file_path = download_audio_from_youtube(yt_url)
187
+
188
+ model = maybe_load_cached_pipeline(model_name)
189
+ # text = model.transcribe("audio.mp3", **GEN_KWARGS)["text"]
190
+ # text = infer(model, audio_file_path, with_timestamps)
191
+ text = infer(model, audio_file_path, with_timestamps, return_df=True)
192
+
193
+ logger.info(f'Transcription by `{model_name}` of "{yt_url}":\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
194
+
195
+ # return html_embed_str, text
196
+ return text
197
+
198
+
199
+ def video_transcribe(video_file_path, with_timestamps, model_name=DEFAULT_MODEL_NAME):
200
+ if video_file_path is None:
201
+ raise ValueError("Failed to transcribe video as no video_file_path has been defined")
202
+
203
+ audio_file_path = re.sub(r"\.mp4$", ".wav", video_file_path)
204
+ os.system(f'ffmpeg -i "{video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file_path}"')
205
+
206
+ model = maybe_load_cached_pipeline(model_name)
207
+ # text = model.transcribe("audio.mp3", **GEN_KWARGS)["text"]
208
+ text = infer(model, audio_file_path, with_timestamps, return_df=True)
209
+
210
+ logger.info(f'Transcription by `{model_name}`:\n{text.to_json(orient="index", force_ascii=False, indent=2)}\n')
211
+
212
+ return text
213
+
214
+
215
+ # load default model
216
+ maybe_load_cached_pipeline(DEFAULT_MODEL_NAME)
217
+
218
+ # default_text_output_df = pd.DataFrame(columns=["start", "end", "text"])
219
+ default_text_output_df = pd.DataFrame(columns=["text"])
220
+
221
+ with gr.Blocks() as demo:
222
+
223
+ with gr.Tab("Transcribe Audio"):
224
+ gr.Markdown(
225
+ f"""
226
+ <div>
227
+ <h1 style='text-align: center'>Whisper French Demo: Transcribe Audio</h1>
228
+ </div>
229
+ Transcribe long-form microphone or audio inputs!
230
+
231
+ 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.
232
+
233
+ Efficient inference is supported by [faster-whisper](https://github.com/guillaumekln/faster-whisper) and [CTranslate2](https://github.com/OpenNMT/CTranslate2).
234
+ """
235
+ )
236
+
237
+ microphone_input = gr.inputs.Audio(source="microphone", type="filepath", label="Record", optional=True)
238
+ upload_input = gr.inputs.Audio(source="upload", type="filepath", label="Upload File", optional=True)
239
+ with_timestamps_input = gr.Checkbox(label="With timestamps?")
240
+
241
+ microphone_transcribe_btn = gr.Button("Transcribe Audio")
242
+
243
+ # gr.Markdown('''
244
+ # Here you will get generated transcrit.
245
+ # ''')
246
+
247
+ # microphone_text_output = gr.outputs.Textbox(label="Transcription")
248
+ text_output_df2 = gr.DataFrame(
249
+ value=default_text_output_df,
250
+ label="Transcription",
251
+ row_count=(0, "dynamic"),
252
+ max_rows=10,
253
+ wrap=True,
254
+ overflow_row_behaviour="paginate",
255
+ )
256
+
257
+ microphone_transcribe_btn.click(
258
+ transcribe, inputs=[microphone_input, upload_input, with_timestamps_input], outputs=text_output_df2
259
+ )
260
+
261
+ # with gr.Tab("Transcribe YouTube"):
262
+ # gr.Markdown(
263
+ # f"""
264
+ # <div>
265
+ # <h1 style='text-align: center'>Whisper French Demo: Transcribe YouTube</h1>
266
+ # </div>
267
+ # Transcribe long-form YouTube videos!
268
+
269
+ # 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.
270
+ # """
271
+ # )
272
+
273
+ # yt_link_input2 = gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL")
274
+ # with_timestamps_input2 = gr.Checkbox(label="With timestamps?", value=True)
275
+
276
+ # yt_transcribe_btn = gr.Button("Transcribe YouTube")
277
+
278
+ # # yt_text_output = gr.outputs.Textbox(label="Transcription")
279
+ # text_output_df3 = gr.DataFrame(
280
+ # value=default_text_output_df,
281
+ # label="Transcription",
282
+ # row_count=(0, "dynamic"),
283
+ # max_rows=10,
284
+ # wrap=True,
285
+ # overflow_row_behaviour="paginate",
286
+ # )
287
+ # # yt_html_output = gr.outputs.HTML(label="YouTube Page")
288
+
289
+ # yt_transcribe_btn.click(yt_transcribe, inputs=[yt_link_input2, with_timestamps_input2], outputs=[text_output_df3])
290
+
291
+ with gr.Tab("Transcribe Video"):
292
+ gr.Markdown(
293
+ f"""
294
+ <div>
295
+ <h1 style='text-align: center'>Whisper French Demo: Transcribe Video</h1>
296
+ </div>
297
+ Transcribe long-form YouTube videos or uploaded video inputs!
298
+
299
+ 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.
300
+
301
+ Efficient inference is supported by [faster-whisper](https://github.com/guillaumekln/faster-whisper) and [CTranslate2](https://github.com/OpenNMT/CTranslate2).
302
+ """
303
+ )
304
+
305
+ yt_link_input = gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL")
306
+ download_youtube_btn = gr.Button("Download Youtube video")
307
+ downloaded_video_output = gr.Video(label="Video file", mirror_webcam=False)
308
+ download_youtube_btn.click(download_video_from_youtube, inputs=[yt_link_input], outputs=[downloaded_video_output])
309
+
310
+ with_timestamps_input3 = gr.Checkbox(label="With timestamps?", value=True)
311
+ video_transcribe_btn = gr.Button("Transcribe video")
312
+ text_output_df = gr.DataFrame(
313
+ value=default_text_output_df,
314
+ label="Transcription",
315
+ row_count=(0, "dynamic"),
316
+ max_rows=10,
317
+ wrap=True,
318
+ overflow_row_behaviour="paginate",
319
+ )
320
+
321
+ video_transcribe_btn.click(video_transcribe, inputs=[downloaded_video_output, with_timestamps_input3], outputs=[text_output_df])
322
+
323
+ # demo.launch(server_name="0.0.0.0", debug=True)
324
+ # demo.launch(server_name="0.0.0.0", debug=True, share=True)
325
+ demo.launch(enable_queue=True)
run_demo.py β†’ run_demo_hf.py RENAMED
File without changes
run_demo_multi_models.py β†’ run_demo_hf_multiple_models.py RENAMED
File without changes
run_demo_low_api_openai.py β†’ run_demo_openai_layout.py RENAMED
@@ -212,7 +212,7 @@ with gr.Blocks() as demo:
212
  gr.Markdown(
213
  f"""
214
  <div>
215
- <h1 style='text-align: center'>Whisper French Demo πŸ‡«πŸ‡· : Transcribe Audio</h1>
216
  </div>
217
  Transcribe long-form microphone or audio inputs!
218
 
@@ -248,7 +248,7 @@ with gr.Blocks() as demo:
248
  # gr.Markdown(
249
  # f"""
250
  # <div>
251
- # <h1 style='text-align: center'>Whisper French Demo πŸ‡«πŸ‡· : Transcribe YouTube</h1>
252
  # </div>
253
  # Transcribe long-form YouTube videos!
254
 
@@ -278,7 +278,7 @@ with gr.Blocks() as demo:
278
  gr.Markdown(
279
  f"""
280
  <div>
281
- <h1 style='text-align: center'>Whisper French Demo πŸ‡«πŸ‡· : Transcribe Video</h1>
282
  </div>
283
  Transcribe long-form YouTube videos or uploaded video inputs!
284
 
 
212
  gr.Markdown(
213
  f"""
214
  <div>
215
+ <h1 style='text-align: center'>Whisper French Demo: Transcribe Audio</h1>
216
  </div>
217
  Transcribe long-form microphone or audio inputs!
218
 
 
248
  # gr.Markdown(
249
  # f"""
250
  # <div>
251
+ # <h1 style='text-align: center'>Whisper French Demo: Transcribe YouTube</h1>
252
  # </div>
253
  # Transcribe long-form YouTube videos!
254
 
 
278
  gr.Markdown(
279
  f"""
280
  <div>
281
+ <h1 style='text-align: center'>Whisper French Demo: Transcribe Video</h1>
282
  </div>
283
  Transcribe long-form YouTube videos or uploaded video inputs!
284