Add OpenAI Whisper-compatible /v1/audio/transcriptions endpoint
Browse files12345678910111213141 unmodified line161718192021222324252627282930313233343 unmodified lines383940414243441 unmodified line4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171184 unmodified lines123124125126127128129130131132133"""Breeze-ASR-25 speech-to-text API on Hugging Face ZeroGPU, protected by an API key.The key is read from the Space secret `API_KEY` (never stored in the repo).Clients send it as:- HTTP header `X-API-Key: <key>` or `Authorization: Bearer <key>`, or- the `api_key` input of the /transcribe endpoint."""import hashlibimport hmacimport osimport timefrom collections import defaultdict, deque1 unmodified lineimport librosaimport spacesimport torchfrom transformers import pipelineMODEL_ID = "MediaTek-Research/Breeze-ASR-25"MAX_AUDIO_SECONDS = int(os.environ.get("MAX_AUDIO_SECONDS", "600"))RATE_LIMIT_PER_MIN = int(os.environ.get("RATE_LIMIT_PER_MIN", "20"))def _load_key_hash() -> str:"""SHA-256 of the API key: from the API_KEY secret if set, else api_key.sha256 in the repo."""if os.environ.get("API_KEY"):return hashlib.sha256(os.environ["API_KEY"].encode()).hexdigest()try:with open(os.path.join(os.path.dirname(__file__), "api_key.sha256")) as f:return f.read().strip().lower()except OSError:return ""3 unmodified linesif not API_KEY_HASH:print("WARNING: no API key configured - every request will be rejected.")# Load on CPU at startup; ZeroGPU moves it to the GPU inside @spaces.GPU calls.asr = pipeline("automatic-speech-recognition",model=MODEL_ID,1 unmodified linedevice="cuda",)_hits: dict[str, deque] = defaultdict(deque)def _extract_key(api_key: str | None, request: gr.Request | None) -> str:if api_key:return api_key.strip()if request is not None:headers = {k.lower(): v for k, v in dict(request.headers).items()}if headers.get("x-api-key"):return headers["x-api-key"].strip()auth = headers.get("authorization", "")if auth.lower().startswith("bearer "):return auth[7:].strip()return ""def _check_auth(api_key: str | None, request: gr.Request | None) -> None:supplied = _extract_key(api_key, request)supplied_hash = hashlib.sha256(supplied.encode()).hexdigest()if not API_KEY_HASH or not supplied or not hmac.compare_digest(supplied_hash, API_KEY_HASH):time.sleep(1) # slow down brute-force attemptsraise gr.Error("Unauthorized: invalid or missing API key.", print_exception=False)# Simple per-key-holder rate limit (by client IP).ip = getattr(getattr(request, "client", None), "host", None) or "unknown"now = time.time()q = _hits[ip]while q and now - q[0] > 60:q.popleft()if len(q) >= RATE_LIMIT_PER_MIN:raise gr.Error("Rate limit exceeded, try again in a minute.", print_exception=False)q.append(now)@spaces.GPU(duration=120)def _run_asr(audio, return_timestamps: bool):out = asr({"raw": audio, "sampling_rate": 16000},chunk_length_s=30,batch_size=8,return_timestamps=return_timestamps,generate_kwargs={"language": "zh", "task": "transcribe"},)return outdef transcribe(audio_path, api_key="", return_timestamps=False, request: gr.Request = None):"""Transcribe an audio file (Mandarin / Taiwanese-accented / zh-en code-switching)."""_check_auth(api_key, request) # runs on CPU -> unauthorized calls never use GPU quotaif not audio_path:raise gr.Error("No audio provided.")audio, _ = librosa.load(audio_path, sr=16000, mono=True)duration = len(audio) / 16000if duration > MAX_AUDIO_SECONDS:raise gr.Error(f"Audio too long ({duration:.0f}s). Max is {MAX_AUDIO_SECONDS}s.")out = _run_asr(audio, bool(return_timestamps))chunks = [{"start": c["timestamp"][0], "end": c["timestamp"][1], "text": c["text"]}for c in out.get("chunks", [])] if return_timestamps else []return out["text"].strip(), {"duration_sec": round(duration, 2), "chunks": chunks}with gr.Blocks(title="Breeze-ASR-25 API") as demo:gr.Markdown("# Breeze-ASR-25 語音辨識 API\n需要 API Key 才能使用。")with gr.Row():with gr.Column():audio_in = gr.Audio(sources=["upload", "microphone"], type="filepath", label="音檔")4 unmodified linestext_out = gr.Textbox(label="辨識結果", lines=8)json_out = gr.JSON(label="詳細資訊")btn.click(transcribe,inputs=[audio_in, key_in, ts_in],outputs=[text_out, json_out],api_name="transcribe",concurrency_limit=2,)demo.queue(max_size=20).launch()123456789101112131415161718191 unmodified line212223242526272829303132333435363738394041423 unmodified lines4647484950511 unmodified line53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472484 unmodified lines253254255256257258259260261262263264265266267"""Breeze-ASR-25 speech-to-text API on Hugging Face ZeroGPU, protected by an API key.Two interfaces, same key:1. OpenAI Whisper-compatible REST: POST /v1/audio/transcriptions(Authorization: Bearer <key>, multipart form field `file`)2. Gradio API / web UI: /transcribeThe key is checked against a SHA-256 hash (Space secret `API_KEY` if set,otherwise the `api_key.sha256` file); the plaintext key is never in the repo."""import hashlibimport hmacimport osimport tempfileimport threadingimport timefrom collections import defaultdict, deque1 unmodified lineimport librosaimport spacesimport torchimport uvicornfrom fastapi import FastAPI, File, Form, HTTPException, Request, UploadFilefrom fastapi.responses import JSONResponse, PlainTextResponsefrom transformers import pipelineMODEL_ID = "MediaTek-Research/Breeze-ASR-25"MAX_AUDIO_SECONDS = int(os.environ.get("MAX_AUDIO_SECONDS", "600"))MAX_UPLOAD_MB = int(os.environ.get("MAX_UPLOAD_MB", "50"))RATE_LIMIT_PER_MIN = int(os.environ.get("RATE_LIMIT_PER_MIN", "20"))def _load_key_hash() -> str:if os.environ.get("API_KEY"):return hashlib.sha256(os.environ["API_KEY"].encode()).hexdigest()try:with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "api_key.sha256")) as f:return f.read().strip().lower()except OSError:return ""3 unmodified linesif not API_KEY_HASH:print("WARNING: no API key configured - every request will be rejected.")asr = pipeline("automatic-speech-recognition",model=MODEL_ID,1 unmodified linedevice="cuda",)# ---------------------------------------------------------------- auth / limitsclass AuthError(Exception):passclass RateLimitError(Exception):pass_hits: dict[str, deque] = defaultdict(deque)_hits_lock = threading.Lock()def _headers_key(headers) -> str:h = {k.lower(): v for k, v in dict(headers).items()}if h.get("x-api-key"):return h["x-api-key"].strip()auth = h.get("authorization", "")if auth.lower().startswith("bearer "):return auth[7:].strip()return ""def _client_ip(headers, client) -> str:h = {k.lower(): v for k, v in dict(headers).items()}fwd = h.get("x-forwarded-for", "")if fwd:return fwd.split(",")[0].strip()return getattr(client, "host", None) or "unknown"def check_auth(supplied: str, ip: str) -> None:supplied = (supplied or "").strip()supplied_hash = hashlib.sha256(supplied.encode()).hexdigest()if not API_KEY_HASH or not supplied or not hmac.compare_digest(supplied_hash, API_KEY_HASH):time.sleep(1) # slow down brute-force attemptsraise AuthError("Invalid or missing API key.")now = time.time()with _hits_lock:q = _hits[ip]while q and now - q[0] > 60:q.popleft()if len(q) >= RATE_LIMIT_PER_MIN:raise RateLimitError("Rate limit exceeded, try again in a minute.")q.append(now)# ---------------------------------------------------------------- inference@spaces.GPU(duration=120)def _run_asr(audio, return_timestamps: bool, language: str):return asr({"raw": audio, "sampling_rate": 16000},chunk_length_s=30,batch_size=8,return_timestamps=return_timestamps,generate_kwargs={"language": language, "task": "transcribe"},)def transcribe_file(path: str, return_timestamps: bool = False, language: str = "zh") -> dict:audio, _ = librosa.load(path, sr=16000, mono=True)duration = len(audio) / 16000if duration > MAX_AUDIO_SECONDS:raise ValueError(f"Audio too long ({duration:.0f}s). Max is {MAX_AUDIO_SECONDS}s.")out = _run_asr(audio, return_timestamps, language or "zh")segments = []if return_timestamps:for i, c in enumerate(out.get("chunks", [])):start, end = c["timestamp"]segments.append({"id": i, "start": start, "end": end if end is not None else duration,"text": c["text"].strip()})return {"text": out["text"].strip(), "duration": round(duration, 2), "segments": segments}# ---------------------------------------------------------------- OpenAI-compatible RESTapp = FastAPI(title="Breeze-ASR-25 API", docs_url=None, redoc_url=None, openapi_url=None)_gpu_slots = threading.Semaphore(2)def _srt_time(t: float, sep: str) -> str:ms = int(round((t or 0) * 1000))h, ms = divmod(ms, 3600000)m, ms = divmod(ms, 60000)s, ms = divmod(ms, 1000)return f"{h:02}:{m:02}:{s:02}{sep}{ms:03}"def _openai_error(status: int, message: str, typ: str) -> JSONResponse:return JSONResponse(status_code=status, content={"error": {"message": message, "type": typ}})def _auth_rest(request: Request):try:check_auth(_headers_key(request.headers), _client_ip(request.headers, request.client))except AuthError as e:return _openai_error(401, str(e), "invalid_request_error")except RateLimitError as e:return _openai_error(429, str(e), "rate_limit_error")return None@app.get("/v1/models")def list_models(request: Request):if (err := _auth_rest(request)) is not None:return errreturn {"object": "list", "data": [{"id": m, "object": "model", "owned_by": "MediaTek-Research"}for m in ("breeze-asr-25", "whisper-1")]}@app.post("/v1/audio/transcriptions")def openai_transcriptions(request: Request,file: UploadFile = File(...),model: str = Form("breeze-asr-25"),language: str = Form("zh"),prompt: str = Form(None),response_format: str = Form("json"),temperature: float = Form(0.0),):if (err := _auth_rest(request)) is not None:return errdata = file.file.read(MAX_UPLOAD_MB * 1024 * 1024 + 1)if len(data) > MAX_UPLOAD_MB * 1024 * 1024:return _openai_error(413, f"File larger than {MAX_UPLOAD_MB} MB.", "invalid_request_error")suffix = os.path.splitext(file.filename or "")[1] or ".wav"with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:tmp.write(data)path = tmp.namefmt = (response_format or "json").lower()need_ts = fmt in ("verbose_json", "srt", "vtt")try:if not _gpu_slots.acquire(timeout=300):return _openai_error(503, "Server busy, try again later.", "server_error")try:result = transcribe_file(path, need_ts, language)finally:_gpu_slots.release()except ValueError as e:return _openai_error(400, str(e), "invalid_request_error")except Exception as e: # noqa: BLE001print("transcription error:", repr(e))return _openai_error(500, f"Transcription failed: {type(e).__name__}", "server_error")finally:os.unlink(path)if fmt == "text":return PlainTextResponse(result["text"])if fmt == "srt":body = "\n".join(f"{i + 1}\n{_srt_time(s['start'], ',')} --> {_srt_time(s['end'], ',')}\n{s['text']}\n"for i, s in enumerate(result["segments"]))return PlainTextResponse(body)if fmt == "vtt":body = "WEBVTT\n\n" + "\n".join(f"{_srt_time(s['start'], '.')} --> {_srt_time(s['end'], '.')}\n{s['text']}\n"for s in result["segments"])return PlainTextResponse(body)if fmt == "verbose_json":return {"task": "transcribe", "language": language, "duration": result["duration"],"text": result["text"], "segments": result["segments"]}return {"text": result["text"]}# ---------------------------------------------------------------- Gradio UI / APIdef gradio_transcribe(audio_path, api_key="", return_timestamps=False, request: gr.Request = None):"""Transcribe an audio file (Mandarin / Taiwanese-accented / zh-en code-switching)."""supplied = api_key or (_headers_key(request.headers) if request else "")ip = _client_ip(request.headers, request.client) if request else "unknown"try:check_auth(supplied, ip) # runs on CPU -> unauthorized calls never use GPU quotaexcept (AuthError, RateLimitError) as e:raise gr.Error(f"Unauthorized: {e}" if isinstance(e, AuthError) else str(e), print_exception=False)if not audio_path:raise gr.Error("No audio provided.")try:r = transcribe_file(audio_path, bool(return_timestamps))except ValueError as e:raise gr.Error(str(e))chunks = [{"start": s["start"], "end": s["end"], "text": s["text"]} for s in r["segments"]]return r["text"], {"duration_sec": r["duration"], "chunks": chunks}with gr.Blocks(title="Breeze-ASR-25 API") as demo:gr.Markdown("# Breeze-ASR-25 語音辨識 API\n需要 API Key 才能使用。\n\n""OpenAI 相容端點:`POST /v1/audio/transcriptions`(Base URL:本站網址 + `/v1`)")with gr.Row():with gr.Column():audio_in = gr.Audio(sources=["upload", "microphone"], type="filepath", label="音檔")4 unmodified linestext_out = gr.Textbox(label="辨識結果", lines=8)json_out = gr.JSON(label="詳細資訊")btn.click(gradio_transcribe,inputs=[audio_in, key_in, ts_in],outputs=[text_out, json_out],api_name="transcribe",concurrency_limit=2,)demo.queue(max_size=20)app = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+184-50