This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-16 20:40:27 +02:00
1 parent 0fd5d290fb
commit 63fb405de1
15 files changed
+289 -15

No files matched your search

@@ -26,6 +26,7 @@
let ttsFormat = $state('mp3');
let hasExistingTtsKey = $state(false);
let voiceModeSystemPrompt = $state('');
let voiceModeSttMode = $state<'browser' | 'provider'>('browser');
const VOICE_MODE_SYSTEM_PROMPT_PLACEHOLDER =
'You are in voice mode. Keep responses brief, conversational, and easy to hear aloud. Prefer one or two short paragraphs. Ask at most one focused follow-up question when needed. Avoid long lists, code blocks, tables, and verbose explanations unless the user explicitly asks.';
@@ -47,6 +48,8 @@
ttsFormat = (config['audio.tts_format'] as string) || 'mp3';
hasExistingTtsKey = !!config['audio.tts_api_key'];
voiceModeSystemPrompt = (config['audio.voice_mode_system_prompt'] as string) || '';
voiceModeSttMode =
config['audio.voice_mode_stt_mode'] === 'provider' ? 'provider' : 'browser';
} catch {}
loading = false;
});
@@ -65,7 +68,8 @@
'audio.tts_model': ttsModel,
'audio.tts_voice': ttsVoice,
'audio.tts_format': ttsFormat,
'audio.voice_mode_system_prompt': voiceModeSystemPrompt
'audio.voice_mode_system_prompt': voiceModeSystemPrompt,
'audio.voice_mode_stt_mode': voiceModeSttMode
};
if (sttApiKey) {
cfg['audio.stt_api_key'] = sttApiKey;
@@ -241,6 +245,19 @@
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('admin.audio.voiceMode')}</h3>
<div class="flex flex-col gap-2.5">
<div class="flex items-center justify-between">
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('admin.audio.voiceModeSttMode')}</span>
<select
bind:value={voiceModeSttMode}
class="bg-transparent text-xs text-gray-600 dark:text-gray-400 outline-none cursor-pointer"
>
<option value="browser">{$t('admin.audio.voiceModeSttBrowser')}</option>
<option value="provider">{$t('admin.audio.voiceModeSttProvider')}</option>
</select>
</div>
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">
{voiceModeSttMode === 'browser' ? $t('admin.audio.voiceModeBrowserSttHint') : $t('admin.audio.voiceModeProviderSttHint')}
</p>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="voice-mode-system-prompt">
{$t('admin.audio.voiceModeSystemPrompt')}
@@ -22,7 +22,13 @@
import QueuedMessageItem from './QueuedMessageItem.svelte';
import Icon from '../Icon.svelte';
import { planMode } from '$lib/stores';
import { ttsConfigured, ttsEnabled, voiceModeEnabled } from '$lib/stores/audio';
import {
sttConfigured,
ttsConfigured,
ttsEnabled,
voiceModeEnabled,
voiceModeSttMode
} from '$lib/stores/audio';
import Spinner from '$lib/components/common/Spinner.svelte';
import { t } from '$lib/i18n';
@@ -64,7 +70,13 @@
let voiceRestartTimer = 0;
let voiceStopRequested = false;
let voiceRearming = $state(false);
const voiceModeAvailable = $derived($ttsEnabled && $ttsConfigured);
let voiceCaptureRecorder: MediaRecorder | null = null;
let voiceCaptureStream: MediaStream | null = null;
let voiceCaptureChunks: Blob[] = [];
let voiceCaptureMimeType = 'audio/webm';
const voiceModeAvailable = $derived(
$ttsEnabled && $ttsConfigured && ($voiceModeSttMode === 'browser' || $sttConfigured)
);
const voiceStatusLabel = $derived(
voiceWaitingForResponse || streaming || sending
? $t('chat.voiceWaiting')
@@ -576,12 +588,110 @@
const recognition = voiceRecognition;
voiceRecognition = null;
voiceStopRequested = true;
stopVoiceCapture();
try {
recognition?.stop();
} catch {}
voiceListening = false;
}
function chooseVoiceCaptureMimeType() {
if (typeof MediaRecorder === 'undefined') return 'audio/webm';
if (MediaRecorder.isTypeSupported?.('audio/webm;codecs=opus')) return 'audio/webm;codecs=opus';
if (MediaRecorder.isTypeSupported?.('audio/webm')) return 'audio/webm';
if (MediaRecorder.isTypeSupported?.('audio/mp4')) return 'audio/mp4';
return '';
}
async function startVoiceCapture() {
if (!workspace || voiceCaptureRecorder || typeof MediaRecorder === 'undefined') return;
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
if (!voiceRecognition || !voiceListening) {
stream.getTracks().forEach((track) => track.stop());
return;
}
const mimeType = chooseVoiceCaptureMimeType();
const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
voiceCaptureStream = stream;
voiceCaptureRecorder = recorder;
voiceCaptureChunks = [];
voiceCaptureMimeType = recorder.mimeType || mimeType || 'audio/webm';
recorder.ondataavailable = (event) => {
if (event.data.size > 0) voiceCaptureChunks.push(event.data);
};
recorder.start();
} catch {
voiceCaptureRecorder = null;
voiceCaptureStream = null;
voiceCaptureChunks = [];
}
}
async function stopVoiceCapture(): Promise<{ blob: Blob; filename: string; contentType: string } | null> {
const recorder = voiceCaptureRecorder;
const stream = voiceCaptureStream;
const chunks = voiceCaptureChunks;
const contentType = voiceCaptureMimeType || 'audio/webm';
voiceCaptureRecorder = null;
voiceCaptureStream = null;
voiceCaptureChunks = [];
if (!recorder) {
stream?.getTracks().forEach((track) => track.stop());
return null;
}
await new Promise<void>((resolve) => {
recorder.onstop = () => resolve();
try {
if (recorder.state !== 'inactive') recorder.stop();
else resolve();
} catch {
resolve();
}
});
stream?.getTracks().forEach((track) => track.stop());
if (!chunks.length) return null;
const ext = contentType.includes('mp4') ? 'm4a' : 'webm';
return {
blob: new Blob(chunks, { type: contentType }),
filename: `voice-mode.${ext}`,
contentType
};
}
async function saveVoiceModeSttCapture(
capture: { blob: Blob; filename: string; contentType: string },
text: string
) {
// Browser STT does not need provider transcription, but the captured audio still
// matters. Sending audio plus transcript through the normal transcribe route keeps
// browser and provider voice samples in one STT cache for the data flywheel.
if (!workspace || !text.trim()) return;
const form = new FormData();
form.append('file', capture.blob, capture.filename);
form.append('text', text.trim());
form.append('workspace', workspace);
form.append('source', 'voice_mode');
form.append('language', navigator.language || 'en-US');
try {
await fetch('/api/audio/transcribe', { method: 'POST', body: form });
} catch {}
}
async function transcribeVoiceModeCapture(
capture: { blob: Blob; filename: string; contentType: string }
): Promise<string> {
const form = new FormData();
form.append('file', capture.blob, capture.filename);
form.append('workspace', workspace);
const res = await fetch('/api/audio/transcribe', { method: 'POST', body: form });
if (!res.ok) throw new Error('transcription failed');
const data = await res.json();
return (data?.text || '').trim();
}
function startVoiceRecognition() {
clearVoiceRestartTimer(false);
if (
@@ -615,17 +725,34 @@
recognition.lang = navigator.language || 'en-US';
recognition.onresult = async (event: any) => {
let text = '';
let browserText = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const result = event.results[i];
if (result?.isFinal) text += ` ${result[0]?.transcript || ''}`;
if (result?.isFinal) browserText += ` ${result[0]?.transcript || ''}`;
}
text = text.trim();
if (!text) return;
inputText = text;
browserText = browserText.trim();
if (!browserText) return;
voiceWaitingForResponse = true;
voiceSawStreaming = false;
const capturePromise = stopVoiceCapture();
stopVoiceRecognition();
const capture = await capturePromise;
let text = browserText;
if ($voiceModeSttMode === 'provider' && capture) {
try {
text = (await transcribeVoiceModeCapture(capture)) || browserText;
} catch {
text = browserText;
}
} else if (capture) {
void saveVoiceModeSttCapture(capture, browserText);
}
if (!text.trim()) {
voiceWaitingForResponse = false;
scheduleVoiceRestart(500);
return;
}
inputText = text;
await tick();
onsend();
};
@@ -642,6 +769,7 @@
if (voiceRecognition !== recognition) return;
voiceRecognition = null;
voiceListening = false;
stopVoiceCapture();
if (!voiceStopRequested) scheduleVoiceRestart(1200);
voiceStopRequested = false;
};
@@ -650,6 +778,7 @@
recognition.start();
voiceListening = true;
voiceRearming = false;
void startVoiceCapture();
} catch {
voiceRecognition = null;
voiceListening = false;
@@ -80,6 +80,9 @@
let ttsErrorShown = false;
let speakingMessageId = $state<string | null>(null);
let ttsStopRequested = false;
// This browser memory cache only helps while the current page is open, such as when
// someone taps the same speak button twice. The backend cache is the durable source
// for cross-session reuse and the workspace data flywheel.
let ttsAudioCacheBytes = 0;
const ttsAudioCache = new Map<string, Blob>();
const TTS_AUDIO_CACHE_LIMIT_BYTES = 20 * 1024 * 1024;
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "Audioeinstellungen konnten nicht gespeichert werden",
@@ -598,6 +598,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "Failed to save audio settings",
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "No se pudieron guardar los ajustes de audio",
@@ -482,6 +482,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "Échec de la sauvegarde des paramètres audio",
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "オーディオ設定の保存に失敗しました",
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "오디오 설정 저장에 실패했습니다",
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "Falha ao salvar as configurações de áudio",
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "Не удалось сохранить настройки аудио",
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "保存音频设置失败",
@@ -483,6 +483,11 @@
"admin.audio.ttsFormat": "Format",
"admin.audio.ttsHint": "Compatible with OpenAI's audio/speech API. If no TTS key is set, the STT key is reused.",
"admin.audio.voiceMode": "Voice Mode",
"admin.audio.voiceModeSttMode": "Speech recognition",
"admin.audio.voiceModeSttBrowser": "Browser",
"admin.audio.voiceModeSttProvider": "Configured STT",
"admin.audio.voiceModeBrowserSttHint": "Uses browser speech recognition, then stores the audio and transcript locally for the voice data flywheel.",
"admin.audio.voiceModeProviderSttHint": "Sends voice-mode audio through the configured STT provider and stores the result locally.",
"admin.audio.voiceModeSystemPrompt": "System prompt",
"admin.audio.voiceModeSystemPromptHint": "Applied only while voice mode is on. Keep it short to make spoken replies useful.",
"admin.audio.saveFailed": "儲存音訊設定失敗",
+8
View File
@@ -14,6 +14,7 @@ export const QUALITY_BITRATES: Record<RecordingQuality, number> = {
export const voiceMemosEnabled = writable<boolean>(false);
export const transcribeEnabled = writable<boolean>(true);
export const sttConfigured = writable<boolean>(false);
export const recordingQuality = writable<RecordingQuality>('high');
export const showVoiceMemo = writable<boolean>(false);
export const ttsEnabled = writable<boolean>(false);
@@ -21,6 +22,7 @@ export const ttsConfigured = writable<boolean>(false);
export const ttsVoice = writable<string>('alloy');
export const ttsFormat = writable<string>('mp3');
export const voiceModeEnabled = writable<boolean>(false);
export const voiceModeSttMode = writable<'browser' | 'provider'>('browser');
export const ttsPlaybackEnabled = writable<boolean>(
typeof localStorage !== 'undefined' ? localStorage.getItem('ttsPlaybackEnabled') === 'true' : false
);
@@ -34,14 +36,17 @@ export async function refreshAudioState() {
const data = await fetchJSON<{
voice_memos_enabled: boolean;
transcribe_enabled: boolean;
stt_configured: boolean;
recording_quality: string;
tts_enabled: boolean;
tts_configured: boolean;
tts_voice: string;
tts_format: string;
voice_mode_stt_mode?: string;
}>('/api/audio/state');
voiceMemosEnabled.set(data.voice_memos_enabled === true);
transcribeEnabled.set(data.transcribe_enabled !== false);
sttConfigured.set(data.stt_configured === true);
const q = data.recording_quality;
if (q === 'medium' || q === 'low') recordingQuality.set(q);
else recordingQuality.set('high');
@@ -49,9 +54,12 @@ export async function refreshAudioState() {
ttsConfigured.set(data.tts_configured === true);
ttsVoice.set(data.tts_voice || 'alloy');
ttsFormat.set(data.tts_format || 'mp3');
voiceModeSttMode.set(data.voice_mode_stt_mode === 'provider' ? 'provider' : 'browser');
} catch {
voiceMemosEnabled.set(false);
sttConfigured.set(false);
ttsEnabled.set(false);
ttsConfigured.set(false);
voiceModeSttMode.set('browser');
}
}
+74 -7
View File
@@ -48,11 +48,13 @@ class SpeechRequest(BaseModel):
class AudioStateResponse(BaseModel):
voice_memos_enabled: bool
transcribe_enabled: bool
stt_configured: bool
recording_quality: str
tts_enabled: bool
tts_configured: bool
tts_voice: str
tts_format: str
voice_mode_stt_mode: str
def _get_user(request: Request) -> str:
@@ -66,6 +68,10 @@ def _get_user(request: Request) -> str:
def _workspace_audio_cache_dir(workspace: str | None, kind: str) -> Path | None:
# Voice samples are project context, so they live under the workspace .cptr
# folder and move with the project. That keeps STT and TTS artifacts available
# for reuse, debugging, and the local data flywheel while ensure_cptr_gitignored
# keeps them out of git.
if not workspace:
return None
ws = Path(workspace).expanduser().resolve()
@@ -78,6 +84,9 @@ def _workspace_audio_cache_dir(workspace: str | None, kind: str) -> Path | None:
def _cache_key(payload: dict, data: bytes | None = None) -> str:
# The key includes the provider settings plus the exact audio bytes or text.
# Without those inputs, a model, voice, or format change could accidentally reuse
# the wrong artifact. The JSON file beside the audio explains what the hash means.
h = hashlib.sha256()
h.update(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode())
if data is not None:
@@ -195,11 +204,13 @@ async def audio_state(request: Request):
return AudioStateResponse(
voice_memos_enabled=await Config.get("audio.voice_memos_enabled") is True,
transcribe_enabled=await Config.get("audio.transcribe_enabled") is not False,
stt_configured=bool(stt_key),
recording_quality=str(quality),
tts_enabled=await Config.get("audio.tts_enabled") is True,
tts_configured=bool(tts_key or stt_key),
tts_voice=str((await Config.get("audio.tts_voice")) or "alloy"),
tts_format=str((await Config.get("audio.tts_format")) or "mp3"),
voice_mode_stt_mode=str((await Config.get("audio.voice_mode_stt_mode")) or "browser"),
)
@@ -224,7 +235,14 @@ async def _transcribe_chunk(
@router.post("/transcribe")
async def transcribe(file: UploadFile, request: Request, workspace: str | None = Form(None)):
async def transcribe(
file: UploadFile,
request: Request,
workspace: str | None = Form(None),
text: str | None = Form(None),
source: str | None = Form(None),
language: str | None = Form(None),
):
"""Send audio to a Whisper-compatible STT API, return transcript text.
If pydub + ffmpeg are available and the file is large, it will be
@@ -232,6 +250,53 @@ async def transcribe(file: UploadFile, request: Request, workspace: str | None =
"""
_get_user(request)
raw_data = await file.read()
filename = file.filename or "audio.webm"
content_type = file.content_type or "audio/webm"
cache_dir = _workspace_audio_cache_dir(workspace, "stt")
cache_json_path: Path | None = None
cache_audio_path: Path | None = None
provided_text = (text or "").strip()
if provided_text:
# Browser speech recognition already produced text, so there is no provider
# call to cache. We still store the captured audio and transcript in the
# normal STT folder so browser mode and provider mode produce the same kind
# of data flywheel sample without paying for a second transcription.
if not raw_data:
raise HTTPException(400, "Speech-to-text capture requires non-empty audio.")
if cache_dir:
audio_ext = _audio_extension(filename, content_type)
key = _cache_key(
{
"type": "stt",
"source": source or "browser_speech_recognition",
"text": provided_text,
"filename": filename,
"content_type": content_type,
"language": language or "",
},
raw_data,
)
cache_json_path = cache_dir / f"{key}.json"
cache_audio_path = cache_dir / f"{key}{audio_ext}"
if not cache_json_path.exists() or not cache_audio_path.exists():
_write_bytes_atomic(cache_audio_path, raw_data)
_write_json_atomic(
cache_json_path,
{
"type": "stt",
"source": source or "browser_speech_recognition",
"transcription_source": "browser_speech_recognition",
"text": provided_text,
"audio_file": cache_audio_path.name,
"filename": filename,
"content_type": content_type,
"language": language,
},
)
return {"text": provided_text, "cached": True}
api_key_encrypted = await Config.get("audio.stt_api_key")
if not api_key_encrypted:
raise HTTPException(
@@ -243,13 +308,11 @@ async def transcribe(file: UploadFile, request: Request, workspace: str | None =
base_url = (await Config.get("audio.stt_base_url")) or "https://api.openai.com/v1"
model = (await Config.get("audio.stt_model")) or "whisper-1"
raw_data = await file.read()
filename = file.filename or "audio.webm"
content_type = file.content_type or "audio/webm"
cache_dir = _workspace_audio_cache_dir(workspace, "stt")
cache_json_path: Path | None = None
cache_audio_path: Path | None = None
if cache_dir:
# Provider STT is cacheable because identical audio with the same provider
# settings should produce the same transcript. Keeping the original audio
# beside the JSON makes the sample reusable for audits, replay, and future
# data flywheel work instead of being a one-off API response.
key = _cache_key(
{
"type": "stt",
@@ -414,6 +477,10 @@ async def speech(body: SpeechRequest, request: Request):
cache_audio_path: Path | None = None
cache_json_path: Path | None = None
if cache_dir:
# TTS is especially worth caching because short phrases repeat often across
# messages and replays. The key uses provider, model, voice, format, and exact
# text so a phrase like "Hi." can be reused safely without new spend, while
# the neighboring JSON records why that audio file exists.
key = _cache_key(
{
"type": "tts",