File size: 10,062 Bytes
3e1b2a1 ee34e08 3e1b2a1 ce527af 3e1b2a1 ee34e08 3e1b2a1 60d8111 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ce527af ee34e08 ce527af 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 ce527af 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 60d8111 ee34e08 3e1b2a1 ee34e08 60d8111 ee34e08 60d8111 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 3e1b2a1 ee34e08 60d8111 5b87961 60d8111 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | """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: /transcribe
The 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 hashlib
import hmac
import os
import tempfile
import threading
import time
from collections import defaultdict, deque
import gradio as gr
import librosa
import spaces
import torch
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import JSONResponse, PlainTextResponse
from transformers import pipeline
MODEL_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 ""
API_KEY_HASH = _load_key_hash()
if not API_KEY_HASH:
print("WARNING: no API key configured - every request will be rejected.")
asr = pipeline(
"automatic-speech-recognition",
model=MODEL_ID,
torch_dtype=torch.float16,
device="cuda",
)
# ---------------------------------------------------------------- auth / limits
class AuthError(Exception):
pass
class 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 attempts
raise 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) / 16000
if 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 REST
api = APIRouter()
_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
@api.get("/v1/models")
def list_models(request: Request):
if (err := _auth_rest(request)) is not None:
return err
return {"object": "list", "data": [
{"id": m, "object": "model", "owned_by": "MediaTek-Research"}
for m in ("breeze-asr-25", "whisper-1")
]}
@api.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 err
data = 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.name
fmt = (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: BLE001
print("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 / API
def 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 quota
except (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="音檔")
key_in = gr.Textbox(label="API Key", type="password")
ts_in = gr.Checkbox(label="回傳時間戳記", value=False)
btn = gr.Button("辨識", variant="primary")
with gr.Column():
text_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)
# Must start via demo.launch() so ZeroGPU detects @spaces.GPU; then attach the
# OpenAI-compatible routes to Gradio's own FastAPI app (inserted first so they win).
demo.launch(prevent_thread_lock=True, ssr_mode=False) # SSR proxy would swallow /v1 routes
for route in reversed(api.routes):
demo.app.router.routes.insert(0, route)
print("OpenAI-compatible routes ready:", [r.path for r in api.routes])
demo.block_thread()
|