# SPDX-License-Identifier: CC-BY-NC-4.0 """An OpenAI-compatible speech-to-text server for this model. Every request goes through the model's own decoder, model.transcribe() (beam search, then the CTC rescoring pass), so the server returns the transcripts a direct call returns. pip install torch "transformers==5.14.1" librosa soundfile julius fastapi uvicorn python-multipart python server.py --model # one GPU; --port 8000, --host 127.0.0.1 curl http://127.0.0.1:8000/v1/audio/transcriptions -F file=@audio.wav POST /v1/audio/transcriptions, a multipart form: file the audio (any format soundfile reads, else librosa; any sampling rate; mono or stereo) model any value (the server runs one model) language "ar" or left out response_format json (default) {"text"}, text (plain text) or verbose_json {"text", "language", "duration", "words"} timestamp_granularities[] word: verbose_json gets "words": [{"word", "start", "end"}] in seconds (null when the transcript cannot be aligned to the audio) digits, latin this model's output switches, true or false (default false: the model card's setting) confidence true adds "confidence", a score from 0 to 1 (null for audio over 35 s or a few samples) A prompt, a temperature above 0, stream=true, segment timestamps and the srt / vtt formats get an error (400); other fields are ignored. GET /health answers 200 once the model is loaded; GET /v1/models lists the served name. Batching: up to --max-batch waiting requests with the same digits / latin setting go through one transcribe() call, the oldest one and those closest to it in length; once the GPU is free, the batcher waits --max-wait-ms for more requests to join. GET /health also counts the requests and batches decoded so far. In bfloat16 a few transcripts can change with the other clips of their batch (padding changes the arithmetic slightly); --max-batch 1 decodes every request alone, as a direct call on one file does. """ from __future__ import annotations import argparse import asyncio import contextlib import functools import math import re import sys import tempfile from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from dataclasses import dataclass from pathlib import Path import numpy as np import torch import uvicorn from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, PlainTextResponse from starlette.datastructures import UploadFile from transformers import AutoModelForSpeechSeq2Seq SAMPLE_RATE = 16000 TRUE, FALSE = ("true", "1", "yes", "on"), ("false", "0", "no", "off", "") class BadRequest(Exception): def __init__(self, message: str, param: str | None = None): super().__init__(message) self.param = param @dataclass(eq=False) class Job: wave: np.ndarray digits: bool latin: bool words: bool confidence: bool future: asyncio.Future class Batcher: """Decodes waiting requests together, one model.transcribe() call at a time on a thread that owns the GPU. A batch is the oldest waiting request plus up to max_batch - 1 others with its digits / latin setting, the closest to it in length (less padding). Once a request is waiting and the GPU is free, others are awaited for max_wait seconds.""" def __init__(self, model, max_batch: int, max_wait: float): self.model, self.max_batch, self.max_wait = model, max_batch, max_wait self.waiting: list[Job] = [] self.wake = asyncio.Event() self.gpu = ThreadPoolExecutor(max_workers=1) self.requests = self.batches = 0 async def submit(self, wave: np.ndarray, digits: bool, latin: bool, words: bool, confidence: bool) -> dict: job = Job(wave, digits, latin, words, confidence, asyncio.get_running_loop().create_future()) self.waiting.append(job) self.wake.set() return await job.future def take(self) -> list[Job]: first = self.waiting[0] same = [j for j in self.waiting[1:] if (j.digits, j.latin) == (first.digits, first.latin)] same.sort(key=lambda j: abs(len(j.wave) - len(first.wave))) batch = [first, *same[: self.max_batch - 1]] self.waiting = [j for j in self.waiting if j not in batch] if not self.waiting: self.wake.clear() return batch async def run(self) -> None: loop = asyncio.get_running_loop() while True: await self.wake.wait() deadline = loop.time() + self.max_wait while len(self.waiting) < self.max_batch: left = deadline - loop.time() if left <= 0: break self.wake.clear() with contextlib.suppress(TimeoutError): await asyncio.wait_for(self.wake.wait(), left) self.wake.set() batch = self.take() call = functools.partial( self.model.transcribe, [j.wave for j in batch], batch_size=self.max_batch, digits=batch[0].digits, latin=batch[0].latin, word_timestamps=any(j.words for j in batch), confidence=any(j.confidence for j in batch), ) try: out = await loop.run_in_executor(self.gpu, call) except Exception as e: # for example out of GPU memory: every request of the batch fails out = [e] * len(batch) self.requests, self.batches = self.requests + len(batch), self.batches + 1 for job, res in zip(batch, out, strict=True): if job.future.done(): # the client went away continue if isinstance(res, Exception): job.future.set_exception(res) else: job.future.set_result(res if isinstance(res, dict) else {"text": res}) def read_audio(load_audio, data: bytes, filename: str) -> np.ndarray: """The upload as 16 kHz mono float32, read by the model's own loader from a file with the upload's extension, so the samples are the ones a direct call on the same file sees.""" if not data: raise BadRequest("the file is empty", "file") suffix = "".join(re.findall(r"\.[A-Za-z0-9]{1,8}$", filename or "")) with tempfile.NamedTemporaryFile(suffix=suffix) as f: f.write(data) f.flush() try: wave = load_audio(f.name) except Exception as e: raise BadRequest(f"the file could not be read as audio ({type(e).__name__})", "file") from e if wave.size == 0: raise BadRequest("the audio holds no samples", "file") if not np.isfinite(wave).all(): raise BadRequest("the audio holds samples that are not finite numbers", "file") return wave def flag(form, name: str) -> bool: value = str(form.get(name, "")).strip().lower() if value not in TRUE + FALSE: raise BadRequest(f"{name} must be true or false, not {value!r}", name) return value in TRUE def build_app(model, served_name: str, max_batch: int, max_wait: float) -> FastAPI: load_audio = sys.modules[type(model).__module__].load_audio # the loader of the model's own code batcher = Batcher(model, max_batch, max_wait) @asynccontextmanager async def lifespan(app: FastAPI): task = asyncio.create_task(batcher.run()) yield task.cancel() app = FastAPI(title="speech-to-text", lifespan=lifespan) @app.exception_handler(BadRequest) async def bad_request(request: Request, e: BadRequest): error = {"message": str(e), "type": "invalid_request_error", "param": e.param, "code": None} return JSONResponse({"error": error}, status_code=400) @app.get("/health") async def health(): return { "status": "ok", "requests": batcher.requests, "batches": batcher.batches, "waiting": len(batcher.waiting), } @app.get("/v1/models") async def models(): return {"object": "list", "data": [{"id": served_name, "object": "model", "owned_by": "ai71"}]} @app.post("/v1/audio/transcriptions") async def transcriptions(request: Request): form = await request.form() upload = form.get("file") if not isinstance(upload, UploadFile): raise BadRequest("send the audio as the multipart file field `file`", "file") fmt = str(form.get("response_format") or "json") grains = set(form.getlist("timestamp_granularities[]") + form.getlist("timestamp_granularities")) if fmt not in ("json", "text", "verbose_json"): raise BadRequest( f"response_format {fmt!r} is not offered: use json, text or verbose_json", "response_format" ) if str(form.get("language") or "ar").lower() not in ("ar", "ara", "arabic"): raise BadRequest("this model transcribes Arabic only: send language=ar or leave it out", "language") if form.get("prompt"): raise BadRequest("a prompt is not supported by this model", "prompt") if str(form.get("temperature") or "0").strip() not in ("0", "0.0"): raise BadRequest("the decoder is deterministic (beam search): temperature must be 0", "temperature") if flag(form, "stream"): raise BadRequest("streaming is not supported", "stream") if grains - {"word"}: raise BadRequest("this model gives word timestamps only", "timestamp_granularities[]") if grains and fmt != "verbose_json": raise BadRequest("timestamp_granularities[] needs response_format=verbose_json", "response_format") digits, latin, conf = flag(form, "digits"), flag(form, "latin"), flag(form, "confidence") wave = await asyncio.to_thread(read_audio, load_audio, await upload.read(), upload.filename or "") res = await batcher.submit(wave, digits, latin, bool(grains), conf) if fmt == "text": return PlainTextResponse(res["text"]) out: dict = {"text": res["text"]} if fmt == "verbose_json": out = {"task": "transcribe", "language": "arabic", "duration": round(len(wave) / SAMPLE_RATE, 3), **out} if grains: out["words"] = res["words"] if conf: # None for audio over 35 s, and for a few samples of audio (no score to give) c = res["confidence"] out["confidence"] = c if c is not None and math.isfinite(c) else None return out return app def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--model", required=True, help="the model repository (or a local copy of it)") ap.add_argument("--served-name", help="the name /v1/models lists (default: --model, or a local folder's name)") ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=8000) ap.add_argument("--device", default="cuda", help="cuda, cuda:N or cpu (float32 on CPU)") ap.add_argument("--max-batch", type=int, default=16, help="requests decoded together (1: each one alone)") ap.add_argument("--max-wait-ms", type=float, default=10.0, help="how long a request waits for others") a = ap.parse_args() # On a GPU the weights load in their own bfloat16 (passing dtype=None would load float32 instead). cpu = {"dtype": torch.float32} if a.device == "cpu" else {} model = AutoModelForSpeechSeq2Seq.from_pretrained(a.model, trust_remote_code=True, **cpu).to(a.device).eval() model.transcribe(np.zeros(SAMPLE_RATE, dtype=np.float32)) # loads the processor and warms the GPU up print(f"model loaded on {a.device}, weights in {next(model.model.parameters()).dtype}", flush=True) name = a.served_name or (Path(a.model).name if Path(a.model).is_dir() else a.model) uvicorn.run(build_app(model, name, a.max_batch, a.max_wait_ms / 1000), host=a.host, port=a.port) if __name__ == "__main__": main()