Download app.py from lanceyen/TestTTS: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/lanceyen/TestTTS/resolve/main/app.py
- Command line
-
hf download hf://spaces/lanceyen/TestTTS/app.py
-
curl -L -o app.py https://huggingface.co/spaces/lanceyen/TestTTS/resolve/main/app.py
10.1 kB
| """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 | |
| 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 | |
| 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") | |
| ]} | |
| 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() | |