Files
sophieandCursor 8f69131872 feat(chat): add SiliconFlow ASR for agent voice input
Replace Web Speech API with MediaRecorder upload to POST /api/speech/transcribe, calling SenseVoice via the existing GJL API credentials.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-03 19:24:35 +08:00

76 lines
2.6 KiB
Python

"""
SiliconFlow ASR service (OpenAI-compatible /v1/audio/transcriptions).
"""
import io
import os
from typing import Tuple
ALLOWED_AUDIO_EXTENSIONS = frozenset({
'webm', 'wav', 'mp3', 'm4a', 'mp4', 'mpeg', 'mpga', 'ogg',
})
MAX_AUDIO_BYTES = int(os.getenv('ASR_MAX_AUDIO_BYTES', str(10 * 1024 * 1024)))
class SpeechAsrService:
@classmethod
def _get_client(cls):
try:
from openai import OpenAI
except ImportError as exc:
raise RuntimeError('OpenAI SDK not installed') from exc
api_key = (os.getenv('GJL_API_KEY') or '').strip()
base_url = (os.getenv('GJL_API_BASE') or 'https://api.siliconflow.cn/v1').strip()
if not api_key:
raise RuntimeError('Missing GJL_API_KEY. Configure it in .env to enable speech recognition')
return OpenAI(api_key=api_key, base_url=base_url)
@classmethod
def _resolve_model(cls) -> str:
return (os.getenv('ASR_MODEL') or 'FunAudioLLM/SenseVoiceSmall').strip()
@classmethod
def _normalize_filename(cls, filename: str, content_type: str) -> str:
name = (filename or '').strip() or 'recording.webm'
if '.' not in name:
if 'wav' in content_type:
name = f'{name}.wav'
elif 'mp4' in content_type or 'm4a' in content_type:
name = f'{name}.m4a'
else:
name = f'{name}.webm'
return name
@classmethod
def validate_upload(cls, filename: str, size: int) -> None:
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
if ext and ext not in ALLOWED_AUDIO_EXTENSIONS:
raise ValueError(f'Unsupported audio format: .{ext}')
if size <= 0:
raise ValueError('Audio file is empty')
if size > MAX_AUDIO_BYTES:
raise ValueError(f'Audio file exceeds {MAX_AUDIO_BYTES // (1024 * 1024)}MB limit')
@classmethod
def transcribe(cls, audio_bytes: bytes, filename: str, content_type: str = '') -> Tuple[str, str]:
cls.validate_upload(filename, len(audio_bytes))
client = cls._get_client()
model = cls._resolve_model()
safe_name = cls._normalize_filename(filename, content_type)
file_obj = io.BytesIO(audio_bytes)
file_obj.name = safe_name
try:
result = client.audio.transcriptions.create(
model=model,
file=file_obj,
)
except Exception as exc:
raise RuntimeError(f'Speech recognition request failed: {exc}') from exc
text = str(getattr(result, 'text', '') or '').strip()
return text, model