sanchit-gandhi HF staff commited on
Commit
1f63fcf
1 Parent(s): 4ce538c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -79
app.py CHANGED
@@ -1,7 +1,11 @@
1
  import base64
 
 
2
 
3
  import gradio as gr
 
4
  import requests
 
5
  from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
6
  from transformers.pipelines.audio_utils import ffmpeg_read
7
 
@@ -9,14 +13,15 @@ from transformers.pipelines.audio_utils import ffmpeg_read
9
  title = "Whisper JAX: The Fastest Whisper API ⚡️"
10
 
11
  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 **12x** faster, making it the fastest Whisper API available."
12
- # description += "\nYou can submit requests to Whisper JAX through this Gradio Demo, or directly through API calls (see below). This notebook demonstrates how you can run the Whisper JAX model yourself on a TPU v2-8 in a Google Colab: TODO."
13
 
14
  API_URL = "https://whisper-jax.ngrok.io/generate/"
15
 
16
  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 and Gradio demo by 🤗 Hugging Face."
17
 
18
  language_names = sorted(TO_LANGUAGE_CODE.keys())
19
- SAMPLING_RATE = 16000
 
 
20
 
21
 
22
  def query(payload):
@@ -46,89 +51,111 @@ def inference(inputs, language=None, task=None, return_timestamps=False):
46
  return text, timestamps
47
 
48
 
49
- def transcribe_audio(microphone, file_upload, task, return_timestamps):
50
- warn_output = ""
51
- if (microphone is not None) and (file_upload is not None):
52
- warn_output = (
53
- "WARNING: You've uploaded an audio file and used the microphone. "
54
- "The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
55
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- elif (microphone is None) and (file_upload is None):
58
- return "ERROR: You have to either use the microphone or upload an audio file"
59
 
60
- inputs = microphone if microphone is not None else file_upload
61
 
62
- with open(inputs, "rb") as f:
63
- inputs = f.read()
64
 
65
- inputs = ffmpeg_read(inputs, SAMPLING_RATE)
66
- inputs = {"array": base64.b64encode(inputs.tobytes()).decode(), "sampling_rate": SAMPLING_RATE}
67
 
68
- text, timestamps = inference(inputs=inputs, task=task, return_timestamps=return_timestamps)
69
 
70
- return warn_output + text, timestamps
71
 
 
 
 
72
 
73
- def _return_yt_html_embed(yt_url):
74
- video_id = yt_url.split("?v=")[-1]
75
- HTML_str = (
76
- f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
77
- " </center>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  )
79
- return HTML_str
80
-
81
-
82
- def transcribe_youtube(yt_url, task, return_timestamps):
83
- html_embed_str = _return_yt_html_embed(yt_url)
84
-
85
- text, timestamps = inference(inputs=yt_url, task=task, return_timestamps=return_timestamps)
86
-
87
- return html_embed_str, text, timestamps
88
-
89
-
90
- audio = gr.Interface(
91
- fn=transcribe_audio,
92
- inputs=[
93
- gr.inputs.Audio(source="microphone", optional=True, type="filepath"),
94
- gr.inputs.Audio(source="upload", optional=True, type="filepath"),
95
- gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
96
- gr.inputs.Checkbox(default=False, label="Return timestamps"),
97
- ],
98
- outputs=[
99
- gr.outputs.Textbox(label="Transcription"),
100
- gr.outputs.Textbox(label="Timestamps"),
101
- ],
102
- allow_flagging="never",
103
- title=title,
104
- description=description,
105
- article=article,
106
- )
107
-
108
- youtube = gr.Interface(
109
- fn=transcribe_youtube,
110
- inputs=[
111
- gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
112
- gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
113
- gr.inputs.Checkbox(default=False, label="Return timestamps"),
114
- ],
115
- outputs=[
116
- gr.outputs.HTML(label="Video"),
117
- gr.outputs.Textbox(label="Transcription"),
118
- gr.outputs.Textbox(label="Timestamps"),
119
- ],
120
- allow_flagging="never",
121
- title=title,
122
- examples=[["https://www.youtube.com/watch?v=m8u-18Q0s7I", "transcribe", False]],
123
- cache_examples=False,
124
- description=description,
125
- article=article,
126
- )
127
-
128
- demo = gr.Blocks()
129
-
130
- with demo:
131
- gr.TabbedInterface([audio, youtube], ["Transcribe Audio", "Transcribe YouTube"])
132
-
133
- demo.queue()
134
- demo.launch()
 
1
  import base64
2
+ from functools import partial
3
+ from multiprocessing import Pool
4
 
5
  import gradio as gr
6
+ import numpy as np
7
  import requests
8
+ from processing_whisper import WhisperPrePostProcessor
9
  from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
10
  from transformers.pipelines.audio_utils import ffmpeg_read
11
 
 
13
  title = "Whisper JAX: The Fastest Whisper API ⚡️"
14
 
15
  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 **12x** faster, making it the fastest Whisper API available."
 
16
 
17
  API_URL = "https://whisper-jax.ngrok.io/generate/"
18
 
19
  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 and Gradio demo by 🤗 Hugging Face."
20
 
21
  language_names = sorted(TO_LANGUAGE_CODE.keys())
22
+ CHUNK_LENGTH_S = 30
23
+ BATCH_SIZE = 16
24
+ NUM_PROC = 16
25
 
26
 
27
  def query(payload):
 
51
  return text, timestamps
52
 
53
 
54
+ def chunked_query(payload):
55
+ response = requests.post("https://whisper-jax.ngrok.io/generate_from_features", json=payload)
56
+ return response.json()
57
+
58
+
59
+ def forward(batch, task=None, return_timestamps=False):
60
+ feature_shape = batch["input_features"].shape
61
+ batch["input_features"] = base64.b64encode(batch["input_features"].tobytes()).decode()
62
+ outputs = chunked_query(
63
+ {"batch": batch, "task": task, "return_timestamps": return_timestamps, "feature_shape": feature_shape}
64
+ )
65
+ outputs["tokens"] = np.asarray(outputs["tokens"])
66
+ return outputs
67
+
68
+
69
+ if __name__ == "__main__":
70
+ processor = WhisperPrePostProcessor.from_pretrained("openai/whisper-large-v2")
71
+ pool = Pool(NUM_PROC)
72
+
73
+ def transcribe_chunked_audio(microphone, file_upload, task, return_timestamps):
74
+ warn_output = ""
75
+ if (microphone is not None) and (file_upload is not None):
76
+ warn_output = (
77
+ "WARNING: You've uploaded an audio file and used the microphone. "
78
+ "The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
79
+ )
80
 
81
+ elif (microphone is None) and (file_upload is None):
82
+ return "ERROR: You have to either use the microphone or upload an audio file"
83
 
84
+ inputs = microphone if microphone is not None else file_upload
85
 
86
+ with open(inputs, "rb") as f:
87
+ inputs = f.read()
88
 
89
+ inputs = ffmpeg_read(inputs, processor.feature_extractor.sampling_rate)
90
+ inputs = {"array": inputs, "sampling_rate": processor.feature_extractor.sampling_rate}
91
 
92
+ dataloader = processor.preprocess_batch(inputs, chunk_length_s=CHUNK_LENGTH_S, batch_size=BATCH_SIZE)
93
 
94
+ model_outputs = pool.map(partial(forward, task=task, return_timestamps=return_timestamps), dataloader)
95
 
96
+ post_processed = processor.postprocess(model_outputs, return_timestamps=return_timestamps)
97
+ timestamps = post_processed.get("chunks")
98
+ return warn_output + post_processed["text"], timestamps
99
 
100
+ def _return_yt_html_embed(yt_url):
101
+ video_id = yt_url.split("?v=")[-1]
102
+ HTML_str = (
103
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
104
+ " </center>"
105
+ )
106
+ return HTML_str
107
+
108
+ def transcribe_youtube(yt_url, task, return_timestamps):
109
+ html_embed_str = _return_yt_html_embed(yt_url)
110
+
111
+ text, timestamps = inference(inputs=yt_url, task=task, return_timestamps=return_timestamps)
112
+
113
+ return html_embed_str, text, timestamps
114
+
115
+ audio_chunked = gr.Interface(
116
+ fn=transcribe_chunked_audio,
117
+ inputs=[
118
+ gr.inputs.Audio(source="microphone", optional=True, type="filepath"),
119
+ gr.inputs.Audio(source="upload", optional=True, type="filepath"),
120
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
121
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
122
+ ],
123
+ outputs=[
124
+ gr.outputs.Textbox(label="Transcription"),
125
+ gr.outputs.Textbox(label="Timestamps"),
126
+ ],
127
+ allow_flagging="never",
128
+ title=title,
129
+ description=description,
130
+ article=article,
131
+ )
132
+
133
+ youtube = gr.Interface(
134
+ fn=transcribe_youtube,
135
+ inputs=[
136
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
137
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
138
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
139
+ ],
140
+ outputs=[
141
+ gr.outputs.HTML(label="Video"),
142
+ gr.outputs.Textbox(label="Transcription"),
143
+ gr.outputs.Textbox(label="Timestamps"),
144
+ ],
145
+ allow_flagging="never",
146
+ title=title,
147
+ examples=[["https://www.youtube.com/watch?v=m8u-18Q0s7I", "transcribe", False]],
148
+ cache_examples=False,
149
+ description=description,
150
+ article=article,
151
  )
152
+
153
+ demo = gr.Blocks()
154
+
155
+ with demo:
156
+ gr.TabbedInterface(
157
+ [audio_chunked, youtube], ["Transcribe Audio", "Transcribe YouTube"]
158
+ )
159
+
160
+ demo.queue()
161
+ demo.launch()