Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat: replace cloud Speech API with 100% local Whisper STT

PurpleDoubleDf61fd3ae8fdd
diff --git a/src/api/voice.ts b/src/api/voice.ts
index cafdf783..5e7aae45 100644
--- a/src/api/voice.ts
+++ b/src/api/voice.ts
@@ -1,12 +1,12 @@
/**
- * Voice API wrapper for Speech Recognition and Speech Synthesis
+ * Voice API — 100% local
+ * STT: Local Whisper (faster-whisper or openai-whisper) via /local-api/transcribe
+ * TTS: Browser SpeechSynthesis (runs locally in the browser, no cloud)
*/
export function isSpeechRecognitionSupported(): boolean {
- return !!(
- (window as any).SpeechRecognition ||
- (window as any).webkitSpeechRecognition
- );
+ // Always true — we use local Whisper, not browser SpeechRecognition API
+ return true;
}
export function isSpeechSynthesisSupported(): boolean {
@@ -134,29 +134,48 @@ export function stopSpeaking(): void {
}
}
-export interface AudioRecorderOptions {
- onInterimTranscript?: (text: string) => void;
+// --- Local Whisper STT ---
+
+export async function checkWhisperAvailable(): Promise<{
+ available: boolean;
+ backend: string | null;
+ error?: string;
+}> {
+ try {
+ const res = await fetch("/local-api/transcribe-status");
+ return res.json();
+ } catch {
+ return { available: false, backend: null, error: "Failed to reach transcribe-status endpoint" };
+ }
+}
+
+export async function transcribeAudio(audioBlob: Blob): Promise<string> {
+ const res = await fetch("/local-api/transcribe", {
+ method: "POST",
+ headers: { "Content-Type": audioBlob.type || "audio/webm" },
+ body: audioBlob,
+ });
+ const data = await res.json();
+ if (data.error) throw new Error(data.error);
+ return data.transcript || "";
}
-interface AudioRecorder {
+// --- Audio Recorder (MediaRecorder only, NO SpeechRecognition) ---
+
+export interface AudioRecorder {
start: () => Promise<void>;
- stop: () => Promise<{ blob: Blob; transcript: string }>;
+ stop: () => Promise<Blob>;
isRecording: () => boolean;
}
-export function createAudioRecorder(options?: AudioRecorderOptions): AudioRecorder {
+export function createAudioRecorder(): AudioRecorder {
let mediaRecorder: MediaRecorder | null = null;
- let recognition: any = null;
let audioChunks: Blob[] = [];
- let currentTranscript = "";
let recording = false;
return {
start: async () => {
audioChunks = [];
- currentTranscript = "";
-
- // Start MediaRecorder for audio blob
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream, {
mimeType: MediaRecorder.isTypeSupported("audio/webm;codecs=opus")
@@ -171,88 +190,13 @@ export function createAudioRecorder(options?: AudioRecorderOptions): AudioRecord
};
mediaRecorder.start(250); // Collect data every 250ms
-
- // Start SpeechRecognition in parallel for transcript
- const SpeechRecognition =
- (window as any).SpeechRecognition ||
- (window as any).webkitSpeechRecognition;
-
- if (SpeechRecognition) {
- recognition = new SpeechRecognition();
- recognition.continuous = true;
- recognition.interimResults = true;
- // Auto-detect user language instead of hardcoding en-US
- recognition.lang = navigator.language || "en-US";
- console.log("[Voice] SpeechRecognition starting with lang:", recognition.lang);
-
- recognition.onstart = () => {
- console.log("[Voice] SpeechRecognition started successfully");
- };
-
- recognition.onresult = (event: any) => {
- console.log("[Voice] onresult fired, results count:", event.results?.length);
- if (!event.results) {
- console.warn("[Voice] onresult: event.results is undefined");
- return;
- }
-
- let interim = "";
- let final = "";
- for (let i = 0; i < event.results.length; i++) {
- const result = event.results[i];
- if (!result || !result[0]) continue;
- if (result.isFinal) {
- final += result[0].transcript;
- } else {
- interim += result[0].transcript;
- }
- }
- currentTranscript = final + interim;
- console.log("[Voice] Transcript update:", currentTranscript.slice(0, 80));
-
- // Fire interim transcript callback for live updates
- if (options?.onInterimTranscript) {
- options.onInterimTranscript(currentTranscript);
- }
- };
-
- recognition.onerror = (event: any) => {
- console.error("[Voice] SpeechRecognition error:", event.error, event.message);
- // If offline or network error, the transcript will just be empty
- // but audio blob still captures
- };
-
- recognition.onend = () => {
- console.log("[Voice] SpeechRecognition ended");
- };
-
- try {
- recognition.start();
- } catch (err) {
- console.error("[Voice] Failed to start SpeechRecognition:", err);
- }
- } else {
- console.warn("[Voice] SpeechRecognition API not available in this browser");
- }
-
recording = true;
},
stop: () => {
- return new Promise((resolve) => {
+ return new Promise<Blob>((resolve) => {
recording = false;
- // Stop recognition
- if (recognition) {
- try {
- recognition.stop();
- } catch {
- // Already stopped
- }
- recognition = null;
- }
-
- // Stop media recorder and collect blob
if (mediaRecorder && mediaRecorder.state !== "inactive") {
mediaRecorder.onstop = () => {
const blob = new Blob(audioChunks, {
@@ -263,15 +207,12 @@ export function createAudioRecorder(options?: AudioRecorderOptions): AudioRecord
mediaRecorder?.stream.getTracks().forEach((track) => track.stop());
mediaRecorder = null;
- resolve({ blob, transcript: currentTranscript });
+ resolve(blob);
};
mediaRecorder.stop();
} else {
- resolve({
- blob: new Blob([], { type: "audio/webm" }),
- transcript: currentTranscript,
- });
+ resolve(new Blob([], { type: "audio/webm" }));
}
});
},
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 7515433d..a285af54 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -1,7 +1,8 @@
-import { useState, useRef, useEffect, useCallback } from 'react'
+import { useState, useRef, useEffect } from 'react'
import { motion } from 'framer-motion'
-import { Send, Square, Check } from 'lucide-react'
+import { Send, Square } from 'lucide-react'
import { VoiceButton } from './VoiceButton'
+import { useVoiceStore } from '../../stores/voiceStore'
interface Props {
onSend: (content: string) => void
@@ -13,7 +14,7 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
const [input, setInput] = useState('')
const [isVoiceRecording, setIsVoiceRecording] = useState(false)
const textareaRef = useRef<HTMLTextAreaElement>(null)
- const stopVoiceRef = useRef<(() => Promise<string>) | null>(null)
+ const isTranscribing = useVoiceStore((s) => s.isTranscribing)
useEffect(() => {
if (textareaRef.current) {
@@ -35,42 +36,24 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
- if (isVoiceRecording) return // Don't send while recording
+ if (isVoiceRecording || isTranscribing) return
handleSend()
}
}
- const handleInterimTranscript = useCallback((text: string) => {
- console.log('[Voice] Interim:', text)
+ const handleRecordingChange = (recording: boolean) => {
+ setIsVoiceRecording(recording)
+ }
+
+ const handleVoiceTranscript = (text: string) => {
setInput(text)
- // Force textarea height recalculation after interim update
+ // Force textarea height recalculation
requestAnimationFrame(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px'
}
})
- }, [])
-
- const handleRecordingChange = useCallback((recording: boolean) => {
- setIsVoiceRecording(recording)
- }, [])
-
- const handleVoiceTranscript = useCallback((text: string) => {
- // Final transcript received after recording stops
- setInput(text)
- }, [])
-
- const handleStopRegistered = useCallback((stopFn: () => Promise<string>) => {
- stopVoiceRef.current = stopFn
- }, [])
-
- // When the checkmark is clicked, stop voice recording via the registered stop function
- const handleConfirmRecording = async () => {
- if (stopVoiceRef.current) {
- await stopVoiceRef.current()
- stopVoiceRef.current = null
- }
}
return (
@@ -78,9 +61,7 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
<div className="flex items-end gap-2.5 glass-card rounded-xl px-3 py-2.5">
<VoiceButton
onTranscript={handleVoiceTranscript}
- onInterimTranscript={handleInterimTranscript}
onRecordingChange={handleRecordingChange}
- onStopRegistered={handleStopRegistered}
disabled={isGenerating}
/>
<textarea
@@ -88,7 +69,7 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
- placeholder={isVoiceRecording ? "Listening..." : "Type a message..."}
+ placeholder={isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : "Type a message..."}
rows={1}
className="flex-1 bg-transparent resize-none text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none text-[0.8rem] leading-relaxed max-h-[200px]"
/>
@@ -100,19 +81,10 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
>
<Square size={15} />
</motion.button>
- ) : isVoiceRecording ? (
- <motion.button
- onClick={handleConfirmRecording}
- className="p-2 rounded-lg bg-green-100 dark:bg-green-500/20 border border-green-300 dark:border-green-500/40 text-green-600 dark:text-green-400 hover:bg-green-200 dark:hover:bg-green-500/30 transition-all shrink-0"
- whileTap={{ scale: 0.9 }}
- title="Confirm voice input"
- >
- <Check size={15} />
- </motion.button>
) : (
<motion.button
onClick={handleSend}
- disabled={!input.trim()}
+ disabled={!input.trim() || isTranscribing}
className="p-2 rounded-lg bg-gray-800 dark:bg-white/10 border border-gray-700 dark:border-white/15 text-white hover:bg-gray-700 dark:hover:bg-white/15 disabled:opacity-30 disabled:cursor-not-allowed transition-all shrink-0"
whileTap={{ scale: 0.9 }}
>
@@ -121,7 +93,7 @@ export function ChatInput({ onSend, onStop, isGenerating }: Props) {
)}
</div>
<p className="text-[0.65rem] text-gray-400 dark:text-gray-600 mt-1.5 text-center">
- {isVoiceRecording ? 'Speaking... click checkmark to confirm' : 'Enter to send \u00b7 Shift+Enter for new line'}
+ {isTranscribing ? 'Transcribing with local Whisper...' : isVoiceRecording ? 'Recording... click mic to stop' : 'Enter to send \u00b7 Shift+Enter for new line'}
</p>
</div>
)
diff --git a/src/components/chat/VoiceButton.tsx b/src/components/chat/VoiceButton.tsx
index 69e8a699..2cd1f00b 100644
--- a/src/components/chat/VoiceButton.tsx
+++ b/src/components/chat/VoiceButton.tsx
@@ -1,46 +1,28 @@
-import { useEffect } from "react"
import { motion } from "framer-motion"
-import { Mic, MicOff } from "lucide-react"
+import { Mic, MicOff, Loader2 } from "lucide-react"
import { useVoice } from "../../hooks/useVoice"
interface Props {
onTranscript: (text: string) => void
- onInterimTranscript?: (text: string) => void
onRecordingChange?: (isRecording: boolean) => void
- onStopRegistered?: (stopFn: () => Promise<string>) => void
disabled?: boolean
}
-export function VoiceButton({ onTranscript, onInterimTranscript, onRecordingChange, onStopRegistered, disabled }: Props) {
- const { isRecording, sttSupported, startRecording, stopRecording } = useVoice()
-
- // Register stop function whenever recording state changes
- useEffect(() => {
- if (isRecording && onStopRegistered) {
- onStopRegistered(async () => {
- const transcript = await stopRecording()
- onRecordingChange?.(false)
- if (transcript.trim()) {
- onTranscript(transcript.trim())
- }
- return transcript
- })
- }
- }, [isRecording, onStopRegistered, stopRecording, onRecordingChange, onTranscript])
+export function VoiceButton({ onTranscript, onRecordingChange, disabled }: Props) {
+ const { isRecording, isTranscribing, sttSupported, startRecording, stopRecording } = useVoice()
const handleClick = async () => {
- if (disabled) return
+ if (disabled || isTranscribing) return
if (isRecording) {
- const transcript = await stopRecording()
onRecordingChange?.(false)
+ const transcript = await stopRecording()
if (transcript.trim()) {
onTranscript(transcript.trim())
}
} else {
- // Notify parent BEFORE starting (so UI updates immediately)
onRecordingChange?.(true)
- await startRecording(onInterimTranscript)
+ await startRecording()
}
}
@@ -54,12 +36,24 @@ export function VoiceButton({ onTranscript, onInterimTranscript, onRecordingChan
<MicOff size={15} />
</button>
<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-gray-800 dark:bg-gray-700 text-white text-[0.6rem] rounded whitespace-nowrap opacity-0 group-hover/mic:opacity-100 transition-opacity pointer-events-none">
- Speech recognition not supported
+ Speech recognition not available
</div>
</div>
)
}
+ // Transcribing state — show spinner
+ if (isTranscribing) {
+ return (
+ <motion.button
+ disabled
+ className="p-2 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/40 text-blue-600 dark:text-blue-400 shrink-0 relative"
+ >
+ <Loader2 size={15} className="animate-spin" />
+ </motion.button>
+ )
+ }
+
return (
<motion.button
onClick={handleClick}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index d720b9c1..37663d41 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react'
-import { ArrowLeft, RotateCcw, Sun, Moon, Mic, Volume2, Check, X } from 'lucide-react'
+import { ArrowLeft, RotateCcw, Sun, Moon, Mic, Volume2, Check, X, Loader2 } from 'lucide-react'
import { useSettingsStore } from '../../stores/settingsStore'
import { useUIStore } from '../../stores/uiStore'
import { GlassCard } from '../ui/GlassCard'
@@ -8,14 +8,16 @@ import { SliderControl } from './SliderControl'
import { ApiConfig } from './ApiConfig'
import { PersonaPanel } from '../personas/PersonaPanel'
import { useVoiceStore } from '../../stores/voiceStore'
+import { checkWhisperAvailable } from '../../api/voice'
export function SettingsPage() {
const { settings, updateSettings, resetSettings } = useSettingsStore()
const { setView } = useUIStore()
const voiceSettings = useVoiceStore()
const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([])
+ const [whisperStatus, setWhisperStatus] = useState<{ available: boolean; backend: string | null; error?: string } | null>(null)
+ const [whisperLoading, setWhisperLoading] = useState(true)
- const sttSupported = typeof window !== 'undefined' && ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)
const ttsSupported = typeof window !== 'undefined' && 'speechSynthesis' in window
useEffect(() => {
@@ -29,6 +31,14 @@ export function SettingsPage() {
return () => speechSynthesis.removeEventListener('voiceschanged', loadVoices)
}, [ttsSupported])
+ // Check Whisper availability on mount
+ useEffect(() => {
+ setWhisperLoading(true)
+ checkWhisperAvailable()
+ .then(setWhisperStatus)
+ .finally(() => setWhisperLoading(false))
+ }, [])
+
return (
<div className="h-full overflow-y-auto scrollbar-thin p-6">
<div className="max-w-2xl mx-auto space-y-6">
@@ -117,15 +127,19 @@ export function SettingsPage() {
<GlassCard>
<h2 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wider">Voice</h2>
<div className="space-y-4">
- {/* Support indicators */}
+ {/* Local STT status */}
<div className="flex items-center gap-4">
<div className="flex items-center gap-1.5">
- {sttSupported ? (
+ {whisperLoading ? (
+ <Loader2 size={14} className="animate-spin text-gray-400" />
+ ) : whisperStatus?.available ? (
<Check size={14} className="text-green-500" />
) : (
<X size={14} className="text-red-500" />
)}
- <span className="text-xs text-gray-600 dark:text-gray-300">Speech-to-Text</span>
+ <span className="text-xs text-gray-600 dark:text-gray-300">
+ Local STT{whisperStatus?.backend ? `: ${whisperStatus.backend}` : ''}
+ </span>
</div>
<div className="flex items-center gap-1.5">
{ttsSupported ? (
@@ -137,6 +151,13 @@ export function SettingsPage() {
</div>
</div>
+ {/* Whisper install hint */}
+ {whisperStatus && !whisperStatus.available && (
+ <div className="text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded-lg px-3 py-2">
+ Whisper not installed. Run: <code className="font-mono bg-amber-100 dark:bg-amber-900/40 px-1 rounded">pip install faster-whisper</code>
+ </div>
+ )}
+
{/* TTS Enabled toggle */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.ts
index 06933912..1f087dcc 100644
--- a/src/hooks/useVoice.ts
+++ b/src/hooks/useVoice.ts
@@ -8,28 +8,21 @@ import {
stopSpeaking as stopSpeakingApi,
getVoicesAsync,
createAudioRecorder,
+ transcribeAudio,
+ type AudioRecorder,
} from "../api/voice";
export function useVoice() {
const store = useVoiceStore();
- const recorderRef = useRef<ReturnType<typeof createAudioRecorder> | null>(null);
- const onInterimRef = useRef<((text: string) => void) | null>(null);
+ const recorderRef = useRef<AudioRecorder | null>(null);
const sttSupported = isSpeechRecognitionSupported();
const ttsSupported = isSpeechSynthesisSupported();
- const startRecording = useCallback(async (onInterimTranscript?: (text: string) => void) => {
+ const startRecording = useCallback(async () => {
if (recorderRef.current?.isRecording()) return;
- onInterimRef.current = onInterimTranscript || null;
-
- const recorder = createAudioRecorder({
- onInterimTranscript: (text: string) => {
- if (onInterimRef.current) {
- onInterimRef.current(text);
- }
- },
- });
+ const recorder = createAudioRecorder();
recorderRef.current = recorder;
try {
@@ -46,17 +39,30 @@ export function useVoice() {
if (!recorderRef.current) return "";
try {
- const { transcript } = await recorderRef.current.stop();
+ // Stop recording and get the audio blob
+ const blob = await recorderRef.current.stop();
store.setRecording(false);
- store.setTranscript(transcript);
recorderRef.current = null;
- onInterimRef.current = null;
- return transcript;
+
+ if (blob.size === 0) return "";
+
+ // Transcribe locally via Whisper
+ store.setTranscribing(true);
+ try {
+ const transcript = await transcribeAudio(blob);
+ store.setTranscript(transcript);
+ return transcript;
+ } catch (err) {
+ console.error("Whisper transcription error:", err);
+ return "";
+ } finally {
+ store.setTranscribing(false);
+ }
} catch (err) {
console.error("Failed to stop recording:", err);
store.setRecording(false);
+ store.setTranscribing(false);
recorderRef.current = null;
- onInterimRef.current = null;
return "";
}
}, [store]);
@@ -114,6 +120,7 @@ export function useVoice() {
return {
isRecording: store.isRecording,
+ isTranscribing: store.isTranscribing,
isSpeaking: store.isSpeaking,
transcript: store.transcript,
sttSupported,
diff --git a/src/stores/voiceStore.ts b/src/stores/voiceStore.ts
index 98e04159..c96e91fd 100644
--- a/src/stores/voiceStore.ts
+++ b/src/stores/voiceStore.ts
@@ -4,6 +4,7 @@ import { persist } from "zustand/middleware";
interface VoiceState {
// Transient state (not persisted)
isRecording: boolean;
+ isTranscribing: boolean;
isSpeaking: boolean;
transcript: string;
@@ -17,6 +18,7 @@ interface VoiceState {
// Actions
setRecording: (recording: boolean) => void;
+ setTranscribing: (transcribing: boolean) => void;
setSpeaking: (speaking: boolean) => void;
setTranscript: (transcript: string) => void;
updateVoiceSettings: (
@@ -37,6 +39,7 @@ export const useVoiceStore = create<VoiceState>()(
(set) => ({
// Transient state
isRecording: false,
+ isTranscribing: false,
isSpeaking: false,
transcript: "",
@@ -50,6 +53,7 @@ export const useVoiceStore = create<VoiceState>()(
// Actions
setRecording: (recording) => set({ isRecording: recording }),
+ setTranscribing: (transcribing) => set({ isTranscribing: transcribing }),
setSpeaking: (speaking) => set({ isSpeaking: speaking }),
setTranscript: (transcript) => set({ transcript }),
@@ -58,6 +62,7 @@ export const useVoiceStore = create<VoiceState>()(
resetTransient: () =>
set({
isRecording: false,
+ isTranscribing: false,
isSpeaking: false,
transcript: "",
}),
diff --git a/vite.config.ts b/vite.config.ts
index b3b67099..1ee2a0d7 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -9,6 +9,7 @@ import http from 'http'
import { config } from 'dotenv'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
+import os from 'os'
// Load .env file from project root
const __dirname = dirname(fileURLToPath(import.meta.url))
@@ -971,6 +972,158 @@ function comfyLauncher(): Plugin {
}
})
})
+
+ // --- Whisper STT Endpoints ---
+
+ // API: Check if Whisper is available
+ server.middlewares.use('/local-api/transcribe-status', (req, res) => {
+ if (req.method !== 'GET') { res.writeHead(405); res.end(); return }
+
+ const pythonBin = (() => {
+ if (process.platform !== 'win32') return 'python3'
+ try {
+ const paths = execSync('where python', { encoding: 'utf8' }).trim().split('\n')
+ const real = paths.find((p: string) => !p.includes('WindowsApps'))
+ return real ? real.trim() : 'python'
+ } catch { return 'python' }
+ })()
+
+ // Try faster-whisper first
+ try {
+ execSync(`${pythonBin} -c "import faster_whisper; print('ok')"`, { encoding: 'utf8', timeout: 10000 })
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ available: true, backend: 'faster-whisper' }))
+ return
+ } catch { /* not installed */ }
+
+ // Try openai-whisper
+ try {
+ execSync(`${pythonBin} -c "import whisper; print('ok')"`, { encoding: 'utf8', timeout: 10000 })
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ available: true, backend: 'whisper' }))
+ return
+ } catch { /* not installed */ }
+
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ available: false, backend: null, error: 'Install faster-whisper: pip install faster-whisper' }))
+ })
+
+ // API: Transcribe audio via local Whisper
+ server.middlewares.use('/local-api/transcribe', (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
+
+ const chunks: Buffer[] = []
+ req.on('data', (chunk: Buffer) => chunks.push(chunk))
+ req.on('end', () => {
+ try {
+ const audioBuffer = Buffer.concat(chunks)
+ if (audioBuffer.length === 0) {
+ res.writeHead(400, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Empty audio data', transcript: '' }))
+ return
+ }
+
+ // Determine file extension from content-type
+ const contentType = req.headers['content-type'] || 'audio/webm'
+ let ext = '.webm'
+ if (contentType.includes('wav')) ext = '.wav'
+ else if (contentType.includes('mp3') || contentType.includes('mpeg')) ext = '.mp3'
+ else if (contentType.includes('ogg')) ext = '.ogg'
+ else if (contentType.includes('mp4') || contentType.includes('m4a')) ext = '.m4a'
+
+ const tmpFile = join(os.tmpdir(), `whisper-${Date.now()}${ext}`)
+ const fs = require('fs')
+ fs.writeFileSync(tmpFile, audioBuffer)
+
+ const pythonBin = (() => {
+ if (process.platform !== 'win32') return 'python3'
+ try {
+ const paths = execSync('where python', { encoding: 'utf8' }).trim().split('\n')
+ const real = paths.find((p: string) => !p.includes('WindowsApps'))
+ return real ? real.trim() : 'python'
+ } catch { return 'python' }
+ })()
+
+ // Build Python scripts as temp files to avoid shell escaping issues
+ const fwScript = join(os.tmpdir(), `fw-${Date.now()}.py`)
+ const owScript = join(os.tmpdir(), `ow-${Date.now()}.py`)
+ const audioPath = tmpFile.replace(/\\/g, '/')
+
+ fs.writeFileSync(fwScript,
+ "from faster_whisper import WhisperModel\n" +
+ "model = WhisperModel('base', device='cpu', compute_type='int8')\n" +
+ "segments, info = model.transcribe('" + audioPath + "')\n" +
+ "text = ' '.join([s.text for s in segments]).strip()\n" +
+ "print(text)\n" +
+ "print('LANG:' + info.language)\n"
+ )
+
+ fs.writeFileSync(owScript,
+ "import whisper\n" +
+ "model = whisper.load_model('base')\n" +
+ "result = model.transcribe('" + audioPath + "')\n" +
+ "print(result['text'].strip())\n" +
+ "print('LANG:' + result.get('language', 'en'))\n"
+ )
+
+ let transcript = ''
+ let language = 'en'
+ let success = false
+
+ // Try faster-whisper
+ try {
+ const output = execSync(`${pythonBin} ${fwScript}`, {
+ encoding: 'utf8',
+ timeout: 30000,
+ }).trim()
+ const lines = output.split('\n')
+ const langLine = lines.find((l: string) => l.startsWith('LANG:'))
+ if (langLine) {
+ language = langLine.replace('LANG:', '')
+ lines.splice(lines.indexOf(langLine), 1)
+ }
+ transcript = lines.join(' ').trim()
+ success = true
+ } catch { /* try fallback */ }
+
+ // Try openai-whisper
+ if (!success) {
+ try {
+ const output = execSync(`${pythonBin} ${owScript}`, {
+ encoding: 'utf8',
+ timeout: 60000,
+ }).trim()
+ const lines = output.split('\n')
+ const langLine = lines.find((l: string) => l.startsWith('LANG:'))
+ if (langLine) {
+ language = langLine.replace('LANG:', '')
+ lines.splice(lines.indexOf(langLine), 1)
+ }
+ transcript = lines.join(' ').trim()
+ success = true
+ } catch { /* neither works */ }
+ }
+
+ // Clean up temp files
+ try { fs.unlinkSync(tmpFile) } catch { /* ignore */ }
+ try { fs.unlinkSync(fwScript) } catch { /* ignore */ }
+ try { fs.unlinkSync(owScript) } catch { /* ignore */ }
+
+ if (!success) {
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Install faster-whisper: pip install faster-whisper', transcript: '' }))
+ return
+ }
+
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ transcript, language }))
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: String(err), transcript: '' }))
+ }
+ })
+ })
+
},
}
}