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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import math
|
3 |
+
import os
|
4 |
+
import tempfile
|
5 |
+
import time
|
6 |
+
from multiprocessing import Pool
|
7 |
+
|
8 |
+
import gradio as gr
|
9 |
+
import jax.numpy as jnp
|
10 |
+
import numpy as np
|
11 |
+
import yt_dlp as youtube_dl
|
12 |
+
from jax.experimental.compilation_cache import compilation_cache as cc
|
13 |
+
from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
|
14 |
+
from transformers.pipelines.audio_utils import ffmpeg_read
|
15 |
+
|
16 |
+
from whisper_jax import FlaxWhisperPipline
|
17 |
+
|
18 |
+
|
19 |
+
cc.initialize_cache("./jax_cache")
|
20 |
+
checkpoint = "openai/whisper-large-v3"
|
21 |
+
|
22 |
+
BATCH_SIZE = 32
|
23 |
+
CHUNK_LENGTH_S = 30
|
24 |
+
NUM_PROC = 32
|
25 |
+
FILE_LIMIT_MB = 1000
|
26 |
+
YT_LENGTH_LIMIT_S = 7200 # limit to 2 hour YouTube files
|
27 |
+
|
28 |
+
title = "Whisper JAX: The Fastest Whisper API ⚡️"
|
29 |
+
|
30 |
+
description = """Whisper JAX is an optimised implementation of the [Whisper model](https://huggingface.co/openai/whisper-large-v3) by OpenAI. It runs on JAX with a TPU v4-8 in the backend. Compared to PyTorch on an A100 GPU, it is over [**70x faster**](https://github.com/sanchit-gandhi/whisper-jax#benchmarks), making it the fastest Whisper API available.
|
31 |
+
|
32 |
+
Note that at peak times, you may find yourself in the queue for this demo. When you submit a request, your queue position will be shown in the top right-hand side of the demo pane. Once you reach the front of the queue, your audio file will be transcribed, with the progress displayed through a progress bar.
|
33 |
+
|
34 |
+
To skip the queue, you may wish to create your own inference endpoint, details for which can be found in the [Whisper JAX repository](https://github.com/sanchit-gandhi/whisper-jax#creating-an-endpoint).
|
35 |
+
"""
|
36 |
+
|
37 |
+
article = "Whisper large-v3 model by OpenAI. Backend running JAX on a TPU v4-8 through the generous support of the [TRC](https://sites.research.google/trc/about/) programme. Whisper JAX [code](https://github.com/sanchit-gandhi/whisper-jax) and Gradio demo by 🤗 Hugging Face."
|
38 |
+
|
39 |
+
language_names = sorted(TO_LANGUAGE_CODE.keys())
|
40 |
+
|
41 |
+
logger = logging.getLogger("whisper-jax-app")
|
42 |
+
logger.setLevel(logging.INFO)
|
43 |
+
ch = logging.StreamHandler()
|
44 |
+
ch.setLevel(logging.INFO)
|
45 |
+
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s", "%Y-%m-%d %H:%M:%S")
|
46 |
+
ch.setFormatter(formatter)
|
47 |
+
logger.addHandler(ch)
|
48 |
+
|
49 |
+
|
50 |
+
def identity(batch):
|
51 |
+
return batch
|
52 |
+
|
53 |
+
|
54 |
+
# Copied from https://github.com/openai/whisper/blob/c09a7ae299c4c34c5839a76380ae407e7d785914/whisper/utils.py#L50
|
55 |
+
def format_timestamp(seconds: float, always_include_hours: bool = False, decimal_marker: str = "."):
|
56 |
+
if seconds is not None:
|
57 |
+
milliseconds = round(seconds * 1000.0)
|
58 |
+
|
59 |
+
hours = milliseconds // 3_600_000
|
60 |
+
milliseconds -= hours * 3_600_000
|
61 |
+
|
62 |
+
minutes = milliseconds // 60_000
|
63 |
+
milliseconds -= minutes * 60_000
|
64 |
+
|
65 |
+
seconds = milliseconds // 1_000
|
66 |
+
milliseconds -= seconds * 1_000
|
67 |
+
|
68 |
+
hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
|
69 |
+
return f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}"
|
70 |
+
else:
|
71 |
+
# we have a malformed timestamp so just return it as is
|
72 |
+
return seconds
|
73 |
+
|
74 |
+
|
75 |
+
if __name__ == "__main__":
|
76 |
+
pipeline = FlaxWhisperPipline(checkpoint, dtype=jnp.bfloat16, batch_size=BATCH_SIZE)
|
77 |
+
stride_length_s = CHUNK_LENGTH_S / 6
|
78 |
+
chunk_len = round(CHUNK_LENGTH_S * pipeline.feature_extractor.sampling_rate)
|
79 |
+
stride_left = stride_right = round(stride_length_s * pipeline.feature_extractor.sampling_rate)
|
80 |
+
step = chunk_len - stride_left - stride_right
|
81 |
+
pool = Pool(NUM_PROC)
|
82 |
+
|
83 |
+
# do a pre-compile step so that the first user to use the demo isn't hit with a long transcription time
|
84 |
+
logger.info("compiling forward call...")
|
85 |
+
start = time.time()
|
86 |
+
random_inputs = {
|
87 |
+
"input_features": np.ones(
|
88 |
+
(BATCH_SIZE, pipeline.model.config.num_mel_bins, 2 * pipeline.model.config.max_source_positions)
|
89 |
+
)
|
90 |
+
}
|
91 |
+
random_timestamps = pipeline.forward(random_inputs, batch_size=BATCH_SIZE, return_timestamps=True)
|
92 |
+
compile_time = time.time() - start
|
93 |
+
logger.info(f"compiled in {compile_time}s")
|
94 |
+
|
95 |
+
def tqdm_generate(inputs: dict, task: str, return_timestamps: bool, progress: gr.Progress):
|
96 |
+
inputs_len = inputs["array"].shape[0]
|
97 |
+
all_chunk_start_idx = np.arange(0, inputs_len, step)
|
98 |
+
num_samples = len(all_chunk_start_idx)
|
99 |
+
num_batches = math.ceil(num_samples / BATCH_SIZE)
|
100 |
+
dummy_batches = list(
|
101 |
+
range(num_batches)
|
102 |
+
) # Gradio progress bar not compatible with generator, see https://github.com/gradio-app/gradio/issues/3841
|
103 |
+
|
104 |
+
dataloader = pipeline.preprocess_batch(inputs, chunk_length_s=CHUNK_LENGTH_S, batch_size=BATCH_SIZE)
|
105 |
+
progress(0, desc="Pre-processing audio file...")
|
106 |
+
logger.info("pre-processing audio file...")
|
107 |
+
dataloader = pool.map(identity, dataloader)
|
108 |
+
logger.info("done post-processing")
|
109 |
+
|
110 |
+
model_outputs = []
|
111 |
+
start_time = time.time()
|
112 |
+
logger.info("transcribing...")
|
113 |
+
# iterate over our chunked audio samples - always predict timestamps to reduce hallucinations
|
114 |
+
for batch, _ in zip(dataloader, progress.tqdm(dummy_batches, desc="Transcribing...")):
|
115 |
+
model_outputs.append(pipeline.forward(batch, batch_size=BATCH_SIZE, task=task, return_timestamps=True))
|
116 |
+
runtime = time.time() - start_time
|
117 |
+
logger.info("done transcription")
|
118 |
+
|
119 |
+
logger.info("post-processing...")
|
120 |
+
post_processed = pipeline.postprocess(model_outputs, return_timestamps=True)
|
121 |
+
text = post_processed["text"]
|
122 |
+
if return_timestamps:
|
123 |
+
timestamps = post_processed.get("chunks")
|
124 |
+
timestamps = [
|
125 |
+
f"[{format_timestamp(chunk['timestamp'][0])} -> {format_timestamp(chunk['timestamp'][1])}] {chunk['text']}"
|
126 |
+
for chunk in timestamps
|
127 |
+
]
|
128 |
+
text = "\n".join(str(feature) for feature in timestamps)
|
129 |
+
logger.info("done post-processing")
|
130 |
+
return text, runtime
|
131 |
+
|
132 |
+
def transcribe_chunked_audio(inputs, task, return_timestamps, progress=gr.Progress()):
|
133 |
+
progress(0, desc="Loading audio file...")
|
134 |
+
logger.info("loading audio file...")
|
135 |
+
if inputs is None:
|
136 |
+
logger.warning("No audio file")
|
137 |
+
raise gr.Error("No audio file submitted! Please upload an audio file before submitting your request.")
|
138 |
+
file_size_mb = os.stat(inputs).st_size / (1024 * 1024)
|
139 |
+
if file_size_mb > FILE_LIMIT_MB:
|
140 |
+
logger.warning("Max file size exceeded")
|
141 |
+
raise gr.Error(
|
142 |
+
f"File size exceeds file size limit. Got file of size {file_size_mb:.2f}MB for a limit of {FILE_LIMIT_MB}MB."
|
143 |
+
)
|
144 |
+
|
145 |
+
with open(inputs, "rb") as f:
|
146 |
+
inputs = f.read()
|
147 |
+
|
148 |
+
inputs = ffmpeg_read(inputs, pipeline.feature_extractor.sampling_rate)
|
149 |
+
inputs = {"array": inputs, "sampling_rate": pipeline.feature_extractor.sampling_rate}
|
150 |
+
logger.info("done loading")
|
151 |
+
text, runtime = tqdm_generate(inputs, task=task, return_timestamps=return_timestamps, progress=progress)
|
152 |
+
return text, runtime
|
153 |
+
|
154 |
+
def _return_yt_html_embed(yt_url):
|
155 |
+
video_id = yt_url.split("?v=")[-1]
|
156 |
+
HTML_str = (
|
157 |
+
f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
|
158 |
+
" </center>"
|
159 |
+
)
|
160 |
+
return HTML_str
|
161 |
+
|
162 |
+
def download_yt_audio(yt_url, filename):
|
163 |
+
info_loader = youtube_dl.YoutubeDL()
|
164 |
+
try:
|
165 |
+
info = info_loader.extract_info(yt_url, download=False)
|
166 |
+
except youtube_dl.utils.DownloadError as err:
|
167 |
+
raise gr.Error(str(err))
|
168 |
+
|
169 |
+
file_length = info["duration_string"]
|
170 |
+
file_h_m_s = file_length.split(":")
|
171 |
+
file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
|
172 |
+
if len(file_h_m_s) == 1:
|
173 |
+
file_h_m_s.insert(0, 0)
|
174 |
+
if len(file_h_m_s) == 2:
|
175 |
+
file_h_m_s.insert(0, 0)
|
176 |
+
|
177 |
+
file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
|
178 |
+
if file_length_s > YT_LENGTH_LIMIT_S:
|
179 |
+
yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
|
180 |
+
file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
|
181 |
+
raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
|
182 |
+
|
183 |
+
ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
|
184 |
+
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
185 |
+
try:
|
186 |
+
ydl.download([yt_url])
|
187 |
+
except youtube_dl.utils.ExtractorError as err:
|
188 |
+
raise gr.Error(str(err))
|
189 |
+
|
190 |
+
def transcribe_youtube(yt_url, task, return_timestamps, progress=gr.Progress()):
|
191 |
+
progress(0, desc="Loading audio file...")
|
192 |
+
logger.info("loading youtube file...")
|
193 |
+
html_embed_str = _return_yt_html_embed(yt_url)
|
194 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
195 |
+
filepath = os.path.join(tmpdirname, "video.mp4")
|
196 |
+
download_yt_audio(yt_url, filepath)
|
197 |
+
|
198 |
+
with open(filepath, "rb") as f:
|
199 |
+
inputs = f.read()
|
200 |
+
|
201 |
+
inputs = ffmpeg_read(inputs, pipeline.feature_extractor.sampling_rate)
|
202 |
+
inputs = {"array": inputs, "sampling_rate": pipeline.feature_extractor.sampling_rate}
|
203 |
+
logger.info("done loading...")
|
204 |
+
text, runtime = tqdm_generate(inputs, task=task, return_timestamps=return_timestamps, progress=progress)
|
205 |
+
return html_embed_str, text, runtime
|
206 |
+
|
207 |
+
microphone_chunked = gr.Interface(
|
208 |
+
fn=transcribe_chunked_audio,
|
209 |
+
inputs=[
|
210 |
+
gr.Audio(source="microphone", type="filepath"),
|
211 |
+
gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
|
212 |
+
gr.Checkbox(value=False, label="Return timestamps"),
|
213 |
+
],
|
214 |
+
outputs=[
|
215 |
+
gr.Textbox(label="Transcription", show_copy_button=True),
|
216 |
+
gr.Textbox(label="Transcription Time (s)"),
|
217 |
+
],
|
218 |
+
allow_flagging="never",
|
219 |
+
title=title,
|
220 |
+
description=description,
|
221 |
+
article=article,
|
222 |
+
)
|
223 |
+
|
224 |
+
audio_chunked = gr.Interface(
|
225 |
+
fn=transcribe_chunked_audio,
|
226 |
+
inputs=[
|
227 |
+
gr.Audio(source="upload", label="Audio file", type="filepath"),
|
228 |
+
gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
|
229 |
+
gr.Checkbox(value=False, label="Return timestamps"),
|
230 |
+
],
|
231 |
+
outputs=[
|
232 |
+
gr.Textbox(label="Transcription", show_copy_button=True),
|
233 |
+
gr.Textbox(label="Transcription Time (s)"),
|
234 |
+
],
|
235 |
+
allow_flagging="never",
|
236 |
+
title=title,
|
237 |
+
description=description,
|
238 |
+
article=article,
|
239 |
+
)
|
240 |
+
|
241 |
+
youtube = gr.Interface(
|
242 |
+
fn=transcribe_youtube,
|
243 |
+
inputs=[
|
244 |
+
gr.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
|
245 |
+
gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
|
246 |
+
gr.Checkbox(value=False, label="Return timestamps"),
|
247 |
+
],
|
248 |
+
outputs=[
|
249 |
+
gr.HTML(label="Video"),
|
250 |
+
gr.Textbox(label="Transcription", show_copy_button=True),
|
251 |
+
gr.Textbox(label="Transcription Time (s)"),
|
252 |
+
],
|
253 |
+
allow_flagging="never",
|
254 |
+
title=title,
|
255 |
+
examples=[["https://www.youtube.com/watch?v=m8u-18Q0s7I", "transcribe", False]],
|
256 |
+
cache_examples=False,
|
257 |
+
description=description,
|
258 |
+
article=article,
|
259 |
+
)
|
260 |
+
|
261 |
+
demo = gr.Blocks()
|
262 |
+
|
263 |
+
with demo:
|
264 |
+
gr.TabbedInterface([microphone_chunked, audio_chunked, youtube], ["Microphone", "Audio File", "YouTube"])
|
265 |
+
|
266 |
+
demo.queue(max_size=5)
|
267 |
+
demo.launch(show_api=False)
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--find-links https://storage.googleapis.com/jax-releases/libtpu_releases.html
|
2 |
+
jax[tpu]
|
3 |
+
pip install git+https://github.com/sanchit-gandhi/whisper-jax.git
|
4 |
+
requests
|
5 |
+
yt-dlp>=2023.3.4
|