Files
syops/backend/app/api/speech/__init__.py
T
2026-09-28 14:52:28 +08:00

46 lines
1.4 KiB
Python

"""
backend/app/api/speech/__init__.py
用途:语音转写 API,将音频转发至 SiliconFlow ASR。
依赖:app.core.auth.jwt、SpeechAsrService。
逻辑:register_blueprints 挂载 /api/speech;需登录后上传 audio/file。
"""
from flask import Blueprint, jsonify, request
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
from app.services.speech_asr import SpeechAsrService
speech_bp = Blueprint('speech', __name__)
@speech_bp.route('/transcribe', methods=['POST'])
def transcribe_audio():
user = get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
uploaded = request.files.get('audio') or request.files.get('file')
if not uploaded or not uploaded.filename:
raise ValidationError('audio file is required')
audio_bytes = uploaded.read()
filename = uploaded.filename or 'recording.webm'
content_type = uploaded.content_type or ''
try:
SpeechAsrService.validate_upload(filename, len(audio_bytes))
except ValueError as exc:
raise ValidationError(str(exc)) from exc
try:
text, model = SpeechAsrService.transcribe(audio_bytes, filename, content_type)
except RuntimeError as exc:
raise ServiceUnavailableError(str(exc)) from exc
return jsonify({
'text': text,
'model': model,
})