Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat: added debug logger, fixed adding ffmpeg to PATH
Gabriel Steinec1356b797bb
diff --git a/DEBUG.md b/DEBUG.mdnew file mode 100644index 000000000..e79346464--- /dev/null+++ b/DEBUG.md@@ -0,0 +1,170 @@+# OpenWispr Debug Mode++## Enabling Debug Logging++When experiencing issues like "no audio detected", you can enable verbose debug logging to help diagnose the problem.++### Method 1: Command Line Flag+Run the app with the `--debug` flag:+```bash+# macOS+/Applications/OpenWispr.app/Contents/MacOS/OpenWispr --debug++# Windows+OpenWispr.exe --debug+```++### Method 2: Environment Variable+Set the `OPENWISPR_DEBUG` environment variable:+```bash+# macOS/Linux+export OPENWISPR_DEBUG=true+open /Applications/OpenWispr.app++# Windows+set OPENWISPR_DEBUG=true+OpenWispr.exe+```++## Finding the Debug Logs++When debug mode is enabled, logs are saved to:++- **macOS**: `~/Library/Application Support/open-wispr/logs/debug-[timestamp].log`+- **Windows**: `%APPDATA%/open-wispr/logs/debug-[timestamp].log`+- **Linux**: `~/.config/open-wispr/logs/debug-[timestamp].log`++## What the Logs Include++The debug logs capture comprehensive information about the audio pipeline:++1. **π¬ FFmpeg Detection**+ - All paths checked for FFmpeg (bundled and system)+ - File existence, permissions, and executable status+ - ASAR unpacking verification+ - Environment variable configuration+ - Final FFmpeg path resolution++2. **ποΈ Audio Recording**+ - Microphone permission requests and grants+ - Audio track details (enabled, muted, label, settings)+ - Real-time audio chunk reception (size and count)+ - Audio level analysis (average, max, silence detection)+ - Recording duration and blob creation++3. **π Audio Processing**+ - Audio data types and conversion+ - Temporary file creation and permissions+ - File sizes at each stage+ - First bytes of audio data (hex)+ - Whisper command construction+ - Python process environment setup++4. **π‘ Process Communication**+ - IPC messages between renderer and main process+ - Audio blob transfer details+ - Whisper process stdout/stderr+ - Process exit codes+ - Error propagation++5. **π― Pipeline Stages**+ - Each stage is clearly marked with descriptive labels+ - Timing information for performance analysis+ - Success/failure status at each step++## Common Issues and What to Look For++### "No Audio Detected"+Look for these specific log entries:+- `Audio appears to be silent` - Check `maxLevel` value (should be > 0.01)+- `Audio chunk received, size: 0` - MediaRecorder not capturing data+- `FFmpeg not available` - FFmpeg path resolution failed+- `Bundled FFmpeg not found` - ASAR unpacking issue+- `FFmpeg exists but is not executable` - Permission problem+- `No audio chunks received after 3 seconds` - Microphone not working+- `Whisper reported no audio detected` - FFmpeg processing failed++### Transcription Fails+Look for:+- `Whisper stderr:` - Check for Python errors or FFmpeg issues+- `Failed to parse Whisper output` - Invalid JSON response+- `Process closed with code: [non-zero]` - Process failure+- `Audio file is empty after writing` - File I/O issue+- `Unsupported audio data type` - Audio format problem++### Slow Performance+Look for:+- Large `blobSize` values (> 10MB) - Consider audio optimization+- Multiple `Checking alternative path` entries - FFmpeg search overhead+- `Whisper process closed` with long delays - Model processing time++### Permission Issues+Look for:+- `Microphone Access Denied` - System permission required+- `dirReadable: false` - Directory access problems+- `permissions: [number]` - Check file permission octals++## Interpreting Key Debug Messages++### FFmpeg Path Resolution+```+π¬ FFmpeg Debug - Initial ffmpeg-static path {+ "ffmpegPath": "/path/to/ffmpeg",+ "exists": true,+ "fileInfo": {+ "size": 74750976,+ "isFile": true,+ "isExecutable": true,+ "permissions": "100755"+ }+}+```+- `exists: false` - Path resolution failed+- `isExecutable: false` - Permission issue+- `permissions` - Should be executable (755 or similar)++### Audio Level Analysis+```+π Audio level analysis {+ "duration": "3.45s",+ "samples": 165888,+ "averageLevel": "0.002134",+ "maxLevel": "0.045632",+ "isSilent": false+}+```+- `maxLevel < 0.01` - Audio too quiet/silent+- `samples: 0` - No audio data captured+- `isSilent: true` - Definite silence detected++### Whisper Process Environment+```+π Starting process {+ "command": "python3",+ "args": ["whisper_bridge.py", "/tmp/whisper_audio.wav", "--model", "base"],+ "env": {+ "FFMPEG_PATH": "/path/to/ffmpeg",+ "FFMPEG_EXECUTABLE": "/path/to/ffmpeg",+ "FFMPEG_BINARY": "/path/to/ffmpeg"+ }+}+```+- All three FFmpeg env vars should point to valid path+- Empty env vars indicate FFmpeg not found++## Sharing Debug Logs++When reporting issues:++1. Enable debug mode and reproduce the issue+2. Find the debug log file (path is shown at startup)+3. Look for any sensitive information and redact if needed+4. Share the relevant portions of the log file+5. Include the error message shown to the user+6. Note your system configuration (macOS version, mic type)++## Disabling Debug Mode++Debug mode is disabled by default. To ensure it's off:+- Don't use the `--debug` flag+- Unset the environment variable: `unset OPENWISPR_DEBUG`\ No newline at end of filediff --git a/main.js b/main.jsindex 684460e01..f1263da8e 100644--- a/main.js+++ b/main.js@@ -5,7 +5,6 @@ process.on("uncaughtException", (error) => {console.error("Uncaught Exception:", error);// Don't exit the process for EPIPE errors as they're harmlessif (error.code === "EPIPE") {- console.log("EPIPE error caught and ignored");return;}// For other errors, log and continue@@ -17,6 +16,7 @@ process.on("unhandledRejection", (reason, promise) => {});// Import helper modules+const debugLogger = require("./src/helpers/debugLogger");const EnvironmentManager = require("./src/helpers/environment");const WindowManager = require("./src/helpers/windowManager");const DatabaseManager = require("./src/helpers/database");@@ -53,7 +53,7 @@ async function startApp() {// Initialize Whisper manager at startup (don't await to avoid blocking)whisperManager.initializeAtStartup().catch((err) => {- console.log("Whisper initialization info:", err.message);+ // Whisper not being available at startup is not critical});// Create main window@@ -89,7 +89,14 @@ async function startApp() {}// App event handlers-app.whenReady().then(startApp);+app.whenReady().then(() => {+ // Log debug status+ if (debugLogger.isEnabled()) {+ console.log(`π Debug mode enabled - Logs saved to: ${debugLogger.getLogPath()}`);+ }++ startApp();+});app.on("window-all-closed", () => {if (process.platform !== "darwin") {diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex f310c5684..f534693bc 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -1,6 +1,7 @@import TextCleanup from "../utils/textCleanup";import ReasoningService from "../services/ReasoningService";+class AudioManager {constructor() {this.mediaRecorder = null;@@ -23,12 +24,12 @@ class AudioManager {async startRecording() {try {if (this.isRecording) {- console.warn("Recording already in progress");return false;}const stream = await navigator.mediaDevices.getUserMedia({ audio: true });+this.mediaRecorder = new MediaRecorder(stream);this.audioChunks = [];@@ -42,6 +43,10 @@ class AudioManager {this.onStateChange?.({ isRecording: false, isProcessing: true });const audioBlob = new Blob(this.audioChunks, { type: "audio/wav" });++ if (audioBlob.size === 0) {+ }+await this.processAudio(audioBlob);// Clean up stream@@ -54,10 +59,25 @@ class AudioManager {return true;} catch (error) {- console.error("Recording error:", error);++ // Provide more specific error messages+ let errorTitle = "Recording Error";+ let errorDescription = `Failed to access microphone: ${error.message}`;++ if (error.name === "NotAllowedError" || error.name === "PermissionDeniedError") {+ errorTitle = "Microphone Access Denied";+ errorDescription = "Please grant microphone permission in your system settings and try again.";+ } else if (error.name === "NotFoundError" || error.name === "DevicesNotFoundError") {+ errorTitle = "No Microphone Found";+ errorDescription = "No microphone was detected. Please connect a microphone and try again.";+ } else if (error.name === "NotReadableError" || error.name === "TrackStartError") {+ errorTitle = "Microphone In Use";+ errorDescription = "The microphone is being used by another application. Please close other apps and try again.";+ }+this.onError?.({- title: "Recording Error",- description: `Failed to access microphone: ${error.message}`,+ title: errorTitle,+ description: errorDescription,});return false;}@@ -78,9 +98,7 @@ class AudioManager {const useLocalWhisper =localStorage.getItem("useLocalWhisper") === "true";const whisperModel = localStorage.getItem("whisperModel") || "base";- const useReasoning = localStorage.getItem("useReasoningModel") === "true";- const reasoningModel =- localStorage.getItem("reasoningModel") || "gpt-3.5-turbo";+let result;if (useLocalWhisper) {@@ -90,11 +108,13 @@ class AudioManager {}this.onTranscriptionComplete?.(result);} catch (error) {- console.error(`π§ [AudioManager] β Transcription error:`, error);- this.onError?.({- title: "Transcription Error",- description: `Transcription failed: ${error.message}`,- });+ // Don't show error here if it's "No audio detected" - already shown elsewhere+ if (error.message !== "No audio detected") {+ this.onError?.({+ title: "Transcription Error",+ description: `Transcription failed: ${error.message}`,+ });+ }} finally {this.isProcessing = false;this.onStateChange?.({ isRecording: false, isProcessing: false });@@ -127,6 +147,18 @@ class AudioManager {}async processWithLocalWhisper(audioBlob, model = "base") {++ // Analyze audio levels first+ const audioAnalysis = await this.analyzeAudioLevels(audioBlob);+ if (audioAnalysis && audioAnalysis.isSilent) {+ // Show error to user immediately+ this.onError?.({+ title: "No Audio Detected",+ description: "The recording appears to be silent. Please check that your microphone is working and not muted.",+ });+ // Still continue to try transcription in case analysis was wrong+ }+try {const arrayBuffer = await audioBlob.arrayBuffer();@@ -141,6 +173,7 @@ class AudioManager {arrayBuffer,options);+if (result.success && result.text) {let text = AudioManager.cleanTranscription(result.text);@@ -153,43 +186,36 @@ class AudioManager {result.success === false &&result.message === "No audio detected") {+ // Show specific error to user with more details+ this.onError?.({+ title: "No Audio Detected",+ description: "The recording contained no detectable audio. Please check your microphone settings.",+ });throw new Error("No audio detected");} else {throw new Error(result.error || "Local Whisper transcription failed");}} catch (error) {- console.error("Local Whisper error:", error);-- // Check if it's a "No audio detected" error and don't retryif (error.message === "No audio detected") {throw error;}- // Try fallback to OpenAI API ONLY if enabled AND we're in local mode- const allowOpenAIFallback =- localStorage.getItem("allowOpenAIFallback") === "true";+ const allowOpenAIFallback = localStorage.getItem("allowOpenAIFallback") === "true";const isLocalMode = localStorage.getItem("useLocalWhisper") === "true";if (allowOpenAIFallback && isLocalMode) {- console.log("Falling back to OpenAI API...");try {const fallbackResult = await this.processWithOpenAIAPI(audioBlob);- // Mark the result as fallback for user awarenessreturn { ...fallbackResult, source: "openai-fallback" };} catch (fallbackError) {- // If OpenAI fallback also fails, throw the original error- throw new Error(- `Local Whisper failed: ${error.message}. OpenAI fallback also failed: ${fallbackError.message}`- );+ throw new Error(`Local Whisper failed: ${error.message}. OpenAI fallback also failed: ${fallbackError.message}`);}} else {- // No fallback allowed - strict local modethrow new Error(`Local Whisper failed: ${error.message}`);}}}- // Get and cache API key for performanceasync getAPIKey() {if (this.cachedApiKey) {return this.cachedApiKey;@@ -214,10 +240,41 @@ class AudioManager {);}- this.cachedApiKey = apiKey; // Cache it+ this.cachedApiKey = apiKey;return apiKey;}+ async analyzeAudioLevels(audioBlob) {+ try {+ const audioContext = new (window.AudioContext || window.webkitAudioContext)();+ const arrayBuffer = await audioBlob.arrayBuffer();+ const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);++ const channelData = audioBuffer.getChannelData(0);+ let sum = 0;+ let max = 0;++ for (let i = 0; i < channelData.length; i++) {+ const sample = Math.abs(channelData[i]);+ sum += sample;+ max = Math.max(max, sample);+ }++ const average = sum / channelData.length;+ const duration = audioBuffer.duration;+++ return {+ duration,+ averageLevel: average,+ maxLevel: max,+ isSilent: max < 0.01+ };+ } catch (error) {+ return null;+ }+ }+// Convert audio to optimal format for API (reduces upload time)async optimizeAudio(audioBlob) {return new Promise((resolve) => {@@ -310,7 +367,6 @@ class AudioManager {const model = localStorage.getItem("reasoningModel") || "gpt-3.5-turbo";return await ReasoningService.processText(text, model);} catch (error) {- console.warn(`Reasoning failed, using basic cleanup:`, error.message);return AudioManager.cleanTranscription(text);}}@@ -372,7 +428,6 @@ class AudioManager {throw new Error("No text transcribed");}} catch (error) {- console.error("OpenAI API error:", error);// Try fallback to Local Whisper ONLY if enabled AND we're in OpenAI modeconst allowLocalFallback =@@ -380,7 +435,6 @@ class AudioManager {const isOpenAIMode = localStorage.getItem("useLocalWhisper") !== "true";if (allowLocalFallback && isOpenAIMode) {- console.log("Falling back to Local Whisper...");const fallbackModel =localStorage.getItem("fallbackWhisperModel") || "base";try {@@ -407,7 +461,6 @@ class AudioManager {// If local fallback fails, throw the original OpenAI errorthrow error;} catch (fallbackError) {- console.error("Local fallback also failed:", fallbackError);throw new Error(`OpenAI API failed: ${error.message}. Local fallback also failed: ${fallbackError.message}`);@@ -436,7 +489,6 @@ class AudioManager {await window.electronAPI.saveTranscription(text);return true;} catch (error) {- console.error("Failed to save transcription:", error);return false;}}diff --git a/src/helpers/debugLogger.js b/src/helpers/debugLogger.jsnew file mode 100644index 000000000..c66d7f8ea--- /dev/null+++ b/src/helpers/debugLogger.js@@ -0,0 +1,215 @@+const fs = require('fs');+const path = require('path');+const { app } = require('electron');++class DebugLogger {+ constructor() {+ // Check multiple sources for debug mode+ this.debugMode = process.env.OPENWISPR_DEBUG === 'true' ||+ process.argv.includes('--debug') ||+ process.env.NODE_ENV === 'development' ||+ this.checkDebugFile();+ this.logFile = null;+ this.logStream = null;++ if (this.debugMode) {+ // Create logs directory+ const logsDir = path.join(app.getPath('userData'), 'logs');+ if (!fs.existsSync(logsDir)) {+ fs.mkdirSync(logsDir, { recursive: true });+ }++ // Create log file with timestamp+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');+ this.logFile = path.join(logsDir, `debug-${timestamp}.log`);++ // Create write stream for better performance+ this.logStream = fs.createWriteStream(this.logFile, { flags: 'a' });++ this.log('π Debug logging enabled', `Log file: ${this.logFile}`);+ this.log('System Info:', {+ platform: process.platform,+ nodeVersion: process.version,+ electronVersion: process.versions.electron,+ appPath: app.getAppPath(),+ userDataPath: app.getPath('userData'),+ resourcesPath: process.resourcesPath,+ environment: process.env.NODE_ENV+ });+ }+ }++ log(...args) {+ if (!this.debugMode) return;++ const timestamp = new Date().toISOString();+ const message = args.map(arg =>+ typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)+ ).join(' ');++ const logLine = `[${timestamp}] ${message}\n`;++ console.log(...args);++ if (this.logStream) {+ this.logStream.write(logLine);+ }+ }++ error(...args) {+ if (!this.debugMode) return;++ const timestamp = new Date().toISOString();+ const message = 'β ERROR: ' + args.map(arg =>+ typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)+ ).join(' ');++ const logLine = `[${timestamp}] ${message}\n`;++ console.error(...args);++ if (this.logStream) {+ this.logStream.write(logLine);+ }+ }++ logFFmpegDebug(context, ffmpegPath, additionalInfo = {}) {+ if (!this.debugMode) return;++ const debugInfo = {+ context,+ ffmpegPath,+ exists: ffmpegPath ? fs.existsSync(ffmpegPath) : false,+ ...additionalInfo+ };++ if (ffmpegPath && fs.existsSync(ffmpegPath)) {+ try {+ const stats = fs.statSync(ffmpegPath);+ debugInfo.fileInfo = {+ size: stats.size,+ isFile: stats.isFile(),+ isExecutable: !!(stats.mode & fs.constants.X_OK),+ permissions: stats.mode.toString(8),+ modified: stats.mtime+ };+ } catch (e) {+ debugInfo.statError = e.message;+ }+ }++ // Check parent directory permissions+ if (ffmpegPath) {+ const dir = path.dirname(ffmpegPath);+ try {+ fs.accessSync(dir, fs.constants.R_OK);+ debugInfo.dirReadable = true;+ } catch (e) {+ debugInfo.dirReadable = false;+ debugInfo.dirError = e.message;+ }+ }++ // Check all possible FFmpeg locations+ const possiblePaths = [+ ffmpegPath,+ ffmpegPath?.replace('app.asar', 'app.asar.unpacked'),+ path.join(process.resourcesPath || '', 'app.asar.unpacked', 'node_modules', 'ffmpeg-static', process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'),+ '/usr/local/bin/ffmpeg',+ '/opt/homebrew/bin/ffmpeg',+ '/usr/bin/ffmpeg'+ ].filter(Boolean);++ debugInfo.pathChecks = possiblePaths.map(p => ({+ path: p,+ exists: fs.existsSync(p)+ }));++ this.log(`π¬ FFmpeg Debug - ${context}`, debugInfo);+ }++ logAudioData(context, audioBlob) {+ if (!this.debugMode) return;++ const audioInfo = {+ context,+ type: audioBlob?.type || 'unknown',+ size: audioBlob?.size || 0,+ constructor: audioBlob?.constructor?.name || 'unknown'+ };++ if (audioBlob instanceof ArrayBuffer) {+ audioInfo.byteLength = audioBlob.byteLength;+ // Check first few bytes+ const view = new Uint8Array(audioBlob, 0, Math.min(16, audioBlob.byteLength));+ audioInfo.firstBytes = Array.from(view).map(b => b.toString(16).padStart(2, '0')).join(' ');+ } else if (audioBlob instanceof Uint8Array) {+ audioInfo.byteLength = audioBlob.byteLength;+ const view = audioBlob.slice(0, Math.min(16, audioBlob.byteLength));+ audioInfo.firstBytes = Array.from(view).map(b => b.toString(16).padStart(2, '0')).join(' ');+ }++ this.log('π Audio Data Debug', audioInfo);+ }++ logProcessStart(command, args, options = {}) {+ if (!this.debugMode) return;++ this.log('π Starting process', {+ command,+ args,+ cwd: options.cwd || process.cwd(),+ env: {+ FFMPEG_PATH: options.env?.FFMPEG_PATH,+ FFMPEG_EXECUTABLE: options.env?.FFMPEG_EXECUTABLE,+ FFMPEG_BINARY: options.env?.FFMPEG_BINARY,+ PATH_preview: options.env?.PATH?.substring(0, 200) + '...'+ }+ });+ }++ logProcessOutput(processName, type, data) {+ if (!this.debugMode) return;++ const output = data.toString().trim();+ if (output) {+ this.log(`π ${processName} ${type}:`, output);+ }+ }++ logWhisperPipeline(stage, details) {+ if (!this.debugMode) return;++ this.log(`ποΈ Whisper Pipeline - ${stage}`, details);+ }++ getLogPath() {+ return this.logFile;+ }++ isEnabled() {+ return this.debugMode;+ }++ close() {+ if (this.logStream) {+ this.log('π Debug logger closing');+ this.logStream.end();+ this.logStream = null;+ }+ }++ checkDebugFile() {+ try {+ const debugFilePath = path.join(app.getPath('userData'), 'ENABLE_DEBUG');+ return fs.existsSync(debugFilePath);+ } catch (e) {+ return false;+ }+ }+}++// Singleton instance+const debugLogger = new DebugLogger();++module.exports = debugLogger;\ No newline at end of filediff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex e3b77aea9..90d30eb74 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1,5 +1,6 @@const { ipcMain, app, shell } = require("electron");const AppUtils = require("../utils");+const debugLogger = require("./debugLogger");class IPCHandlers {constructor(managers) {@@ -115,20 +116,34 @@ class IPCHandlers {ipcMain.handle("transcribe-local-whisper",async (event, audioBlob, options = {}) => {+ debugLogger.log('transcribe-local-whisper called', {+ audioBlobType: typeof audioBlob,+ audioBlobSize: audioBlob?.byteLength || audioBlob?.length || 0,+ options+ });+try {const result = await this.whisperManager.transcribeLocalWhisper(audioBlob,options);+ debugLogger.log('Whisper result', {+ success: result.success,+ hasText: !!result.text,+ message: result.message,+ error: result.error+ });+// Check if no audio was detected and send appropriate eventif (!result.success && result.message === "No audio detected") {+ debugLogger.log('Sending no-audio-detected event to renderer');event.sender.send("no-audio-detected");}return result;} catch (error) {- console.error("β Local Whisper transcription error:", error);+ debugLogger.error('Local Whisper transcription error', error);throw error;}}@@ -153,7 +168,6 @@ class IPCHandlers {});return result;} catch (error) {- console.error("β Python installation error:", error);throw error;}});@@ -184,7 +198,6 @@ class IPCHandlers {return result;} catch (error) {- console.error("β Whisper installation error:", error);throw error;}});@@ -208,7 +221,6 @@ class IPCHandlers {return result;} catch (error) {- console.error("β Model download error:", error);// Send error eventevent.sender.send("whisper-download-progress", {@@ -247,7 +259,6 @@ class IPCHandlers {AppUtils.cleanup(this.windowManager.mainWindow);return { success: true, message: "Cleanup completed successfully" };} catch (error) {- console.error("β Cleanup error:", error);throw error;}});@@ -270,7 +281,6 @@ class IPCHandlers {await shell.openExternal(url);return { success: true };} catch (error) {- console.error("β Failed to open external URL:", error);return { success: false, error: error.message };}});diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex 3cbc8d598..70c8eb64c 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -6,6 +6,7 @@ const path = require("path");const crypto = require("crypto");const PythonInstaller = require("./pythonInstaller");const { runCommand, TIMEOUTS } = require("../utils/process");+const debugLogger = require("./debugLogger");class WhisperManager {constructor() {@@ -36,12 +37,27 @@ class WhisperManager {await this.checkWhisperInstallation();this.isInitialized = true;} catch (error) {- console.error("Whisper not available at startup:", error.message);+ // Whisper not available at startup is not criticalthis.isInitialized = true;}}async transcribeLocalWhisper(audioBlob, options = {}) {+ debugLogger.logWhisperPipeline('transcribeLocalWhisper - start', {+ options,+ audioBlobType: audioBlob?.constructor?.name,+ audioBlobSize: audioBlob?.byteLength || audioBlob?.size || 0+ });++ // First check if FFmpeg is available+ const ffmpegCheck = await this.checkFFmpegAvailability();+ debugLogger.logWhisperPipeline('FFmpeg availability check', ffmpegCheck);++ if (!ffmpegCheck.available) {+ debugLogger.error('FFmpeg not available', ffmpegCheck);+ throw new Error(`FFmpeg not available: ${ffmpegCheck.error || 'Unknown error'}`);+ }+const tempAudioPath = await this.createTempAudioFile(audioBlob);const model = options.model || "base";const language = options.language || null;@@ -54,7 +70,6 @@ class WhisperManager {);return this.parseWhisperResult(result);} catch (error) {- console.error("Local Whisper transcription error:", error);throw error;} finally {await this.cleanupTempFile(tempAudioPath);@@ -65,6 +80,9 @@ class WhisperManager {const tempDir = os.tmpdir();const filename = `whisper_audio_${crypto.randomUUID()}.wav`;const tempAudioPath = path.join(tempDir, filename);++ debugLogger.logAudioData('createTempAudioFile', audioBlob);+ debugLogger.log('Creating temp file at:', tempAudioPath);let buffer;if (audioBlob instanceof ArrayBuffer) {@@ -76,48 +94,76 @@ class WhisperManager {} else if (audioBlob && audioBlob.buffer) {buffer = Buffer.from(audioBlob.buffer);} else {+ debugLogger.error('Unsupported audio data type:', typeof audioBlob, audioBlob);throw new Error(`Unsupported audio data type: ${typeof audioBlob}`);}++ debugLogger.log('Buffer created, size:', buffer.length);await fsPromises.writeFile(tempAudioPath, buffer);++ // Verify file was written correctly+ const stats = await fsPromises.stat(tempAudioPath);+ const fileInfo = {+ path: tempAudioPath,+ size: stats.size,+ isFile: stats.isFile(),+ permissions: stats.mode.toString(8)+ };+ debugLogger.logWhisperPipeline('Temp audio file created', fileInfo);++ if (stats.size === 0) {+ debugLogger.error('Audio file is empty after writing');+ throw new Error("Audio file is empty");+ }+return tempAudioPath;}async runWhisperProcess(tempAudioPath, model, language) {const pythonCmd = await this.findPythonExecutable();const whisperScriptPath = this.getWhisperScriptPath();++ // Check if whisper script exists+ if (!fs.existsSync(whisperScriptPath)) {+ throw new Error(`Whisper script not found at: ${whisperScriptPath}`);+ }+const args = [whisperScriptPath, tempAudioPath, "--model", model];if (language) {args.push("--language", language);}args.push("--output-format", "json");+return new Promise(async (resolve, reject) => {// Get FFmpeg path with robust production/development handlinglet ffmpegPath;try {ffmpegPath = require("ffmpeg-static");+ debugLogger.logFFmpegDebug('Initial ffmpeg-static path', ffmpegPath);// Add Windows .exe extension if missingif (process.platform === "win32" && !ffmpegPath.endsWith(".exe")) {ffmpegPath += ".exe";}- // In production, handle ASAR unpacking more robustlyif (process.env.NODE_ENV !== "development" && !fs.existsSync(ffmpegPath)) {const possiblePaths = [- // Direct ASAR replacementffmpegPath.replace("app.asar", "app.asar.unpacked"),- // Alternative unpacked locationsffmpegPath.replace(/.*app\.asar/, path.join(__dirname, "..", "..", "app.asar.unpacked")),- // Resources folder fallbackpath.join(process.resourcesPath, "app.asar.unpacked", "node_modules", "ffmpeg-static", process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg")];+ debugLogger.log('FFmpeg not found at primary path, checking alternatives');+for (const possiblePath of possiblePaths) {- if (fs.existsSync(possiblePath)) {+ const exists = fs.existsSync(possiblePath);++ if (exists) {ffmpegPath = possiblePath;+ debugLogger.log('FFmpeg found at:', ffmpegPath);break;}}@@ -125,36 +171,46 @@ class WhisperManager {// Final validation of bundled FFmpegif (!fs.existsSync(ffmpegPath)) {+ debugLogger.error('Bundled FFmpeg not found at:', ffmpegPath);throw new Error(`Bundled FFmpeg not found at ${ffmpegPath}`);}// Validate it's actually executabletry {fs.accessSync(ffmpegPath, fs.constants.X_OK);+ debugLogger.log('FFmpeg is executable');} catch (e) {+ debugLogger.error('FFmpeg exists but is not executable:', e.message);throw new Error(`FFmpeg exists but is not executable: ${ffmpegPath}`);}} catch (e) {- console.warn("Bundled FFmpeg not available:", e.message);+ debugLogger.log('Bundled FFmpeg not available, trying system FFmpeg');// Try system FFmpeg with validationconst systemFFmpeg = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";+try {- await runCommand(systemFFmpeg, ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });+ const versionResult = await runCommand(systemFFmpeg, ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });ffmpegPath = systemFFmpeg;- console.log("Using system FFmpeg");+ debugLogger.log('Using system FFmpeg');} catch (systemError) {- console.error("System FFmpeg also unavailable:", systemError.message);+ debugLogger.error('System FFmpeg also unavailable:', systemError.message);ffmpegPath = systemFFmpeg; // Last resort - let Python handle the error}}- // Enhanced environment setup+ // Enhanced environment setup - Python script checks multiple env vars+ // Make sure to use absolute paths+ const absoluteFFmpegPath = path.resolve(ffmpegPath);const enhancedEnv = {...process.env,- FFMPEG_PATH: ffmpegPath,+ FFMPEG_PATH: absoluteFFmpegPath,+ FFMPEG_EXECUTABLE: absoluteFFmpegPath,+ FFMPEG_BINARY: absoluteFFmpegPath,};++ debugLogger.logFFmpegDebug('Setting FFmpeg env vars', absoluteFFmpegPath);// Add ffmpeg directory to PATH if we have a valid pathif (ffmpegPath) {@@ -165,9 +221,54 @@ class WhisperManager {if (!currentPath.includes(ffmpegDir)) {enhancedEnv.PATH = `${ffmpegDir}${pathSeparator}${currentPath}`;}++ // CRITICAL: Also create a symlink or use the actual unpacked path+ // The issue is that the ffmpeg path points to the ASAR archive, but we need the unpacked version+ if (ffmpegPath.includes('app.asar') && !ffmpegPath.includes('app.asar.unpacked')) {+ const unpackedPath = ffmpegPath.replace('app.asar', 'app.asar.unpacked');+ if (fs.existsSync(unpackedPath)) {+ ffmpegPath = unpackedPath;+ enhancedEnv.FFMPEG_PATH = unpackedPath;+ enhancedEnv.FFMPEG_EXECUTABLE = unpackedPath;+ enhancedEnv.FFMPEG_BINARY = unpackedPath;+ // Update PATH with the unpacked directory+ const unpackedDir = path.dirname(unpackedPath);+ enhancedEnv.PATH = `${unpackedDir}${pathSeparator}${currentPath}`;+ debugLogger.log('Using unpacked FFmpeg path:', unpackedPath);+ }+ }} else {- console.warn("No valid FFmpeg path found, transcription may fail");+ debugLogger.error('No valid FFmpeg path found, transcription may fail');}++ // Add common system paths for macOS GUI launches+ if (process.platform === "darwin") {+ const commonPaths = [+ "/usr/local/bin",+ "/opt/homebrew/bin",+ "/opt/homebrew/sbin",+ "/usr/bin",+ "/bin",+ "/usr/sbin",+ "/sbin"+ ];++ const currentPath = enhancedEnv.PATH || "";+ const pathsToAdd = commonPaths.filter(p => !currentPath.includes(p));++ if (pathsToAdd.length > 0) {+ enhancedEnv.PATH = `${currentPath}:${pathsToAdd.join(":")}`;+ debugLogger.log('Added system paths for GUI launch');+ }+ }++ const envDebugInfo = {+ FFMPEG_PATH: enhancedEnv.FFMPEG_PATH,+ PATH_includes_ffmpeg: enhancedEnv.PATH?.includes(path.dirname(ffmpegPath || "")),+ pythonCmd,+ args: args.join(" ")+ };+ debugLogger.logProcessStart(pythonCmd, args, { env: enhancedEnv });const whisperProcess = spawn(pythonCmd, args, {stdio: ["ignore", "pipe", "pipe"],@@ -183,25 +284,20 @@ class WhisperManager {const timeout = setTimeout(() => {if (!isResolved) {whisperProcess.kill("SIGTERM");- reject(new Error("Whisper transcription timed out (60 seconds)"));+ reject(new Error("Whisper transcription timed out (120 seconds)"));}- }, 60000);+ }, 1200000);whisperProcess.stdout.on("data", (data) => {stdout += data.toString();+ debugLogger.logProcessOutput('Whisper', 'stdout', data);});whisperProcess.stderr.on("data", (data) => {const stderrText = data.toString();stderr += stderrText;- if (- stderrText.includes("ffmpeg") ||- stderrText.includes("Error") ||- stderrText.includes("failed")- ) {- console.error("Whisper error:", stderrText.trim());- }+ debugLogger.logProcessOutput('Whisper', 'stderr', data);});whisperProcess.on("close", (code) => {@@ -209,7 +305,14 @@ class WhisperManager {isResolved = true;clearTimeout(timeout);+ debugLogger.logWhisperPipeline('Process closed', {+ code,+ stdoutLength: stdout.length,+ stderrLength: stderr.length+ });+if (code === 0) {+ debugLogger.log('Transcription successful');resolve(stdout);} else {// Better error message for FFmpeg issues@@ -238,6 +341,7 @@ class WhisperManager {}parseWhisperResult(stdout) {+ debugLogger.logWhisperPipeline('Parsing result', { stdoutLength: stdout.length });try {// Clean stdout by removing any non-JSON contentconst lines = stdout.split("\n").filter((line) => line.trim());@@ -257,12 +361,13 @@ class WhisperManager {}const result = JSON.parse(jsonLine);+if (!result.text || result.text.trim().length === 0) {return { success: false, message: "No audio detected" };}return { success: true, text: result.text.trim() };} catch (parseError) {- console.error("Raw stdout:", stdout);+ debugLogger.error('Failed to parse Whisper output');throw new Error(`Failed to parse Whisper output: ${parseError.message}`);}}@@ -271,7 +376,7 @@ class WhisperManager {try {await fsPromises.unlink(tempAudioPath);} catch (cleanupError) {- console.warn("Could not clean up temp file:", cleanupError.message);+ // Temp file cleanup error is not critical}}@@ -410,16 +515,85 @@ class WhisperManager {}async checkFFmpegAvailability() {+ debugLogger.logWhisperPipeline('checkFFmpegAvailability - start', {});+try {const pythonCmd = await this.findPythonExecutable();const whisperScriptPath = this.getWhisperScriptPath();+ // Get FFmpeg path to pass to Python script+ let ffmpegPath;+ try {+ ffmpegPath = require("ffmpeg-static");+ console.log("π¬ [WhisperManager] Initial FFmpeg path for check:", ffmpegPath);+ const envInfo = {+ NODE_ENV: process.env.NODE_ENV,+ resourcesPath: process.resourcesPath,+ __dirname: __dirname+ };+ console.log("π¬ [WhisperManager] Environment:", envInfo);+ debugLogger.logFFmpegDebug('checkFFmpegAvailability', ffmpegPath, envInfo);++ // Always check if the path exists and handle ASAR unpacking+ if (!fs.existsSync(ffmpegPath)) {+ console.log("π¬ [WhisperManager] FFmpeg not found at initial path, checking alternatives...");++ const possiblePaths = [+ // Direct ASAR replacement+ ffmpegPath.replace("app.asar", "app.asar.unpacked"),+ // Alternative ASAR replacement patterns+ ffmpegPath.replace(/app\.asar[\/\\]/, "app.asar.unpacked/"),+ // Resources folder fallback+ process.resourcesPath ? path.join(process.resourcesPath, "app.asar.unpacked", "node_modules", "ffmpeg-static", process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg") : null,+ // Development fallback+ path.join(__dirname, "..", "..", "node_modules", "ffmpeg-static", process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg")+ ].filter(Boolean);++ console.log("π¬ [WhisperManager] Checking alternative paths:");+ debugLogger.log('Checking alternative FFmpeg paths for availability check');++ for (const possiblePath of possiblePaths) {+ const exists = fs.existsSync(possiblePath);+ console.log("π¬ [WhisperManager] Checking:", possiblePath, "exists:", exists);+ debugLogger.logFFmpegDebug('Checking availability path', possiblePath);++ if (exists) {+ ffmpegPath = possiblePath;+ console.log("β [WhisperManager] Found FFmpeg at:", ffmpegPath);+ debugLogger.log('FFmpeg found for availability check at:', ffmpegPath);+ break;+ }+ }+ }++ // Final validation+ if (!ffmpegPath || !fs.existsSync(ffmpegPath)) {+ console.warn("β οΈ [WhisperManager] FFmpeg not found at any location");+ ffmpegPath = null;+ } else {+ console.log("β [WhisperManager] Using FFmpeg at:", ffmpegPath);+ }+ } catch (e) {+ console.warn("β οΈ [WhisperManager] ffmpeg-static error:", e.message);+ ffmpegPath = null;+ }+const result = await new Promise((resolve) => {+ // Set up environment with FFmpeg path+ const env = {+ ...process.env,+ FFMPEG_PATH: ffmpegPath || "",+ FFMPEG_EXECUTABLE: ffmpegPath || "",+ FFMPEG_BINARY: ffmpegPath || ""+ };+const checkProcess = spawn(pythonCmd, [whisperScriptPath,"--mode","check-ffmpeg",- ]);+ ], {+ env: env+ });let output = "";let stderr = "";@@ -433,17 +607,26 @@ class WhisperManager {});checkProcess.on("close", (code) => {+ debugLogger.logWhisperPipeline('FFmpeg check process closed', {+ code,+ outputLength: output.length,+ stderrLength: stderr.length+ });+if (code === 0) {try {const result = JSON.parse(output);+ debugLogger.log('FFmpeg check result:', result);resolve(result);} catch (parseError) {+ debugLogger.error('Failed to parse FFmpeg check result:', parseError);resolve({available: false,error: "Failed to parse FFmpeg check result",});}} else {+ debugLogger.error('FFmpeg check failed with code:', code, 'stderr:', stderr);resolve({available: false,error: stderr || "FFmpeg check failed",@@ -698,12 +881,10 @@ class WhisperManager {});checkProcess.on("error", (error) => {- console.error("Model status check error:", error);- reject(new Error(`Model status check error: ${error.message}`));+ reject(new Error(`Model status check error: ${error.message}`));});});} catch (error) {- console.error("Model status check error:", error);throw error;}}@@ -747,12 +928,10 @@ class WhisperManager {});listProcess.on("error", (error) => {- console.error("Model list error:", error);- reject(new Error(`Model list error: ${error.message}`));+ reject(new Error(`Model list error: ${error.message}`));});});} catch (error) {- console.error("Model list error:", error);throw error;}}@@ -804,12 +983,10 @@ class WhisperManager {});deleteProcess.on("error", (error) => {- console.error("Model delete error:", error);- reject(new Error(`Model delete error: ${error.message}`));+ reject(new Error(`Model delete error: ${error.message}`));});});} catch (error) {- console.error("Model delete error:", error);throw error;}}diff --git a/whisper_bridge.py b/whisper_bridge.pyindex 16747b8cb..5cfbdb1ed 100755--- a/whisper_bridge.py+++ b/whisper_bridge.py@@ -18,16 +18,15 @@ import gcdef get_ffmpeg_path():"""Get path to bundled FFmpeg executable with proper production support"""-- # Check environment variables first (set by Node.js)+ # Check environment variables firstenv_paths = [- os.environ.get("FFMPEG_PATH"),- os.environ.get("FFMPEG_EXECUTABLE"),- os.environ.get("FFMPEG_BINARY")+ ("FFMPEG_PATH", os.environ.get("FFMPEG_PATH")),+ ("FFMPEG_EXECUTABLE", os.environ.get("FFMPEG_EXECUTABLE")),+ ("FFMPEG_BINARY", os.environ.get("FFMPEG_BINARY"))]- for env_path in env_paths:- if env_path and os.path.exists(env_path):+ for env_name, env_path in env_paths:+ if env_path and os.path.exists(env_path) and os.access(env_path, os.X_OK):return env_path# Determine base path@@ -45,18 +44,22 @@ def get_ffmpeg_path():os.path.join(base_path, "..", "..", "..", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg"),os.path.join(base_path, "..", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg"),# Development path+ os.path.join(base_path, "node_modules", "ffmpeg-static", "ffmpeg"),+ # Alternative development pathos.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg"),]elif sys.platform == "win32": # Windowspossible_paths = [os.path.join(base_path, "..", "..", "..", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg.exe"),os.path.join(base_path, "..", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg.exe"),+ os.path.join(base_path, "node_modules", "ffmpeg-static", "ffmpeg.exe"),os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg.exe"),]else: # Linuxpossible_paths = [os.path.join(base_path, "..", "..", "..", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg"),os.path.join(base_path, "..", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg"),+ os.path.join(base_path, "node_modules", "ffmpeg-static", "ffmpeg"),os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg"),]@@ -66,12 +69,48 @@ def get_ffmpeg_path():if os.path.exists(abs_path) and os.access(abs_path, os.X_OK):return abs_path+ # Try system FFmpeg as last resort+ if sys.platform == "darwin":+ common_ffmpeg_paths = [+ "/opt/homebrew/bin/ffmpeg", # Homebrew on Apple Silicon+ "/usr/local/bin/ffmpeg", # Homebrew on Intel or manual installs+ "/usr/bin/ffmpeg", # System location+ "ffmpeg" # In PATH+ ]+ else:+ common_ffmpeg_paths = ["ffmpeg"]++ for ffmpeg_cmd in common_ffmpeg_paths:+ try:+ import subprocess+ result = subprocess.run([ffmpeg_cmd, "-version"], capture_output=True, text=True, timeout=5)+ if result.returncode == 0:+ return ffmpeg_cmd+ except Exception:+ continue+return None# Set FFmpeg path for Whisperffmpeg_path = get_ffmpeg_path()if ffmpeg_path:os.environ["FFMPEG_BINARY"] = ffmpeg_path++ # CRITICAL: Add ffmpeg directory to PATH so Whisper can find it+ ffmpeg_dir = os.path.dirname(os.path.abspath(ffmpeg_path))+ current_path = os.environ.get("PATH", "")+ if ffmpeg_dir not in current_path:+ os.environ["PATH"] = f"{ffmpeg_dir}:{current_path}"++ # For Whisper library, we need to ensure 'ffmpeg' command works+ # Create a symlink if needed (for macOS/Linux)+ if sys.platform != "win32" and os.path.isfile(ffmpeg_path) and os.path.basename(ffmpeg_path) != "ffmpeg":+ symlink_path = os.path.join(ffmpeg_dir, "ffmpeg")+ if not os.path.exists(symlink_path):+ try:+ os.symlink(ffmpeg_path, symlink_path)+ except Exception:+ pass# Global model cache to avoid reloading_model_cache = {}@@ -87,12 +126,10 @@ def load_model(model_name="base"):try:model = whisper.load_model(model_name)- # Cache the model but limit cache size- if len(_model_cache) >= 2: # Keep max 2 models in memory- # Remove oldest model+ if len(_model_cache) >= 2:oldest_key = next(iter(_model_cache))del _model_cache[oldest_key]- gc.collect() # Force garbage collection+ gc.collect()_model_cache[model_name] = modelreturn model@@ -111,16 +148,15 @@ def get_expected_model_size(model_name):except Exception:pass- # Fallback to approximate sizes (in bytes)approximate_sizes = {- "tiny": 39 * 1024 * 1024, # ~39MB- "base": 74 * 1024 * 1024, # ~74MB- "small": 244 * 1024 * 1024, # ~244MB- "medium": 769 * 1024 * 1024, # ~769MB- "large": 1550 * 1024 * 1024, # ~1550MB- "turbo": 809 * 1024 * 1024 # ~809MB+ "tiny": 39 * 1024 * 1024,+ "base": 74 * 1024 * 1024,+ "small": 244 * 1024 * 1024,+ "medium": 769 * 1024 * 1024,+ "large": 1550 * 1024 * 1024,+ "turbo": 809 * 1024 * 1024}- return approximate_sizes.get(model_name, 100 * 1024 * 1024) # Default 100MB+ return approximate_sizes.get(model_name, 100 * 1024 * 1024)def monitor_download_progress(model_name, expected_size, stop_event):"""Monitor download progress by watching file size growth"""@@ -144,22 +180,18 @@ def monitor_download_progress(model_name, expected_size, stop_event):current_time = time.time()time_diff = current_time - last_update_time- # Calculate speed if we have a previous measurementspeed_mbps = 0if last_size > 0 and time_diff > 0 and current_size > last_size:bytes_per_second = (current_size - last_size) / time_diff- speed_mbps = (bytes_per_second * 8) / (1024 * 1024) # Convert to Mbps+ speed_mbps = (bytes_per_second * 8) / (1024 * 1024)- # Keep rolling average of speed samplesspeed_samples.append(speed_mbps)- if len(speed_samples) > 10: # Keep last 10 samples+ if len(speed_samples) > 10:speed_samples.pop(0)speed_mbps = sum(speed_samples) / len(speed_samples)- # Send progress update (throttled to avoid spam)percentage = min((current_size / expected_size * 100) if expected_size > 0 else 0, 100)- # Only send progress updates every 0.5 seconds or when percentage changes significantlyif (current_time - last_progress_update > 0.5 orabs(percentage - last_progress_update) > 1.0):@@ -188,7 +220,7 @@ def monitor_download_progress(model_name, expected_size, stop_event):except Exception:pass- time.sleep(0.5) # Check every 500ms+ time.sleep(0.5)def download_model(model_name="base"):"""Download Whisper model with real-time progress monitoring"""@@ -353,26 +385,31 @@ def delete_model(model_name="base"):def transcribe_audio(audio_path, model_name="base", language=None):"""Transcribe audio file using Whisper with optimizations"""++ if not os.path.exists(audio_path):+ return {"error": f"Audio file not found: {audio_path}", "success": False}+try:# Load model (uses cache for performance)model = load_model(model_name)if model is None:return {"error": "Failed to load Whisper model", "success": False}- # Set transcription options - keep it simple for reliabilityoptions = {- "fp16": False, # Use FP32 for better compatibility- "verbose": False, # Reduce logging overhead+ "fp16": False,+ "verbose": False,}if language:options["language"] = languageresult = model.transcribe(audio_path, **options)- # Return results - only JSON to stdout+ text = result.get("text", "").strip()+ language = result.get("language", "unknown")+return {- "text": result.get("text", "").strip(),- "language": result.get("language", "unknown"),+ "text": text,+ "language": language,"success": True}@@ -385,22 +422,24 @@ def transcribe_audio(audio_path, model_name="base", language=None):def check_ffmpeg():"""Check if FFmpeg is available and working"""try:- # Test FFmpeg by trying to get its versionimport subprocess- result = subprocess.run([ffmpeg_path or "ffmpeg", "-version"],+ test_path = ffmpeg_path or "ffmpeg"++ result = subprocess.run([test_path, "-version"],capture_output=True, text=True, timeout=10)if result.returncode == 0:+ version_line = result.stdout.split('\n')[0] if result.stdout else "Unknown"return {"available": True,- "path": ffmpeg_path or "ffmpeg",- "version": result.stdout.split('\n')[0] if result.stdout else "Unknown",+ "path": test_path,+ "version": version_line,"success": True}else:return {"available": False,- "error": f"FFmpeg returned code {result.returncode}",+ "error": f"FFmpeg returned code {result.returncode}: {result.stderr}","success": False}except subprocess.TimeoutExpired: