sanchit-gandhi commited on
Commit
96926b8
·
1 Parent(s): e3d9fb4

Switch to Docker

Browse files
Files changed (8) hide show
  1. Dockerfile +30 -0
  2. README.md +1 -3
  3. app.py +0 -177
  4. nginx.conf +23 -0
  5. packages.txt +0 -1
  6. processing_whisper.py +0 -145
  7. requirements.txt +0 -3
  8. run.sh +4 -0
Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
@@ -3,9 +3,7 @@ title: Whisper JAX
3
  emoji: ⚡️
4
  colorFrom: yellow
5
  colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 3.24.1
8
- app_file: app.py
9
  pinned: false
10
  ---
11
 
 
3
  emoji: ⚡️
4
  colorFrom: yellow
5
  colorTo: indigo
6
+ sdk: docker
 
 
7
  pinned: false
8
  ---
9
 
app.py DELETED
@@ -1,177 +0,0 @@
1
- import base64
2
- import os
3
- from functools import partial
4
- from multiprocessing import Pool
5
-
6
- import gradio as gr
7
- import numpy as np
8
- import requests
9
- from processing_whisper import WhisperPrePostProcessor
10
- from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
11
- from transformers.pipelines.audio_utils import ffmpeg_read
12
-
13
-
14
- title = "Whisper JAX: The Fastest Whisper API ⚡️"
15
-
16
- 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.
17
-
18
- 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.
19
- """
20
-
21
- API_URL = os.getenv("API_URL")
22
- API_URL_FROM_FEATURES = os.getenv("API_URL_FROM_FEATURES")
23
-
24
- 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."
25
-
26
- language_names = sorted(TO_LANGUAGE_CODE.keys())
27
- CHUNK_LENGTH_S = 30
28
- BATCH_SIZE = 16
29
- NUM_PROC = 16
30
- FILE_LIMIT_MB = 1000
31
-
32
-
33
- def query(payload):
34
- response = requests.post(API_URL, json=payload)
35
- return response.json(), response.status_code
36
-
37
-
38
- def inference(inputs, language=None, task=None, return_timestamps=False):
39
- payload = {"inputs": inputs, "task": task, "return_timestamps": return_timestamps}
40
-
41
- # langauge can come as an empty string from the Gradio `None` default, so we handle it separately
42
- if language:
43
- payload["language"] = language
44
-
45
- data, status_code = query(payload)
46
-
47
- if status_code == 200:
48
- text = data["text"]
49
- else:
50
- text = data["detail"]
51
-
52
- if return_timestamps:
53
- timestamps = data["chunks"]
54
- else:
55
- timestamps = None
56
-
57
- return text, timestamps
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
- if __name__ == "__main__":
76
- processor = WhisperPrePostProcessor.from_pretrained("openai/whisper-large-v2")
77
- pool = Pool(NUM_PROC)
78
-
79
- def transcribe_chunked_audio(inputs, task, return_timestamps):
80
- file_size_mb = os.stat(inputs).st_size / (1024 * 1024)
81
- if file_size_mb > FILE_LIMIT_MB:
82
- return f"ERROR: File size exceeds file size limit. Got file of size {file_size_mb:.2f}MB for a limit of {FILE_LIMIT_MB}MB.", None
83
-
84
- with open(inputs, "rb") as f:
85
- inputs = f.read()
86
-
87
- inputs = ffmpeg_read(inputs, processor.feature_extractor.sampling_rate)
88
- inputs = {"array": inputs, "sampling_rate": processor.feature_extractor.sampling_rate}
89
-
90
- dataloader = processor.preprocess_batch(inputs, chunk_length_s=CHUNK_LENGTH_S, batch_size=BATCH_SIZE)
91
-
92
- try:
93
- model_outputs = pool.map(partial(forward, task=task, return_timestamps=return_timestamps), dataloader)
94
- except ValueError as err:
95
- # pre-processor does all the necessary compatibility checks for our audio inputs
96
- return err, None
97
-
98
- post_processed = processor.postprocess(model_outputs, return_timestamps=return_timestamps)
99
- timestamps = post_processed.get("chunks")
100
- return post_processed["text"], timestamps
101
-
102
- def _return_yt_html_embed(yt_url):
103
- video_id = yt_url.split("?v=")[-1]
104
- HTML_str = (
105
- f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
106
- " </center>"
107
- )
108
- return HTML_str
109
-
110
- def transcribe_youtube(yt_url, task, return_timestamps):
111
- html_embed_str = _return_yt_html_embed(yt_url)
112
-
113
- text, timestamps = inference(inputs=yt_url, task=task, return_timestamps=return_timestamps)
114
-
115
- return html_embed_str, text, timestamps
116
-
117
- microphone_chunked = gr.Interface(
118
- fn=transcribe_chunked_audio,
119
- inputs=[
120
- gr.inputs.Audio(source="microphone", optional=True, type="filepath"),
121
- gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
122
- gr.inputs.Checkbox(default=False, label="Return timestamps"),
123
- ],
124
- outputs=[
125
- gr.outputs.Textbox(label="Transcription"),
126
- gr.outputs.Textbox(label="Timestamps"),
127
- ],
128
- allow_flagging="never",
129
- title=title,
130
- description=description,
131
- article=article,
132
- )
133
-
134
- audio_chunked = gr.Interface(
135
- fn=transcribe_chunked_audio,
136
- inputs=[
137
- gr.inputs.Audio(source="upload", optional=True, label="Audio file", type="filepath"),
138
- gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
139
- gr.inputs.Checkbox(default=False, label="Return timestamps"),
140
- ],
141
- outputs=[
142
- gr.outputs.Textbox(label="Transcription"),
143
- gr.outputs.Textbox(label="Timestamps"),
144
- ],
145
- allow_flagging="never",
146
- title=title,
147
- description=description,
148
- article=article,
149
- )
150
-
151
- youtube = gr.Interface(
152
- fn=transcribe_youtube,
153
- inputs=[
154
- gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
155
- gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
156
- gr.inputs.Checkbox(default=False, label="Return timestamps"),
157
- ],
158
- outputs=[
159
- gr.outputs.HTML(label="Video"),
160
- gr.outputs.Textbox(label="Transcription"),
161
- gr.outputs.Textbox(label="Timestamps"),
162
- ],
163
- allow_flagging="never",
164
- title=title,
165
- examples=[["https://www.youtube.com/watch?v=m8u-18Q0s7I", "transcribe", False]],
166
- cache_examples=False,
167
- description=description,
168
- article=article,
169
- )
170
-
171
- demo = gr.Blocks()
172
-
173
- with demo:
174
- gr.TabbedInterface([microphone_chunked, audio_chunked, youtube], ["Microphone", "Audio File", "YouTube"])
175
-
176
- demo.queue(max_size=3)
177
- demo.launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
nginx.conf ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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://whisper-jax.ngrok.io;
11
+ proxy_set_header Host whisper-jax.ngrok.io;
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 DELETED
@@ -1 +0,0 @@
1
- ffmpeg
 
 
processing_whisper.py DELETED
@@ -1,145 +0,0 @@
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}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,3 +0,0 @@
1
- transformers
2
- pytube
3
- requests>=2.28.2
 
 
 
 
run.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ service nginx start
4
+ sleep infinity