Afrinetwork7 commited on
Commit
c173d9b
1 Parent(s): 3af97c3

Create router.py

Browse files
Files changed (1) hide show
  1. router.py +191 -0
router.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import logging
3
+ import math
4
+ import tempfile
5
+ import time
6
+ from typing import Optional, Tuple
7
+
8
+ import fastapi
9
+ import jax.numpy as jnp
10
+ import numpy as np
11
+ import yt_dlp as youtube_dl
12
+ from jax.experimental.compilation_cache import compilation_cache as cc
13
+ from pydantic import BaseModel
14
+ from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE
15
+ from transformers.pipelines.audio_utils import ffmpeg_read
16
+
17
+ from whisper_jax import FlaxWhisperPipline
18
+
19
+ cc.initialize_cache("./jax_cache")
20
+ checkpoint = "openai/whisper-large-v3"
21
+
22
+ BATCH_SIZE = 32
23
+ CHUNK_LENGTH_S = 30
24
+ NUM_PROC = 32
25
+ FILE_LIMIT_MB = 10000
26
+ YT_LENGTH_LIMIT_S = 15000 # limit to 2 hour YouTube files
27
+
28
+ logger = logging.getLogger("whisper-jax-app")
29
+ logger.setLevel(logging.INFO)
30
+ ch = logging.StreamHandler()
31
+ ch.setLevel(logging.INFO)
32
+ formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s", "%Y-%m-%d %H:%M:%S")
33
+ ch.setFormatter(formatter)
34
+ logger.addHandler(ch)
35
+
36
+ pipeline = FlaxWhisperPipline(checkpoint, dtype=jnp.bfloat16, batch_size=BATCH_SIZE)
37
+ stride_length_s = CHUNK_LENGTH_S / 6
38
+ chunk_len = round(CHUNK_LENGTH_S * pipeline.feature_extractor.sampling_rate)
39
+ stride_left = stride_right = round(stride_length_s * pipeline.feature_extractor.sampling_rate)
40
+ step = chunk_len - stride_left - stride_right
41
+
42
+ # do a pre-compile step so that the first user to use the demo isn't hit with a long transcription time
43
+ logger.info("compiling forward call...")
44
+ start = time.time()
45
+ random_inputs = {
46
+ "input_features": np.ones(
47
+ (BATCH_SIZE, pipeline.model.config.num_mel_bins, 2 * pipeline.model.config.max_source_positions)
48
+ )
49
+ }
50
+ random_timestamps = pipeline.forward(random_inputs, batch_size=BATCH_SIZE, return_timestamps=True)
51
+ compile_time = time.time() - start
52
+ logger.info(f"compiled in {compile_time}s")
53
+
54
+ app = fastapi.FastAPI()
55
+
56
+ class TranscriptionRequest(BaseModel):
57
+ audio_file: str
58
+ task: str = "transcribe"
59
+ return_timestamps: bool = False
60
+
61
+ class TranscriptionResponse(BaseModel):
62
+ transcription: str
63
+ runtime: float
64
+
65
+ @app.post("/transcribe", response_model=TranscriptionResponse)
66
+ def transcribe_audio(request: TranscriptionRequest):
67
+ logger.info("loading audio file...")
68
+ if not request.audio_file:
69
+ logger.warning("No audio file")
70
+ raise fastapi.HTTPException(status_code=400, detail="No audio file submitted!")
71
+
72
+ audio_bytes = base64.b64decode(request.audio_file)
73
+ file_size_mb = len(audio_bytes) / (1024 * 1024)
74
+ if file_size_mb > FILE_LIMIT_MB:
75
+ logger.warning("Max file size exceeded")
76
+ raise fastapi.HTTPException(
77
+ status_code=400,
78
+ detail=f"File size exceeds file size limit. Got file of size {file_size_mb:.2f}MB for a limit of {FILE_LIMIT_MB}MB.",
79
+ )
80
+
81
+ inputs = ffmpeg_read(audio_bytes, pipeline.feature_extractor.sampling_rate)
82
+ inputs = {"array": inputs, "sampling_rate": pipeline.feature_extractor.sampling_rate}
83
+ logger.info("done loading")
84
+ text, runtime = _tqdm_generate(inputs, task=request.task, return_timestamps=request.return_timestamps)
85
+ return TranscriptionResponse(transcription=text, runtime=runtime)
86
+
87
+ @app.post("/transcribe_youtube")
88
+ def transcribe_youtube(
89
+ yt_url: str, task: str = "transcribe", return_timestamps: bool = False
90
+ ) -> Tuple[str, str, float]:
91
+ logger.info("loading youtube file...")
92
+ html_embed_str = _return_yt_html_embed(yt_url)
93
+ with tempfile.TemporaryDirectory() as tmpdirname:
94
+ filepath = os.path.join(tmpdirname, "video.mp4")
95
+ _download_yt_audio(yt_url, filepath)
96
+
97
+ with open(filepath, "rb") as f:
98
+ inputs = f.read()
99
+
100
+ inputs = ffmpeg_read(inputs, pipeline.feature_extractor.sampling_rate)
101
+ inputs = {"array": inputs, "sampling_rate": pipeline.feature_extractor.sampling_rate}
102
+ logger.info("done loading...")
103
+ text, runtime = _tqdm_generate(inputs, task=task, return_timestamps=return_timestamps)
104
+ return html_embed_str, text, runtime
105
+
106
+ def _tqdm_generate(inputs: dict, task: str, return_timestamps: bool, progress: Optional[fastapi.ProgressBar] = None):
107
+ inputs_len = inputs["array"].shape[0]
108
+ all_chunk_start_idx = np.arange(0, inputs_len, step)
109
+ num_samples = len(all_chunk_start_idx)
110
+ num_batches = math.ceil(num_samples / BATCH_SIZE)
111
+
112
+ dataloader = pipeline.preprocess_batch(inputs, chunk_length_s=CHUNK_LENGTH_S, batch_size=BATCH_SIZE)
113
+ model_outputs = []
114
+ start_time = time.time()
115
+ logger.info("transcribing...")
116
+ # iterate over our chunked audio samples - always predict timestamps to reduce hallucinations
117
+ for batch, _ in zip(dataloader, range(num_batches)):
118
+ model_outputs.append(pipeline.forward(batch, batch_size=BATCH_SIZE, task=task, return_timestamps=True))
119
+ runtime = time.time() - start_time
120
+ logger.info("done transcription")
121
+
122
+ logger.info("post-processing...")
123
+ post_processed = pipeline.postprocess(model_outputs, return_timestamps=True)
124
+ text = post_processed["text"]
125
+ if return_timestamps:
126
+ timestamps = post_processed.get("chunks")
127
+ timestamps = [
128
+ f"[{_format_timestamp(chunk['timestamp'][0])} -> {_format_timestamp(chunk['timestamp'][1])}] {chunk['text']}"
129
+ for chunk in timestamps
130
+ ]
131
+ text = "\n".join(str(feature) for feature in timestamps)
132
+ logger.info("done post-processing")
133
+ return text, runtime
134
+
135
+ def _return_yt_html_embed(yt_url: str) -> str:
136
+ video_id = yt_url.split("?v=")[-1]
137
+ HTML_str = (
138
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
139
+ " </center>"
140
+ )
141
+ return HTML_str
142
+
143
+ def _download_yt_audio(yt_url: str, filename: str):
144
+ info_loader = youtube_dl.YoutubeDL()
145
+ try:
146
+ info = info_loader.extract_info(yt_url, download=False)
147
+ except youtube_dl.utils.DownloadError as err:
148
+ raise fastapi.HTTPException(status_code=400, detail=str(err))
149
+
150
+ file_length = info["duration_string"]
151
+ file_h_m_s = file_length.split(":")
152
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
153
+ if len(file_h_m_s) == 1:
154
+ file_h_m_s.insert(0, 0)
155
+ if len(file_h_m_s) == 2:
156
+ file_h_m_s.insert(0, 0)
157
+
158
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
159
+ if file_length_s > YT_LENGTH_LIMIT_S:
160
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
161
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
162
+ raise fastapi.HTTPException(
163
+ status_code=400,
164
+ detail=f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.",
165
+ )
166
+
167
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
168
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
169
+ try:
170
+ ydl.download([yt_url])
171
+ except youtube_dl.utils.ExtractorError as err:
172
+ raise fastapi.HTTPException(status_code=400, detail=str(err))
173
+
174
+ def _format_timestamp(seconds: float, always_include_hours: bool = False, decimal_marker: str = "."):
175
+ if seconds is not None:
176
+ milliseconds = round(seconds * 1000.0)
177
+
178
+ hours = milliseconds // 3_600_000
179
+ milliseconds -= hours * 3_600_000
180
+
181
+ minutes = milliseconds // 60_000
182
+ milliseconds -= minutes * 60_000
183
+
184
+ seconds = milliseconds // 1_000
185
+ milliseconds -= seconds * 1_000
186
+
187
+ hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
188
+ return f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}"
189
+ else:
190
+ # we have a malformed timestamp so just return it as is
191
+ return seconds