From 8f69131872cbe5c032d3159b6b91b5c9d3f05588 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Wed, 3 Jun 2026 19:24:35 +0800 Subject: [PATCH] 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 --- .env.shared | 2 + backend/app/__init__.py | 2 + backend/app/api/speech.py | 40 ++++ backend/app/services/speech_asr.py | 75 +++++++ .../src/composables/useAudioTranscription.ts | 204 ++++++++++++++++++ .../src/composables/useSpeechRecognition.ts | 156 -------------- frontend/src/i18n.ts | 12 ++ frontend/src/types/speech-recognition.d.ts | 45 ---- frontend/src/views/ChatView.vue | 29 +-- 9 files changed, 350 insertions(+), 215 deletions(-) create mode 100644 backend/app/api/speech.py create mode 100644 backend/app/services/speech_asr.py create mode 100644 frontend/src/composables/useAudioTranscription.ts delete mode 100644 frontend/src/composables/useSpeechRecognition.ts delete mode 100644 frontend/src/types/speech-recognition.d.ts diff --git a/.env.shared b/.env.shared index a1620261..cf21c3e2 100644 --- a/.env.shared +++ b/.env.shared @@ -68,6 +68,8 @@ DIFY_API_BASE=https://api.dify.ai/v1 GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu GJL_API_BASE=https://api.siliconflow.cn/v1 GJL_MODEL=deepseek-ai/DeepSeek-V3 +# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR +ASR_MODEL=FunAudioLLM/SenseVoiceSmall # HR SQL Server Configuration HR_SQLSERVER_HOST=192.168.100.191 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index f7762e24..0f67bc06 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -56,6 +56,7 @@ def create_app(config_name='default'): from app.api.schedule_admin import schedule_admin_bp from app.api.workspace_schedule import workspace_schedule_bp from app.api.internal_jobs import internal_jobs_bp + from app.api.speech import speech_bp # 聊天相关接口 app.register_blueprint(chat_bp, url_prefix='/api/chat') @@ -72,6 +73,7 @@ def create_app(config_name='default'): app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') + app.register_blueprint(speech_bp, url_prefix='/api/speech') # Eagerly load persisted runtime settings so the very first request after # a worker boot already sees the admin-saved configuration (otherwise the diff --git a/backend/app/api/speech.py b/backend/app/api/speech.py new file mode 100644 index 00000000..95e9d0d2 --- /dev/null +++ b/backend/app/api/speech.py @@ -0,0 +1,40 @@ +""" +Speech transcription API — forwards audio to SiliconFlow ASR. +""" +from flask import Blueprint, jsonify, request + +from app.auth_jwt import get_current_user +from app.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, + }) diff --git a/backend/app/services/speech_asr.py b/backend/app/services/speech_asr.py new file mode 100644 index 00000000..750482cc --- /dev/null +++ b/backend/app/services/speech_asr.py @@ -0,0 +1,75 @@ +""" +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 diff --git a/frontend/src/composables/useAudioTranscription.ts b/frontend/src/composables/useAudioTranscription.ts new file mode 100644 index 00000000..fbaab8fd --- /dev/null +++ b/frontend/src/composables/useAudioTranscription.ts @@ -0,0 +1,204 @@ +import { ref, computed, onBeforeUnmount } from 'vue'; +import { getAuthHeaders } from '../utils/auth'; + +export type AudioTranscriptionErrorKey = + | 'chat.voiceRequiresHttps' + | 'chat.voiceNotSupported' + | 'chat.voicePermissionDenied' + | 'chat.voiceRecordTooShort' + | 'chat.voiceTranscriptionFailed'; + +const isSecureContextForMic = (): boolean => { + if (typeof window === 'undefined') return false; + if (window.isSecureContext) return true; + const host = window.location.hostname; + return host === 'localhost' || host === '127.0.0.1'; +}; + +const canUseMediaRecorder = (): boolean => { + if (typeof window === 'undefined') return false; + return Boolean(window.MediaRecorder && navigator.mediaDevices?.getUserMedia); +}; + +export const getVoiceUnavailableErrorKey = (): AudioTranscriptionErrorKey | null => { + if (!isSecureContextForMic()) return 'chat.voiceRequiresHttps'; + if (!canUseMediaRecorder()) return 'chat.voiceNotSupported'; + return null; +}; + +const pickMimeType = (): string => { + const candidates = [ + 'audio/webm;codecs=opus', + 'audio/webm', + 'audio/mp4', + 'audio/ogg;codecs=opus', + ]; + for (const type of candidates) { + if (MediaRecorder.isTypeSupported(type)) return type; + } + return ''; +}; + +export function useAudioTranscription(options: { + onResult: (text: string) => void; + onError: (key: AudioTranscriptionErrorKey) => void; +}) { + const isRecording = ref(false); + const isTranscribing = ref(false); + const isSupported = computed(() => getVoiceUnavailableErrorKey() === null); + const isBusy = computed(() => isRecording.value || isTranscribing.value); + + let mediaStream: MediaStream | null = null; + let mediaRecorder: MediaRecorder | null = null; + let chunks: Blob[] = []; + let baseText = ''; + let skipTranscription = false; + + const cleanupStream = () => { + if (mediaStream) { + mediaStream.getTracks().forEach((track) => track.stop()); + mediaStream = null; + } + mediaRecorder = null; + chunks = []; + }; + + const stopRecording = () => { + if (mediaRecorder && mediaRecorder.state !== 'inactive') { + mediaRecorder.stop(); + return; + } + isRecording.value = false; + cleanupStream(); + }; + + const transcribeBlob = async (blob: Blob, mimeType: string) => { + if (blob.size < 800) { + options.onError('chat.voiceRecordTooShort'); + return; + } + + isTranscribing.value = true; + try { + const ext = mimeType.includes('mp4') ? 'm4a' : 'webm'; + const formData = new FormData(); + formData.append('audio', blob, `recording.${ext}`); + + const response = await fetch('/api/speech/transcribe', { + method: 'POST', + headers: { ...getAuthHeaders() }, + body: formData, + }); + + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + const errMsg = payload?.error?.message || payload?.message || `Request failed (${response.status})`; + throw new Error(errMsg); + } + + const text = String(payload.text || '').trim(); + if (!text) { + options.onError('chat.voiceRecordTooShort'); + return; + } + + const prefix = baseText.trim(); + options.onResult(prefix ? `${prefix} ${text}` : text); + } catch { + options.onError('chat.voiceTranscriptionFailed'); + } finally { + isTranscribing.value = false; + } + }; + + const startRecording = async (existingText = '') => { + if (isBusy.value) return; + + const unavailable = getVoiceUnavailableErrorKey(); + if (unavailable) { + options.onError(unavailable); + return; + } + + baseText = existingText; + + try { + mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true }); + } catch (err) { + const denied = err instanceof DOMException && ( + err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError' + ); + options.onError(denied ? 'chat.voicePermissionDenied' : 'chat.voiceTranscriptionFailed'); + return; + } + + chunks = []; + const mimeType = pickMimeType(); + try { + mediaRecorder = mimeType + ? new MediaRecorder(mediaStream, { mimeType }) + : new MediaRecorder(mediaStream); + } catch { + cleanupStream(); + options.onError('chat.voiceNotSupported'); + return; + } + + mediaRecorder.ondataavailable = (event) => { + if (event.data.size > 0) chunks.push(event.data); + }; + + mediaRecorder.onstop = async () => { + isRecording.value = false; + const type = mediaRecorder?.mimeType || mimeType || 'audio/webm'; + const blob = new Blob(chunks, { type }); + const shouldSkip = skipTranscription; + skipTranscription = false; + cleanupStream(); + if (shouldSkip) return; + await transcribeBlob(blob, type); + }; + + mediaRecorder.onerror = () => { + isRecording.value = false; + cleanupStream(); + options.onError('chat.voiceTranscriptionFailed'); + }; + + mediaRecorder.start(); + isRecording.value = true; + }; + + const toggle = (existingText = '') => { + if (isTranscribing.value) return; + if (isRecording.value) { + stopRecording(); + return; + } + void startRecording(existingText); + }; + + const cancel = () => { + skipTranscription = true; + if (mediaRecorder && mediaRecorder.state !== 'inactive') { + mediaRecorder.stop(); + } else { + cleanupStream(); + } + isRecording.value = false; + isTranscribing.value = false; + }; + + onBeforeUnmount(cancel); + + return { + isRecording, + isTranscribing, + isSupported, + isBusy, + startRecording, + stopRecording, + toggle, + cancel, + }; +} diff --git a/frontend/src/composables/useSpeechRecognition.ts b/frontend/src/composables/useSpeechRecognition.ts deleted file mode 100644 index 39a68a2e..00000000 --- a/frontend/src/composables/useSpeechRecognition.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { ref, computed, onBeforeUnmount, type Ref } from 'vue'; - -export type SpeechRecognitionErrorKey = - | 'chat.voiceNotSupported' - | 'chat.voiceRequiresHttps' - | 'chat.voicePermissionDenied' - | 'chat.voiceNoSpeech' - | 'chat.voiceAudioCapture' - | 'chat.voiceNetworkError' - | 'chat.voiceServiceNotAllowed' - | 'chat.voiceRecognitionFailed'; - -type SpeechRecognitionCtor = new () => SpeechRecognition; - -const getSpeechRecognitionCtor = (): SpeechRecognitionCtor | null => { - if (typeof window === 'undefined') return null; - const w = window as Window & { - SpeechRecognition?: SpeechRecognitionCtor; - webkitSpeechRecognition?: SpeechRecognitionCtor; - }; - return w.SpeechRecognition || w.webkitSpeechRecognition || null; -}; - -export const mapLocaleToSpeechLang = (locale: string): string => { - const map: Record = { - 'zh-CN': 'zh-CN', - 'zh-TW': 'zh-TW', - en: 'en-US', - th: 'th-TH', - }; - return map[locale] || 'zh-CN'; -}; - -const isSecureContextForSpeech = (): boolean => { - if (typeof window === 'undefined') return false; - if (window.isSecureContext) return true; - const host = window.location.hostname; - return host === 'localhost' || host === '127.0.0.1'; -}; - -/** 语音不可用时的提示 key;HTTPS/localhost 且浏览器有 API 时返回 null */ -export const getVoiceUnavailableErrorKey = (): SpeechRecognitionErrorKey | null => { - if (!isSecureContextForSpeech()) return 'chat.voiceRequiresHttps'; - if (!getSpeechRecognitionCtor()) return 'chat.voiceNotSupported'; - return null; -}; - -const mapErrorToKey = (error: string): SpeechRecognitionErrorKey => { - switch (error) { - case 'not-allowed': - return 'chat.voicePermissionDenied'; - case 'service-not-allowed': - return 'chat.voiceServiceNotAllowed'; - case 'no-speech': - return 'chat.voiceNoSpeech'; - case 'audio-capture': - return 'chat.voiceAudioCapture'; - case 'network': - return 'chat.voiceNetworkError'; - default: - return 'chat.voiceRecognitionFailed'; - } -}; - -export function useSpeechRecognition(options: { - lang: Ref; - onResult: (text: string) => void; - onError: (key: SpeechRecognitionErrorKey) => void; -}) { - const isListening = ref(false); - const isSupported = computed(() => getVoiceUnavailableErrorKey() === null); - - let recognition: SpeechRecognition | null = null; - let baseText = ''; - - const stop = () => { - if (recognition) { - try { - recognition.abort(); - } catch { - // ignore abort errors - } - recognition = null; - } - isListening.value = false; - }; - - const start = (existingText = '') => { - if (isListening.value) return; - - const unavailable = getVoiceUnavailableErrorKey(); - if (unavailable) { - options.onError(unavailable); - return; - } - - const Ctor = getSpeechRecognitionCtor()!; - - stop(); - baseText = existingText; - - const instance = new Ctor(); - instance.continuous = true; - instance.interimResults = true; - instance.lang = mapLocaleToSpeechLang(options.lang.value); - - instance.onstart = () => { - isListening.value = true; - }; - - instance.onresult = (event: SpeechRecognitionEvent) => { - let sessionTranscript = ''; - for (let i = 0; i < event.results.length; i++) { - sessionTranscript += event.results[i]?.[0]?.transcript || ''; - } - options.onResult(`${baseText}${sessionTranscript}`); - }; - - instance.onerror = (event: SpeechRecognitionErrorEvent) => { - if (event.error === 'aborted') return; - options.onError(mapErrorToKey(event.error)); - stop(); - }; - - instance.onend = () => { - isListening.value = false; - recognition = null; - }; - - recognition = instance; - try { - recognition.start(); - } catch { - options.onError('chat.voiceRecognitionFailed'); - stop(); - } - }; - - const toggle = (existingText = '') => { - if (isListening.value) { - stop(); - return; - } - start(existingText); - }; - - onBeforeUnmount(stop); - - return { - isListening, - isSupported, - start, - stop, - toggle, - }; -} diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 9d85770e..489ee9b4 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -1267,6 +1267,9 @@ const messages = { voiceNetworkError: 'Voice recognition network error', voiceServiceNotAllowed: 'Voice recognition service is not allowed', voiceRecognitionFailed: 'Voice recognition failed. Please try again', + voiceTranscribing: 'Transcribing...', + voiceRecordTooShort: 'Recording too short or no speech detected', + voiceTranscriptionFailed: 'Speech recognition failed. Please try again', collapseBrowser: 'Collapse Browser', openBrowser: 'Open Browser', kb: { @@ -2737,6 +2740,9 @@ const messages = { voiceNetworkError: '语音识别网络错误', voiceServiceNotAllowed: '不允许使用语音识别服务', voiceRecognitionFailed: '语音识别失败,请重试', + voiceTranscribing: '正在识别…', + voiceRecordTooShort: '录音太短或未检测到语音', + voiceTranscriptionFailed: '语音识别失败,请重试', collapseBrowser: '收起浏览器', openBrowser: '打开浏览器', kb: { @@ -4066,6 +4072,9 @@ const messages = { voiceNetworkError: '語音辨識網路錯誤', voiceServiceNotAllowed: '不允許使用語音辨識服務', voiceRecognitionFailed: '語音辨識失敗,請重試', + voiceTranscribing: '正在辨識…', + voiceRecordTooShort: '錄音太短或未偵測到語音', + voiceTranscriptionFailed: '語音辨識失敗,請重試', collapseBrowser: '收起瀏覽器', openBrowser: '打開瀏覽器', kb: { @@ -5312,6 +5321,9 @@ const messages = { voiceNetworkError: 'เกิดข้อผิดพลาดเครือข่ายในการรู้จำเสียง', voiceServiceNotAllowed: 'ไม่อนุญาตให้ใช้บริการรู้จำเสียง', voiceRecognitionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง', + voiceTranscribing: 'กำลังแปลงเสียง...', + voiceRecordTooShort: 'การบันทึกสั้นเกินไปหรือไม่พบเสียงพูด', + voiceTranscriptionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง', collapseBrowser: 'ย่อเบราว์เซอร์', openBrowser: 'เปิดเบราว์เซอร์', kb: { diff --git a/frontend/src/types/speech-recognition.d.ts b/frontend/src/types/speech-recognition.d.ts deleted file mode 100644 index 239add32..00000000 --- a/frontend/src/types/speech-recognition.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -interface SpeechRecognitionAlternative { - transcript: string; - confidence: number; -} - -interface SpeechRecognitionResult { - readonly isFinal: boolean; - readonly length: number; - item(index: number): SpeechRecognitionAlternative; - [index: number]: SpeechRecognitionAlternative; -} - -interface SpeechRecognitionResultList { - readonly length: number; - item(index: number): SpeechRecognitionResult; - [index: number]: SpeechRecognitionResult; -} - -interface SpeechRecognitionEvent extends Event { - readonly resultIndex: number; - readonly results: SpeechRecognitionResultList; -} - -interface SpeechRecognitionErrorEvent extends Event { - readonly error: string; - readonly message: string; -} - -interface SpeechRecognition extends EventTarget { - continuous: boolean; - interimResults: boolean; - lang: string; - start(): void; - stop(): void; - abort(): void; - onstart: ((this: SpeechRecognition, ev: Event) => void) | null; - onend: ((this: SpeechRecognition, ev: Event) => void) | null; - onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null; - onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null; -} - -interface Window { - SpeechRecognition?: new () => SpeechRecognition; - webkitSpeechRecognition?: new () => SpeechRecognition; -} diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 4f9298ff..d87599d4 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -21,7 +21,7 @@ import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue'; import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue'; import { useMessage } from '../composables/useMessage'; import { useIsMobile } from '../composables/useIsMobile'; -import { getVoiceUnavailableErrorKey, useSpeechRecognition } from '../composables/useSpeechRecognition'; +import { getVoiceUnavailableErrorKey, useAudioTranscription } from '../composables/useAudioTranscription'; import { useTheme } from '../composables/useTheme'; import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth'; import { copyTextToClipboard } from '../utils/clipboard'; @@ -664,11 +664,11 @@ const copiedIndex = ref(null); const { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage } = useChat(); const input = ref(''); const { - isListening: isVoiceListening, + isRecording: isVoiceRecording, + isTranscribing: isVoiceTranscribing, toggle: toggleVoiceInput, - stop: stopVoiceInput, -} = useSpeechRecognition({ - lang: locale, + cancel: cancelVoiceInput, +} = useAudioTranscription({ onResult: (text) => { input.value = text; }, @@ -678,7 +678,7 @@ const { }); const handleVoiceFeatureClick = () => { - if (isThinking.value) return; + if (isThinking.value || isVoiceTranscribing.value) return; const unavailable = getVoiceUnavailableErrorKey(); if (unavailable) { msg.warning(t(unavailable)); @@ -688,7 +688,7 @@ const handleVoiceFeatureClick = () => { }; watch(isThinking, (thinking) => { - if (thinking) stopVoiceInput(); + if (thinking) cancelVoiceInput(); }); const currentAgent = ref(null); @@ -2484,7 +2484,7 @@ const syncChatStateForRoute = async () => { const syncToken = ++routeSyncToken; resetChatStateForAgentChange(); - stopVoiceInput(); + cancelVoiceInput(); setLastChatAgentId(agentId); syncOpenAgentRegistration(); @@ -3285,10 +3285,10 @@ const showChatRating = ref(false); v-model="input" @keydown.enter.prevent="handleSend" rows="1" - :placeholder="isVoiceListening ? $t('chat.voiceListening') : $t('chat.askAnything')" + :placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')" class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent" style="min-height: 44px; max-height: 220px;" - :disabled="isThinking" + :disabled="isThinking || isVoiceTranscribing" spellcheck="false" autocorrect="off" autocapitalize="off" @@ -3323,12 +3323,13 @@ const showChatRating = ref(false);