Ashishkr commited on
Commit
a237091
1 Parent(s): cac64a7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +328 -0
app.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import time
4
+
5
+ import gradio as gr
6
+ import numpy as np
7
+ import torch
8
+ import yt_dlp as youtube_dl
9
+ from gradio_client import Client
10
+ from pyannote.audio import Pipeline
11
+ from transformers.pipelines.audio_utils import ffmpeg_read
12
+
13
+
14
+ YT_LENGTH_LIMIT_S = 36000 # limit to 1 hour YouTube files
15
+ SAMPLING_RATE = 16000
16
+
17
+ API_URL = "https://sanchit-gandhi-whisper-jax.hf.space/"
18
+ HF_TOKEN = os.environ.get("HF_TOKEN")
19
+
20
+ # set up the Gradio client
21
+ client = Client(API_URL)
22
+
23
+ # set up the diarization pipeline
24
+ diarization_pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token=HF_TOKEN)
25
+
26
+
27
+ def format_string(timestamp):
28
+ """
29
+ Reformat a timestamp string from (HH:)MM:SS to float seconds. Note that the hour column
30
+ is optional, and is appended within the function if not input.
31
+
32
+ Args:
33
+ timestamp (str):
34
+ Timestamp in string format, either MM:SS or HH:MM:SS.
35
+ Returns:
36
+ seconds (float):
37
+ Total seconds corresponding to the input timestamp.
38
+ """
39
+ split_time = timestamp.split(":")
40
+ split_time = [float(sub_time) for sub_time in split_time]
41
+
42
+ if len(split_time) == 2:
43
+ split_time.insert(0, 0)
44
+
45
+ seconds = split_time[0] * 3600 + split_time[1] * 60 + split_time[2]
46
+ return seconds
47
+
48
+
49
+ # Adapted from https://github.com/openai/whisper/blob/c09a7ae299c4c34c5839a76380ae407e7d785914/whisper/utils.py#L50
50
+ def format_timestamp(seconds: float, always_include_hours: bool = False, decimal_marker: str = "."):
51
+ """
52
+ Reformat a timestamp from a float of seconds to a string in format (HH:)MM:SS. Note that the hour
53
+ column is optional, and is appended in the function if the number of hours > 0.
54
+
55
+ Args:
56
+ seconds (float):
57
+ Total seconds corresponding to the input timestamp.
58
+ Returns:
59
+ timestamp (str):
60
+ Timestamp in string format, either MM:SS or HH:MM:SS.
61
+ """
62
+ if seconds is not None:
63
+ milliseconds = round(seconds * 1000.0)
64
+
65
+ hours = milliseconds // 3_600_000
66
+ milliseconds -= hours * 3_600_000
67
+
68
+ minutes = milliseconds // 60_000
69
+ milliseconds -= minutes * 60_000
70
+
71
+ seconds = milliseconds // 1_000
72
+ milliseconds -= seconds * 1_000
73
+
74
+ hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
75
+ return f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}"
76
+ else:
77
+ # we have a malformed timestamp so just return it as is
78
+ return seconds
79
+
80
+
81
+ def format_as_transcription(raw_segments):
82
+ return "\n\n".join(
83
+ [
84
+ f"{chunk['speaker']} [{format_timestamp(chunk['timestamp'][0])} -> {format_timestamp(chunk['timestamp'][1])}] {chunk['text']}"
85
+ for chunk in raw_segments
86
+ ]
87
+ )
88
+
89
+
90
+ def _return_yt_html_embed(yt_url):
91
+ video_id = yt_url.split("?v=")[-1]
92
+ HTML_str = (
93
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
94
+ " </center>"
95
+ )
96
+ return HTML_str
97
+
98
+
99
+ def download_yt_audio(yt_url, filename):
100
+ info_loader = youtube_dl.YoutubeDL()
101
+ try:
102
+ info = info_loader.extract_info(yt_url, download=False)
103
+ except youtube_dl.utils.DownloadError as err:
104
+ raise gr.Error(str(err))
105
+
106
+ file_length = info["duration_string"]
107
+ file_length_s = format_string(file_length)
108
+
109
+ if file_length_s > YT_LENGTH_LIMIT_S:
110
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
111
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
112
+ raise gr.Error(
113
+ f"To encourage fair usage of the demo, the maximum YouTube length is {yt_length_limit_hms}, "
114
+ f"got {file_length_hms} YouTube video."
115
+ )
116
+
117
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
118
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
119
+ try:
120
+ ydl.download([yt_url])
121
+ except youtube_dl.utils.ExtractorError as err:
122
+ raise gr.Error(str(err))
123
+
124
+
125
+ def align(transcription, segments, group_by_speaker=True):
126
+ transcription_split = transcription.split("\n")
127
+
128
+ # re-format transcription from string to List[Dict]
129
+ transcript = []
130
+ for chunk in transcription_split:
131
+ start_end, transcription = chunk[1:].split("] ")
132
+ start, end = start_end.split("->")
133
+
134
+ transcript.append({"timestamp": (format_string(start), format_string(end)), "text": transcription})
135
+
136
+ # diarizer output may contain consecutive segments from the same speaker (e.g. {(0 -> 1, speaker_1), (1 -> 1.5, speaker_1), ...})
137
+ # we combine these segments to give overall timestamps for each speaker's turn (e.g. {(0 -> 1.5, speaker_1), ...})
138
+ new_segments = []
139
+ prev_segment = cur_segment = segments[0]
140
+
141
+ for i in range(1, len(segments)):
142
+ cur_segment = segments[i]
143
+
144
+ # check if we have changed speaker ("label")
145
+ if cur_segment["label"] != prev_segment["label"] and i < len(segments):
146
+ # add the start/end times for the super-segment to the new list
147
+ new_segments.append(
148
+ {
149
+ "segment": {"start": prev_segment["segment"]["start"], "end": cur_segment["segment"]["start"]},
150
+ "speaker": prev_segment["label"],
151
+ }
152
+ )
153
+ prev_segment = segments[i]
154
+
155
+ # add the last segment(s) if there was no speaker change
156
+ new_segments.append(
157
+ {
158
+ "segment": {"start": prev_segment["segment"]["start"], "end": cur_segment["segment"]["end"]},
159
+ "speaker": prev_segment["label"],
160
+ }
161
+ )
162
+
163
+ # get the end timestamps for each chunk from the ASR output
164
+ end_timestamps = np.array([chunk["timestamp"][-1] for chunk in transcript])
165
+ segmented_preds = []
166
+
167
+ # align the diarizer timestamps and the ASR timestamps
168
+ for segment in new_segments:
169
+ # get the diarizer end timestamp
170
+ end_time = segment["segment"]["end"]
171
+ # find the ASR end timestamp that is closest to the diarizer's end timestamp and cut the transcript to here
172
+ upto_idx = np.argmin(np.abs(end_timestamps - end_time))
173
+
174
+ if group_by_speaker:
175
+ segmented_preds.append(
176
+ {
177
+ "speaker": segment["speaker"],
178
+ "text": "".join([chunk["text"] for chunk in transcript[: upto_idx + 1]]),
179
+ "timestamp": (transcript[0]["timestamp"][0], transcript[upto_idx]["timestamp"][1]),
180
+ }
181
+ )
182
+ else:
183
+ for i in range(upto_idx + 1):
184
+ segmented_preds.append({"speaker": segment["speaker"], **transcript[i]})
185
+
186
+ # crop the transcripts and timestamp lists according to the latest timestamp (for faster argmin)
187
+ transcript = transcript[upto_idx + 1 :]
188
+ end_timestamps = end_timestamps[upto_idx + 1 :]
189
+
190
+ # final post-processing
191
+ transcription = format_as_transcription(segmented_preds)
192
+ return transcription
193
+
194
+
195
+ def transcribe(audio_path, task="transcribe", group_by_speaker=True, progress=gr.Progress()):
196
+ # run Whisper JAX asynchronously using Gradio client (endpoint)
197
+ job = client.submit(
198
+ audio_path,
199
+ task,
200
+ True,
201
+ api_name="/predict_1",
202
+ )
203
+
204
+ # run diarization while we wait for Whisper JAX
205
+ progress(0, desc="Diarizing...")
206
+ diarization = diarization_pipeline(audio_path)
207
+ segments = diarization.for_json()["content"]
208
+
209
+ # only fetch the transcription result after performing diarization
210
+ progress(0.33, desc="Transcribing...")
211
+ transcription, _ = job.result()
212
+
213
+ # align the ASR transcriptions and diarization timestamps
214
+ progress(0.66, desc="Aligning...")
215
+ transcription = align(transcription, segments, group_by_speaker=group_by_speaker)
216
+
217
+ return transcription
218
+
219
+
220
+ def transcribe_yt(yt_url, task="transcribe", group_by_speaker=True, progress=gr.Progress()):
221
+ # run Whisper JAX asynchronously using Gradio client (endpoint)
222
+ job = client.submit(
223
+ yt_url,
224
+ task,
225
+ True,
226
+ api_name="/predict_2",
227
+ )
228
+
229
+ html_embed_str = _return_yt_html_embed(yt_url)
230
+ progress(0, desc="Downloading YouTube video...")
231
+ with tempfile.TemporaryDirectory() as tmpdirname:
232
+ filepath = os.path.join(tmpdirname, "video.mp4")
233
+ download_yt_audio(yt_url, filepath)
234
+ with open(filepath, "rb") as f:
235
+ inputs = f.read()
236
+
237
+ inputs = ffmpeg_read(inputs, SAMPLING_RATE)
238
+ inputs = torch.from_numpy(inputs).float()
239
+ inputs = inputs.unsqueeze(0)
240
+
241
+ # run diarization while we wait for Whisper JAX
242
+ progress(0.25, desc="Diarizing...")
243
+ diarization = diarization_pipeline(
244
+ {"waveform": inputs, "sample_rate": SAMPLING_RATE},
245
+ )
246
+ segments = diarization.for_json()["content"]
247
+
248
+ # only fetch the transcription result after performing diarization
249
+ progress(0.50, desc="Transcribing...")
250
+ _, transcription, _ = job.result()
251
+
252
+ # align the ASR transcriptions and diarization timestamps
253
+ progress(0.75, desc="Aligning...")
254
+ transcription = align(transcription, segments, group_by_speaker=group_by_speaker)
255
+
256
+ return html_embed_str, transcription
257
+
258
+
259
+ title = "Whisper JAX + Speaker Diarization ⚡️"
260
+
261
+ description = """Combine the speed of Whisper JAX with pyannote speaker diarization to transcribe meetings in super fast time. Demo uses Whisper JAX as an [endpoint](https://twitter.com/sanchitgandhi99/status/1656665496463495168) and pyannote speaker diarization running locally. The Whisper JAX endpoint is run asynchronously, meaning speaker diarization is run in parallel to the speech transcription. The diarized timestamps are aligned with the Whisper output to give the final speaker-segmented transcription.
262
+
263
+ To duplicate the demo, first accept the pyannote terms of use for the [speaker diarization](https://huggingface.co/pyannote/speaker-diarization) and [segmentation](https://huggingface.co/pyannote/segmentation) models. Then, click [here](https://huggingface.co/spaces/sanchit-gandhi/whisper-jax-diarization?duplicate=true) to duplicate the demo, and enter your Hugging Face access token as a Space secret when prompted.
264
+ """
265
+
266
+ article = "Whisper large-v2 model by OpenAI. Speaker diarization model by pyannote. Whisper JAX 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."
267
+
268
+ microphone = gr.Interface(
269
+ fn=transcribe,
270
+ inputs=[
271
+ gr.inputs.Audio(source="microphone", optional=True, type="filepath"),
272
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
273
+ gr.inputs.Checkbox(default=True, label="Group by speaker"),
274
+ ],
275
+ outputs=[
276
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
277
+ ],
278
+ allow_flagging="never",
279
+ title=title,
280
+ description=description,
281
+ article=article,
282
+ )
283
+
284
+ audio_file = gr.Interface(
285
+ fn=transcribe,
286
+ inputs=[
287
+ gr.inputs.Audio(source="upload", optional=True, label="Audio file", type="filepath"),
288
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
289
+ gr.inputs.Checkbox(default=True, label="Group by speaker"),
290
+ ],
291
+ outputs=[
292
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
293
+ ],
294
+ allow_flagging="never",
295
+ title=title,
296
+ description=description,
297
+ article=article,
298
+ )
299
+
300
+ youtube = gr.Interface(
301
+ fn=transcribe_yt,
302
+ inputs=[
303
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
304
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
305
+ gr.inputs.Checkbox(default=True, label="Group by speaker"),
306
+ ],
307
+ outputs=[
308
+ gr.outputs.HTML(label="Video"),
309
+ gr.outputs.Textbox(label="Transcription").style(show_copy_button=True),
310
+ ],
311
+ allow_flagging="never",
312
+ title=title,
313
+ examples=[
314
+ ["https://www.youtube.com/watch?v=m8u-18Q0s7I", "transcribe", True],
315
+ ["https://www.youtube.com/watch?v=LCOe3a9EHJs", "transcribe", True],
316
+ ],
317
+ cache_examples=False,
318
+ description=description,
319
+ article=article,
320
+ )
321
+
322
+ demo = gr.Blocks()
323
+
324
+ with demo:
325
+ gr.TabbedInterface([microphone, audio_file, youtube], ["Microphone", "Audio File", "YouTube"])
326
+
327
+ demo.queue(max_size=10)
328
+ demo.launch()