"""语音转写端点""" import os import uuid import logging from fastapi import APIRouter, UploadFile, File, HTTPException from pydantic import BaseModel from typing import Optional from app.audio.transcriber import transcribe_audio logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/v1", tags=["audio"]) MAX_FILE_SIZE = 5 * 1024 * 1024 UPLOAD_DIR = "/tmp/stt_uploads" class TranscribeResponse(BaseModel): code: int = 200 message: str = "ok" data: Optional[dict] = None @router.post("/audio/transcribe", response_model=TranscribeResponse) async def transcribe(file: UploadFile = File(...)): if not file.filename or not file.filename.lower().endswith((".mp3", ".wav", ".m4a", ".flac", ".ogg")): raise HTTPException(status_code=400, detail="不支持的音频格式,仅支持 mp3/wav/m4a/flac/ogg") content = await file.read() if len(content) > MAX_FILE_SIZE: raise HTTPException(status_code=413, detail="音频文件过大(最大 5MB)") if len(content) < 1000: raise HTTPException(status_code=400, detail="音频文件为空或过短") os.makedirs(UPLOAD_DIR, exist_ok=True) ext = file.filename.rsplit(".", 1)[-1] tmp_path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4().hex}.{ext}") try: with open(tmp_path, "wb") as f: f.write(content) result = transcribe_audio(tmp_path) return TranscribeResponse(data=result) except Exception as e: logger.error("转写失败: %s", e, exc_info=True) return TranscribeResponse(code=500, message="转写失败: " + str(e), data={}) finally: try: os.remove(tmp_path) except OSError: pass