sanchit-gandhi HF staff commited on
Commit
ee44eab
1 Parent(s): 01993f6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -0
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import pytube
4
+ from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
5
+ from transformers.pipelines.audio_utils import ffmpeg_read
6
+
7
+ title = "Whisper JAX: The Fastest Whisper API Available ⚡️"
8
+
9
+ 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.
10
+
11
+ You 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.
12
+ """
13
+
14
+ API_URL = "https://whisper-jax.ngrok.io/generate/"
15
+
16
+ api_info = """## Python API call:
17
+ ```python
18
+ import requests
19
+
20
+ response = requests.post("{URL}", json={
21
+ "inputs": "/path/to/file/audio.mp3",
22
+ "task": "transcribe",
23
+ "return_timestamps": False,
24
+ }).json()
25
+
26
+ data = response["data"]
27
+ ```
28
+
29
+ ## Javascript API call:
30
+ ```javascript
31
+ fetch("{URL}", {
32
+ method: "POST",
33
+ headers: { "Content-Type": "application/json" },
34
+ body: JSON.stringify({
35
+ data: [
36
+ "/path/to/file/audio.mp3",
37
+ "afrikaans",
38
+ "transcribe",
39
+ false,
40
+ ]
41
+ })})
42
+ .then(r => r.json())
43
+ .then(
44
+ r => {
45
+ let data = r.data;
46
+ }
47
+ )
48
+ ```
49
+
50
+ ## CURL API call:
51
+ ```
52
+ curl -X POST -d '{"inputs": "/path/to/file/audio.mp3", "task": "transcribe", "return_timestamps": false}' {URL} -H "content-type: application/json"
53
+ ```
54
+ """
55
+ api_info = api_info.replace("{URL}", API_URL)
56
+ 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."
57
+
58
+ language_names = sorted(TO_LANGUAGE_CODE.keys())
59
+ SAMPLING_RATE = 16000
60
+
61
+
62
+ def query(payload):
63
+ response = requests.post(API_URL, json=payload)
64
+ return response.json(), response.status_code
65
+
66
+
67
+ def inference(inputs, task, return_timestamps):
68
+ payload = {"inputs": inputs, "task": task, "return_timestamps": return_timestamps}
69
+
70
+ data, status_code = query(payload)
71
+
72
+ if status_code == 200:
73
+ text = data["text"]
74
+ else:
75
+ text = data["detail"]
76
+
77
+ if return_timestamps:
78
+ timestamps = data[0]["chunks"]
79
+ else:
80
+ timestamps = None
81
+
82
+ return text, timestamps
83
+
84
+
85
+ def transcribe_audio(microphone, file_upload, task, return_timestamps):
86
+ warn_output = ""
87
+ if (microphone is not None) and (file_upload is not None):
88
+ warn_output = (
89
+ "WARNING: You've uploaded an audio file and used the microphone. "
90
+ "The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
91
+ )
92
+
93
+ elif (microphone is None) and (file_upload is None):
94
+ return "ERROR: You have to either use the microphone or upload an audio file"
95
+
96
+ inputs = microphone if microphone is not None else file_upload
97
+
98
+ inputs = {"array": inputs[1].tolist(), "sampling_rate": inputs[0]}
99
+
100
+ text, timestamps = inference(inputs=inputs, task=task, return_timestamps=return_timestamps)
101
+
102
+ return warn_output + text, timestamps
103
+
104
+
105
+ def _return_yt_html_embed(yt_url):
106
+ video_id = yt_url.split("?v=")[-1]
107
+ HTML_str = (
108
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
109
+ " </center>"
110
+ )
111
+ return HTML_str
112
+
113
+
114
+ def transcribe_youtube(yt_url, task, return_timestamps):
115
+ yt = pytube.YouTube(yt_url)
116
+ html_embed_str = _return_yt_html_embed(yt_url)
117
+ stream = yt.streams.filter(only_audio=True)[0]
118
+ stream.download(filename="audio.mp3")
119
+
120
+ with open("audio.mp3", "rb") as f:
121
+ inputs = f.read()
122
+
123
+ inputs = ffmpeg_read(inputs, SAMPLING_RATE)
124
+ inputs = {"array": inputs.tolist(), "sampling_rate": SAMPLING_RATE}
125
+
126
+ yield html_embed_str, "Video loaded, transcribing audio...", None
127
+
128
+ text, timestamps = inference(inputs=inputs, task=task, return_timestamps=return_timestamps)
129
+
130
+ yield html_embed_str, text, timestamps
131
+
132
+ audio = gr.Interface(
133
+ fn=transcribe_audio,
134
+ inputs=[
135
+ gr.inputs.Audio(source="microphone", optional=True),
136
+ gr.inputs.Audio(source="upload", optional=True),
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.Textbox(label="Transcription"),
142
+ gr.outputs.Textbox(label="Timestamps"),
143
+ ],
144
+ allow_flagging="never",
145
+ title=title,
146
+ description=description,
147
+ article=article,
148
+ )
149
+
150
+ youtube = gr.Interface(
151
+ fn=transcribe_youtube,
152
+ inputs=[
153
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
154
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
155
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
156
+ ],
157
+ outputs=[
158
+ gr.outputs.HTML(label="Video"),
159
+ gr.outputs.Textbox(label="Transcription"),
160
+ gr.outputs.Textbox(label="Timestamps"),
161
+ ],
162
+ allow_flagging="never",
163
+ title=title,
164
+ description=description,
165
+ article=article,
166
+ )
167
+
168
+ demo = gr.Blocks()
169
+
170
+ with demo:
171
+ gr.TabbedInterface([audio, youtube], ["Transcribe Audio", "Transcribe YouTube"])
172
+
173
+ demo.queue()
174
+ demo.launch()