sanchit-gandhi HF staff commited on
Commit
9b43ccd
1 Parent(s): ce13071
Files changed (8) hide show
  1. Dockerfile +0 -30
  2. README.md +3 -4
  3. app.py +246 -0
  4. nginx.conf +0 -23
  5. packages.txt +2 -0
  6. processing_whisper.py +146 -0
  7. requirements.txt +4 -0
  8. run.sh +0 -5
Dockerfile DELETED
@@ -1,30 +0,0 @@
1
- FROM ubuntu
2
-
3
- # Based on https://huggingface.co/spaces/radames/nginx-gradio-reverse-proxy/blob/main/Dockerfile
4
- USER root
5
-
6
- RUN apt-get -y update && apt-get -y install nginx
7
- RUN mkdir -p /var/cache/nginx \
8
- /var/log/nginx \
9
- /var/lib/nginx
10
- RUN touch /var/run/nginx.pid
11
-
12
- RUN chown -R 1000:1000 /var/cache/nginx \
13
- /var/log/nginx \
14
- /var/lib/nginx \
15
- /var/run/nginx.pid
16
-
17
- RUN useradd -m -u 1000 user
18
-
19
- USER user
20
- ENV HOME=/home/user
21
-
22
- RUN mkdir $HOME/app
23
- WORKDIR $HOME/app
24
-
25
- # Copy nginx configuration
26
- COPY --chown=user nginx.conf /etc/nginx/sites-available/default
27
- COPY --chown=user . .
28
-
29
- CMD ["bash", "run.sh"]
30
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,10 +1,9 @@
1
- ---
2
  title: Whisper JAX
3
  emoji: ⚡️
4
  colorFrom: yellow
5
  colorTo: indigo
6
- sdk: docker
 
 
7
  pinned: false
8
- ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
  title: Whisper JAX
2
  emoji: ⚡️
3
  colorFrom: yellow
4
  colorTo: indigo
5
+ sdk: gradio
6
+ sdk_version: 3.27.0
7
+ app_file: app.py
8
  pinned: false
 
9
 
 
app.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import math
3
+ import os
4
+ import time
5
+ from multiprocessing import Pool
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ import pytube
10
+ import requests
11
+ from processing_whisper import WhisperPrePostProcessor
12
+ from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
13
+ from transformers.pipelines.audio_utils import ffmpeg_read
14
+
15
+
16
+ title = "Whisper JAX: The Fastest Whisper API ⚡️"
17
+
18
+ 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.
19
+
20
+ Note that using microphone or audio file requires the audio input to be transferred from the Gradio demo to the TPU, which for large audio files can be slow. We recommend using YouTube where possible, since this directly downloads the audio file to the TPU, skipping the file transfer step.
21
+ """
22
+
23
+ API_URL = os.getenv("API_URL")
24
+ API_URL_FROM_FEATURES = os.getenv("API_URL_FROM_FEATURES")
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
+ language_names = sorted(TO_LANGUAGE_CODE.keys())
29
+ CHUNK_LENGTH_S = 30
30
+ BATCH_SIZE = 16
31
+ NUM_PROC = 16
32
+ FILE_LIMIT_MB = 1000
33
+
34
+
35
+ def query(payload):
36
+ response = requests.post(API_URL, json=payload)
37
+ return response.json(), response.status_code
38
+
39
+
40
+ def inference(inputs, task=None, return_timestamps=False):
41
+ payload = {"inputs": inputs, "task": task, "return_timestamps": return_timestamps}
42
+
43
+ data, status_code = query(payload)
44
+
45
+ if status_code == 200:
46
+ text = data["text"]
47
+ else:
48
+ text = data["detail"]
49
+
50
+ timestamps = data.get("chunks")
51
+ if timestamps is not None:
52
+ timestamps = [
53
+ f"[{format_timestamp(chunk['timestamp'][0])} -> {format_timestamp(chunk['timestamp'][1])}] {chunk['text']}"
54
+ for chunk in timestamps
55
+ ]
56
+ text = "\n".join(str(feature) for feature in timestamps)
57
+ return text
58
+
59
+
60
+ def chunked_query(payload):
61
+ response = requests.post(API_URL_FROM_FEATURES, json=payload)
62
+ return response.json()
63
+
64
+
65
+ def forward(batch, task=None, return_timestamps=False):
66
+ feature_shape = batch["input_features"].shape
67
+ batch["input_features"] = base64.b64encode(batch["input_features"].tobytes()).decode()
68
+ outputs = chunked_query(
69
+ {"batch": batch, "task": task, "return_timestamps": return_timestamps, "feature_shape": feature_shape}
70
+ )
71
+ outputs["tokens"] = np.asarray(outputs["tokens"])
72
+ return outputs
73
+
74
+
75
+ def identity(batch):
76
+ return batch
77
+
78
+
79
+ # Copied from https://github.com/openai/whisper/blob/c09a7ae299c4c34c5839a76380ae407e7d785914/whisper/utils.py#L50
80
+ def format_timestamp(seconds: float, always_include_hours: bool = False, decimal_marker: str = "."):
81
+ if seconds is not None:
82
+ milliseconds = round(seconds * 1000.0)
83
+
84
+ hours = milliseconds // 3_600_000
85
+ milliseconds -= hours * 3_600_000
86
+
87
+ minutes = milliseconds // 60_000
88
+ milliseconds -= minutes * 60_000
89
+
90
+ seconds = milliseconds // 1_000
91
+ milliseconds -= seconds * 1_000
92
+
93
+ hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
94
+ return f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}"
95
+ else:
96
+ # we have a malformed timestamp so just return it as is
97
+ return seconds
98
+
99
+
100
+ if __name__ == "__main__":
101
+ processor = WhisperPrePostProcessor.from_pretrained("openai/whisper-large-v2")
102
+ stride_length_s = CHUNK_LENGTH_S / 6
103
+ chunk_len = round(CHUNK_LENGTH_S * processor.feature_extractor.sampling_rate)
104
+ stride_left = stride_right = round(stride_length_s * processor.feature_extractor.sampling_rate)
105
+ step = chunk_len - stride_left - stride_right
106
+ pool = Pool(NUM_PROC)
107
+
108
+ def tqdm_generate(inputs: dict, task: str, return_timestamps: bool, progress: gr.Progress):
109
+ inputs_len = inputs["array"].shape[0]
110
+ all_chunk_start_idx = np.arange(0, inputs_len, step)
111
+ num_samples = len(all_chunk_start_idx)
112
+ num_batches = math.ceil(num_samples / BATCH_SIZE)
113
+ dummy_batches = list(
114
+ range(num_batches)
115
+ ) # Gradio progress bar not compatible with generator, see https://github.com/gradio-app/gradio/issues/3841
116
+
117
+ dataloader = processor.preprocess_batch(inputs, chunk_length_s=CHUNK_LENGTH_S, batch_size=BATCH_SIZE)
118
+ progress(0, desc="Pre-processing audio file...")
119
+ dataloader = pool.map(identity, dataloader)
120
+
121
+ model_outputs = []
122
+ start_time = time.time()
123
+ # iterate over our chunked audio samples
124
+ for batch, _ in zip(dataloader, progress.tqdm(dummy_batches, desc="Transcribing...")):
125
+ model_outputs.append(forward(batch, task=task, return_timestamps=return_timestamps))
126
+ runtime = time.time() - start_time
127
+
128
+ post_processed = processor.postprocess(model_outputs, return_timestamps=return_timestamps)
129
+ text = post_processed["text"]
130
+ timestamps = post_processed.get("chunks")
131
+ if timestamps is not None:
132
+ timestamps = [
133
+ f"[{format_timestamp(chunk['timestamp'][0])} -> {format_timestamp(chunk['timestamp'][1])}] {chunk['text']}"
134
+ for chunk in timestamps
135
+ ]
136
+ text = "\n".join(str(feature) for feature in timestamps)
137
+ return text, runtime
138
+
139
+ def transcribe_chunked_audio(inputs, task, return_timestamps, progress=gr.Progress()):
140
+ progress(0, desc="Loading audio file...")
141
+ file_size_mb = os.stat(inputs).st_size / (1024 * 1024)
142
+ if file_size_mb > FILE_LIMIT_MB:
143
+ raise gr.Error(
144
+ f"File size exceeds file size limit. Got file of size {file_size_mb:.2f}MB for a limit of {FILE_LIMIT_MB}MB."
145
+ )
146
+
147
+ with open(inputs, "rb") as f:
148
+ inputs = f.read()
149
+
150
+ inputs = ffmpeg_read(inputs, processor.feature_extractor.sampling_rate)
151
+ inputs = {"array": inputs, "sampling_rate": processor.feature_extractor.sampling_rate}
152
+ text, runtime = tqdm_generate(inputs, task=task, return_timestamps=return_timestamps, progress=progress)
153
+ return text, runtime
154
+
155
+ def _return_yt_html_embed(yt_url):
156
+ video_id = yt_url.split("?v=")[-1]
157
+ HTML_str = (
158
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
159
+ " </center>"
160
+ )
161
+ return HTML_str
162
+
163
+ def transcribe_youtube(yt_url, task, return_timestamps, progress=gr.Progress(), max_filesize=75.0):
164
+ progress(0, desc="Loading audio file...")
165
+ html_embed_str = _return_yt_html_embed(yt_url)
166
+ try:
167
+ yt = pytube.YouTube(yt_url)
168
+ stream = yt.streams.filter(only_audio=True)[0]
169
+ except KeyError:
170
+ raise gr.Error("An error occurred while loading the YouTube video. Please try again.")
171
+
172
+ if stream.filesize_mb > max_filesize:
173
+ raise gr.Error(f"Maximum YouTube file size is {max_filesize}MB, got {stream.filesize_mb:.2f}MB.")
174
+
175
+ stream.download(filename="audio.mp3")
176
+
177
+ with open("audio.mp3", "rb") as f:
178
+ inputs = f.read()
179
+
180
+ inputs = ffmpeg_read(inputs, processor.feature_extractor.sampling_rate)
181
+ inputs = {"array": inputs, "sampling_rate": processor.feature_extractor.sampling_rate}
182
+ text, runtime = tqdm_generate(inputs, task=task, return_timestamps=return_timestamps, progress=progress)
183
+ return html_embed_str, text, runtime
184
+
185
+ microphone_chunked = gr.Interface(
186
+ fn=transcribe_chunked_audio,
187
+ inputs=[
188
+ gr.inputs.Audio(source="microphone", optional=True, type="filepath"),
189
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
190
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
191
+ ],
192
+ outputs=[
193
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
194
+ gr.outputs.Textbox(label="Transcription Time (s)"),
195
+ ],
196
+ allow_flagging="never",
197
+ title=title,
198
+ description=description,
199
+ article=article,
200
+ )
201
+
202
+ audio_chunked = gr.Interface(
203
+ fn=transcribe_chunked_audio,
204
+ inputs=[
205
+ gr.inputs.Audio(source="upload", optional=True, label="Audio file", type="filepath"),
206
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
207
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
208
+ ],
209
+ outputs=[
210
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
211
+ gr.outputs.Textbox(label="Transcription Time (s)"),
212
+ ],
213
+ allow_flagging="never",
214
+ title=title,
215
+ description=description,
216
+ article=article,
217
+ )
218
+
219
+ youtube = gr.Interface(
220
+ fn=transcribe_youtube,
221
+ inputs=[
222
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
223
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
224
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
225
+ ],
226
+ outputs=[
227
+ gr.outputs.HTML(label="Video"),
228
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
229
+ gr.outputs.Textbox(label="Transcription Time (s)"),
230
+ ],
231
+ allow_flagging="never",
232
+ title=title,
233
+ examples=[["https://www.youtube.com/watch?v=m8u-18Q0s7I", "transcribe", False]],
234
+ cache_examples=False,
235
+ description=description,
236
+ article=article,
237
+ )
238
+
239
+ demo = gr.Blocks()
240
+
241
+ with demo:
242
+ gr.TabbedInterface([microphone_chunked, audio_chunked, youtube], ["Microphone", "Audio File", "YouTube"])
243
+
244
+ demo.queue(concurrency_count=3, max_size=5)
245
+ demo.launch(show_api=False)
246
+
nginx.conf DELETED
@@ -1,23 +0,0 @@
1
- server {
2
- listen 7860 default_server;
3
- listen [::]:7860 default_server;
4
-
5
- root /usr/share/nginx/html;
6
- index index.html index.htm;
7
-
8
- server_name _;
9
- location / {
10
- proxy_pass https://API_URL;
11
- proxy_set_header Host API_URL;
12
- proxy_set_header X-Real-IP $remote_addr;
13
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
14
- #proxy_set_header X-Forwarded-Proto $scheme;
15
- proxy_set_header X-Forwarded-Proto http;
16
- proxy_set_header X-Forwarded-Ssl off;
17
- proxy_set_header X-Url-Scheme http;
18
- proxy_buffering off;
19
- proxy_http_version 1.1;
20
- proxy_set_header Upgrade $http_upgrade;
21
- proxy_set_header Connection "upgrade";
22
- }
23
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+
processing_whisper.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import numpy as np
4
+ from transformers import WhisperProcessor
5
+
6
+
7
+ class WhisperPrePostProcessor(WhisperProcessor):
8
+ def chunk_iter_with_batch(self, inputs, chunk_len, stride_left, stride_right, batch_size):
9
+ inputs_len = inputs.shape[0]
10
+ step = chunk_len - stride_left - stride_right
11
+
12
+ all_chunk_start_idx = np.arange(0, inputs_len, step)
13
+ num_samples = len(all_chunk_start_idx)
14
+
15
+ num_batches = math.ceil(num_samples / batch_size)
16
+ batch_idx = np.array_split(np.arange(num_samples), num_batches)
17
+
18
+ for i, idx in enumerate(batch_idx):
19
+ chunk_start_idx = all_chunk_start_idx[idx]
20
+
21
+ chunk_end_idx = chunk_start_idx + chunk_len
22
+
23
+ chunks = [inputs[chunk_start:chunk_end] for chunk_start, chunk_end in zip(chunk_start_idx, chunk_end_idx)]
24
+ processed = self.feature_extractor(
25
+ chunks, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="np"
26
+ )
27
+
28
+ _stride_left = np.where(chunk_start_idx == 0, 0, stride_left)
29
+ is_last = np.where(stride_right > 0, chunk_end_idx > inputs_len, chunk_end_idx >= inputs_len)
30
+ _stride_right = np.where(is_last, 0, stride_right)
31
+
32
+ chunk_lens = [chunk.shape[0] for chunk in chunks]
33
+ strides = [
34
+ (int(chunk_l), int(_stride_l), int(_stride_r))
35
+ for chunk_l, _stride_l, _stride_r in zip(chunk_lens, _stride_left, _stride_right)
36
+ ]
37
+
38
+ yield {"stride": strides, **processed}
39
+
40
+ def preprocess_batch(self, inputs, chunk_length_s=0, stride_length_s=None, batch_size=None):
41
+ stride = None
42
+ if isinstance(inputs, dict):
43
+ stride = inputs.pop("stride", None)
44
+ # Accepting `"array"` which is the key defined in `datasets` for
45
+ # better integration
46
+ if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
47
+ raise ValueError(
48
+ "When passing a dictionary to FlaxWhisperPipline, the dict needs to contain a "
49
+ '"raw" or "array" key containing the numpy array representing the audio, and a "sampling_rate" key '
50
+ "containing the sampling rate associated with the audio array."
51
+ )
52
+
53
+ _inputs = inputs.pop("raw", None)
54
+ if _inputs is None:
55
+ # Remove path which will not be used from `datasets`.
56
+ inputs.pop("path", None)
57
+ _inputs = inputs.pop("array", None)
58
+ in_sampling_rate = inputs.pop("sampling_rate")
59
+ inputs = _inputs
60
+
61
+ if in_sampling_rate != self.feature_extractor.sampling_rate:
62
+ try:
63
+ import librosa
64
+ except ImportError as err:
65
+ raise ImportError(
66
+ "To support resampling audio files, please install 'librosa' and 'soundfile'."
67
+ ) from err
68
+
69
+ inputs = librosa.resample(
70
+ inputs, orig_sr=in_sampling_rate, target_sr=self.feature_extractor.sampling_rate
71
+ )
72
+ ratio = self.feature_extractor.sampling_rate / in_sampling_rate
73
+ else:
74
+ ratio = 1
75
+
76
+ if not isinstance(inputs, np.ndarray):
77
+ raise ValueError(f"We expect a numpy ndarray as input, got `{type(inputs)}`.")
78
+ if len(inputs.shape) != 1:
79
+ raise ValueError(
80
+ f"We expect a single channel audio input for the Flax Whisper API, got {len(inputs.shape)} channels."
81
+ )
82
+
83
+ if stride is not None:
84
+ if stride[0] + stride[1] > inputs.shape[0]:
85
+ raise ValueError("Stride is too large for input.")
86
+
87
+ # Stride needs to get the chunk length here, it's going to get
88
+ # swallowed by the `feature_extractor` later, and then batching
89
+ # can add extra data in the inputs, so we need to keep track
90
+ # of the original length in the stride so we can cut properly.
91
+ stride = (inputs.shape[0], int(round(stride[0] * ratio)), int(round(stride[1] * ratio)))
92
+
93
+ if chunk_length_s:
94
+ if stride_length_s is None:
95
+ stride_length_s = chunk_length_s / 6
96
+
97
+ if isinstance(stride_length_s, (int, float)):
98
+ stride_length_s = [stride_length_s, stride_length_s]
99
+
100
+ chunk_len = round(chunk_length_s * self.feature_extractor.sampling_rate)
101
+ stride_left = round(stride_length_s[0] * self.feature_extractor.sampling_rate)
102
+ stride_right = round(stride_length_s[1] * self.feature_extractor.sampling_rate)
103
+
104
+ if chunk_len < stride_left + stride_right:
105
+ raise ValueError("Chunk length must be superior to stride length.")
106
+
107
+ for item in self.chunk_iter_with_batch(
108
+ inputs,
109
+ chunk_len,
110
+ stride_left,
111
+ stride_right,
112
+ batch_size,
113
+ ):
114
+ yield item
115
+ else:
116
+ processed = self.feature_extractor(
117
+ inputs, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="np"
118
+ )
119
+ if stride is not None:
120
+ processed["stride"] = stride
121
+ yield processed
122
+
123
+ def postprocess(self, model_outputs, return_timestamps=None, return_language=None):
124
+ # unpack the outputs from list(dict(list)) to list(dict)
125
+ model_outputs = [dict(zip(output, t)) for output in model_outputs for t in zip(*output.values())]
126
+
127
+ time_precision = self.feature_extractor.chunk_length / 1500 # max source positions = 1500
128
+ # Send the chunking back to seconds, it's easier to handle in whisper
129
+ sampling_rate = self.feature_extractor.sampling_rate
130
+ for output in model_outputs:
131
+ if "stride" in output:
132
+ chunk_len, stride_left, stride_right = output["stride"]
133
+ # Go back in seconds
134
+ chunk_len /= sampling_rate
135
+ stride_left /= sampling_rate
136
+ stride_right /= sampling_rate
137
+ output["stride"] = chunk_len, stride_left, stride_right
138
+
139
+ text, optional = self.tokenizer._decode_asr(
140
+ model_outputs,
141
+ return_timestamps=return_timestamps,
142
+ return_language=return_language,
143
+ time_precision=time_precision,
144
+ )
145
+ return {"text": text, **optional}
146
+
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ transformers
2
+ pytube
3
+ requests>=2.28.2
4
+
run.sh DELETED
@@ -1,5 +0,0 @@
1
- #!/bin/bash
2
-
3
- cat nginx.conf | sed "s|API_URL|${API_URL}|g" > /etc/nginx/sites-available/default
4
- service nginx start
5
- sleep infinity