RaysDipesh commited on
Commit
48a2587
·
1 Parent(s): becdc3e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +235 -0
app.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import math
3
+ import os
4
+ import time
5
+ from functools import partial
6
+ from multiprocessing import Pool
7
+
8
+ import gradio as gr
9
+ import numpy as np
10
+ import pytube
11
+ import requests
12
+ from processing_whisper import WhisperPrePostProcessor
13
+ from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
14
+ from transformers.pipelines.audio_utils import ffmpeg_read
15
+
16
+
17
+ title = "Whisper JAX: The Fastest Whisper API ⚡️"
18
+
19
+ description = """Whisper JAX is an optimised implementation of the [Whisper model](https://huggingface.co/openai/whisper-large-v2) 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.
20
+
21
+ 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 sent to the TPU and then transcribed, with the progress displayed through a progress bar.
22
+
23
+ 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).
24
+ """
25
+
26
+ article = "Whisper large-v2 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."
27
+
28
+ API_SEND_URL = os.getenv("API_SEND_URL")
29
+ API_FORWARD_URL = os.getenv("API_FORWARD_URL")
30
+
31
+ language_names = sorted(TO_LANGUAGE_CODE.keys())
32
+ CHUNK_LENGTH_S = 30
33
+ BATCH_SIZE = 16
34
+ NUM_PROC = 16
35
+ FILE_LIMIT_MB = 1000
36
+
37
+
38
+ def query(url, payload):
39
+ response = requests.post(url, json=payload)
40
+ return response.json(), response.status_code
41
+
42
+
43
+ def inference(batch_id, idx, task=None, return_timestamps=False):
44
+ payload = {"batch_id": batch_id, "idx": idx, "task": task, "return_timestamps": return_timestamps}
45
+
46
+ data, status_code = query(API_FORWARD_URL, payload)
47
+
48
+ if status_code == 200:
49
+ tokens = {"tokens": np.asarray(data["tokens"])}
50
+ return tokens
51
+ else:
52
+ gr.Error(data["detail"])
53
+
54
+
55
+ def send_chunks(batch, batch_id):
56
+ feature_shape = batch["input_features"].shape
57
+ batch["input_features"] = base64.b64encode(batch["input_features"].tobytes()).decode()
58
+ query(API_SEND_URL, {"batch": batch, "feature_shape": feature_shape, "batch_id": batch_id})
59
+
60
+
61
+ def forward(batch_id, idx, task=None, return_timestamps=False):
62
+ outputs = inference(batch_id, idx, task, return_timestamps)
63
+ return outputs
64
+
65
+
66
+ # Copied from https://github.com/openai/whisper/blob/c09a7ae299c4c34c5839a76380ae407e7d785914/whisper/utils.py#L50
67
+ def format_timestamp(seconds: float, always_include_hours: bool = False, decimal_marker: str = "."):
68
+ if seconds is not None:
69
+ milliseconds = round(seconds * 1000.0)
70
+
71
+ hours = milliseconds // 3_600_000
72
+ milliseconds -= hours * 3_600_000
73
+
74
+ minutes = milliseconds // 60_000
75
+ milliseconds -= minutes * 60_000
76
+
77
+ seconds = milliseconds // 1_000
78
+ milliseconds -= seconds * 1_000
79
+
80
+ hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
81
+ return f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}"
82
+ else:
83
+ # we have a malformed timestamp so just return it as is
84
+ return seconds
85
+
86
+
87
+ if __name__ == "__main__":
88
+ processor = WhisperPrePostProcessor.from_pretrained("openai/whisper-large-v2")
89
+ stride_length_s = CHUNK_LENGTH_S / 6
90
+ chunk_len = round(CHUNK_LENGTH_S * processor.feature_extractor.sampling_rate)
91
+ stride_left = stride_right = round(stride_length_s * processor.feature_extractor.sampling_rate)
92
+ step = chunk_len - stride_left - stride_right
93
+ pool = Pool(NUM_PROC)
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_batch_id = np.arange(0, inputs_len, step)
98
+ num_samples = len(all_chunk_start_batch_id)
99
+ num_batches = math.ceil(num_samples / BATCH_SIZE)
100
+ dummy_batches = list(range(num_batches))
101
+
102
+ dataloader = processor.preprocess_batch(inputs, chunk_length_s=CHUNK_LENGTH_S, batch_size=BATCH_SIZE)
103
+ progress(0, desc="Sending audio to TPU...")
104
+ batch_id = np.random.randint(
105
+ 1000000
106
+ ) # TODO(SG): swap to an iterator - currently taking our 1 in a million chances
107
+ pool.map(partial(send_chunks, batch_id=batch_id), dataloader)
108
+
109
+ model_outputs = []
110
+ start_time = time.time()
111
+ # iterate over our chunked audio samples
112
+ for idx in progress.tqdm(dummy_batches, desc="Transcribing..."):
113
+ model_outputs.append(forward(batch_id, idx, task=task, return_timestamps=return_timestamps))
114
+ runtime = time.time() - start_time
115
+
116
+ post_processed = processor.postprocess(model_outputs, return_timestamps=return_timestamps)
117
+ text = post_processed["text"]
118
+ timestamps = post_processed.get("chunks")
119
+ if timestamps is not None:
120
+ timestamps = [
121
+ f"[{format_timestamp(chunk['timestamp'][0])} -> {format_timestamp(chunk['timestamp'][1])}] {chunk['text']}"
122
+ for chunk in timestamps
123
+ ]
124
+ text = "\n".join(str(feature) for feature in timestamps)
125
+ return text, runtime
126
+
127
+ def transcribe_chunked_audio(inputs, task, return_timestamps, progress=gr.Progress()):
128
+ progress(0, desc="Loading audio file...")
129
+ if inputs is None:
130
+ raise gr.Error("No audio file submitted! Please upload an audio file before submitting your request.")
131
+ file_size_mb = os.stat(inputs).st_size / (1024 * 1024)
132
+ if file_size_mb > FILE_LIMIT_MB:
133
+ raise gr.Error(
134
+ f"File size exceeds file size limit. Got file of size {file_size_mb:.2f}MB for a limit of {FILE_LIMIT_MB}MB."
135
+ )
136
+
137
+ with open(inputs, "rb") as f:
138
+ inputs = f.read()
139
+
140
+ inputs = ffmpeg_read(inputs, processor.feature_extractor.sampling_rate)
141
+ inputs = {"array": inputs, "sampling_rate": processor.feature_extractor.sampling_rate}
142
+ text, runtime = tqdm_generate(inputs, task=task, return_timestamps=return_timestamps, progress=progress)
143
+ return text, runtime
144
+
145
+ def _return_yt_html_embed(yt_url):
146
+ video_id = yt_url.split("?v=")[-1]
147
+ HTML_str = (
148
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
149
+ " </center>"
150
+ )
151
+ return HTML_str
152
+
153
+ def transcribe_youtube(yt_url, task, return_timestamps, progress=gr.Progress(), max_filesize=75.0):
154
+ progress(0, desc="Loading audio file...")
155
+ html_embed_str = _return_yt_html_embed(yt_url)
156
+ try:
157
+ yt = pytube.YouTube(yt_url)
158
+ stream = yt.streams.filter(only_audio=True)[0]
159
+ except:
160
+ raise gr.Error("An error occurred while loading the YouTube video. Please try again.")
161
+
162
+ if stream.filesize_mb > max_filesize:
163
+ raise gr.Error(f"Maximum YouTube file size is {max_filesize}MB, got {stream.filesize_mb:.2f}MB.")
164
+
165
+ stream.download(filename="audio.mp3")
166
+
167
+ with open("audio.mp3", "rb") as f:
168
+ inputs = f.read()
169
+
170
+ inputs = ffmpeg_read(inputs, processor.feature_extractor.sampling_rate)
171
+ inputs = {"array": inputs, "sampling_rate": processor.feature_extractor.sampling_rate}
172
+ text, runtime = tqdm_generate(inputs, task=task, return_timestamps=return_timestamps, progress=progress)
173
+ return html_embed_str, text, runtime
174
+
175
+ microphone_chunked = gr.Interface(
176
+ fn=transcribe_chunked_audio,
177
+ inputs=[
178
+ gr.inputs.Audio(source="microphone", optional=True, type="filepath"),
179
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
180
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
181
+ ],
182
+ outputs=[
183
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
184
+ gr.outputs.Textbox(label="Transcription Time (s)"),
185
+ ],
186
+ allow_flagging="never",
187
+ title=title,
188
+ description=description,
189
+ article=article,
190
+ )
191
+
192
+ audio_chunked = gr.Interface(
193
+ fn=transcribe_chunked_audio,
194
+ inputs=[
195
+ gr.inputs.Audio(source="upload", optional=True, label="Audio file", type="filepath"),
196
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
197
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
198
+ ],
199
+ outputs=[
200
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
201
+ gr.outputs.Textbox(label="Transcription Time (s)"),
202
+ ],
203
+ allow_flagging="never",
204
+ title=title,
205
+ description=description,
206
+ article=article,
207
+ )
208
+
209
+ youtube = gr.Interface(
210
+ fn=transcribe_youtube,
211
+ inputs=[
212
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
213
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
214
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
215
+ ],
216
+ outputs=[
217
+ gr.outputs.HTML(label="Video"),
218
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
219
+ gr.outputs.Textbox(label="Transcription Time (s)"),
220
+ ],
221
+ allow_flagging="never",
222
+ title=title,
223
+ examples=[["https://www.youtube.com/watch?v=m8u-18Q0s7I", "transcribe", False]],
224
+ cache_examples=False,
225
+ description=description,
226
+ article=article,
227
+ )
228
+
229
+ demo = gr.Blocks()
230
+
231
+ with demo:
232
+ gr.TabbedInterface([microphone_chunked, audio_chunked, youtube], ["Microphone", "Audio File", "YouTube"])
233
+
234
+ demo.queue(max_size=10)
235
+ demo.launch(show_api=False, max_threads=10)