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
refactor: cleanup of files and bundling fixes
Gabriel Steina4f9470f24ba
diff --git a/electron-builder.json b/electron-builder.jsonindex 0dce09158..c86072d49 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -21,13 +21,11 @@"!src/node_modules/**/*"],"asarUnpack": [- "assets/**/*","whisper_bridge.py",- "node_modules/ffmpeg-static/**/*"+ "**/node_modules/ffmpeg-static/**/*"],"extraResources": [- "assets/**/*",- "node_modules/ffmpeg-static/**/*"+ "assets/**/*"],"mac": {"category": "public.app-category.productivity",@@ -40,6 +38,7 @@"gatekeeperAssess": false,"entitlements": "build/entitlements.mac.plist","entitlementsInherit": "build/entitlements.mac.plist",+ "identity": null,"extendInfo": {"LSUIElement": false,"NSMicrophoneUsageDescription": "OpenWispr needs microphone access for speech-to-text transcription.",@@ -75,5 +74,12 @@"width": 540,"height": 380}+ },+ "publish": {+ "provider": "github",+ "owner": "HeroTools",+ "repo": "open-wispr",+ "private": false,+ "releaseType": "release"}-}\ No newline at end of file+}diff --git a/package.json b/package.jsonindex fc1532836..fda2a4964 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-wispr",- "version": "0.1.0",+ "version": "0.0.3-alpha","description": "A desktop dictation application using OpenAI Whisper for speech-to-text transcription","main": "main.js","private": true,@@ -46,7 +46,6 @@"eslint": "^9.25.0","eslint-plugin-react-hooks": "^5.2.0","eslint-plugin-react-refresh": "^0.4.19",- "ffmpeg-static": "^5.2.0","globals": "^16.0.0","postcss": "^8.5.6","tailwindcss": "^4.1.10",@@ -59,6 +58,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","dotenv": "^16.3.1",+ "ffmpeg-static": "^5.2.0","electron-updater": "^6.6.2","lucide-react": "^0.518.0","react": "^19.1.0",diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex baa29743e..e9d2efe81 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -28,14 +28,12 @@ class WhisperManager {async initializeAtStartup() {try {- // Initialize Python path and Whisper installation statusawait this.findPythonExecutable();await this.checkWhisperInstallation();this.isInitialized = true;- console.log("✅ Whisper manager initialized at startup");} catch (error) {- console.log("⚠️ Whisper not available at startup:", error.message);- this.isInitialized = true; // Mark as initialized even if Whisper isn't available+ console.error("Whisper not available at startup:", error.message);+ this.isInitialized = true;}}@@ -45,18 +43,14 @@ class WhisperManager {const language = options.language || null;try {- console.log(tempAudioPath,- model,- language)const result = await this.runWhisperProcess(tempAudioPath,model,language);- console.log(result)return this.parseWhisperResult(result);} catch (error) {- console.error("❌ Local Whisper transcription error:", error);+ console.error("Local Whisper transcription error:", error);throw error;} finally {this.cleanupTempFile(tempAudioPath);@@ -86,104 +80,123 @@ class WhisperManager {}async runWhisperProcess(tempAudioPath, model, language) {- const pythonCmd = await this.findPythonExecutable();- const whisperScriptPath = this.getWhisperScriptPath();- const args = [whisperScriptPath, tempAudioPath, '--model', model];- if (language) {- args.push('--language', language);- }- args.push('--output-format', 'json');+ const pythonCmd = await this.findPythonExecutable();+ const whisperScriptPath = this.getWhisperScriptPath();+ const args = [whisperScriptPath, tempAudioPath, "--model", model];+ if (language) {+ args.push("--language", language);+ }+ args.push("--output-format", "json");return new Promise((resolve, reject) => {+ // Get FFmpeg path with proper production/development handling+ let ffmpegPath;- const ffmpegPath = require('ffmpeg-static').replace('app.asar', 'app.asar.unpacked');- // Enhanced environment setup with multiple FFmpeg paths- const enhancedEnv = {- ...process.env,- FFMPEG_PATH: ffmpegPath,- FFMPEG_EXECUTABLE: ffmpegPath,- FFMPEG_BINARY: ffmpegPath,- };-- // Add ffmpeg directory to PATH- const ffmpegDir = path.dirname(ffmpegPath);- const currentPath = enhancedEnv.PATH || '';- const pathSeparator = process.platform === 'win32' ? ';' : ':';-- if (!currentPath.includes(ffmpegDir)) {- enhancedEnv.PATH = `${ffmpegDir}${pathSeparator}${currentPath}`;- }+ if (process.env.NODE_ENV === "development") {+ ffmpegPath = require("ffmpeg-static");+ } else {+ // Production: try unpacked location first, then fallback+ try {+ const originalPath = require("ffmpeg-static");+ ffmpegPath = originalPath.replace("app.asar", "app.asar.unpacked");- console.log('🎬 FFmpeg setup:', {- ffmpegPath,- ffmpegDir,- pathUpdated: enhancedEnv.PATH.includes(ffmpegDir)- });+ if (!fs.existsSync(ffmpegPath)) {+ ffmpegPath = originalPath;+ }+ } catch (e) {+ console.error("Could not resolve FFmpeg path:", e.message);+ ffmpegPath = null;+ }+ }- const whisperProcess = spawn(pythonCmd, args, {- stdio: ['ignore', 'pipe', 'pipe'],- windowsHide: true,- env: enhancedEnv, // Use enhanced environment- });+ // Enhanced environment setup+ const enhancedEnv = {+ ...process.env,+ FFMPEG_PATH: ffmpegPath,+ FFMPEG_EXECUTABLE: ffmpegPath,+ FFMPEG_BINARY: ffmpegPath,+ };++ // Add ffmpeg directory to PATH if we have a valid path+ if (ffmpegPath) {+ const ffmpegDir = path.dirname(ffmpegPath);+ const currentPath = enhancedEnv.PATH || "";+ const pathSeparator = process.platform === "win32" ? ";" : ":";- let stdout = '';- let stderr = '';- let isResolved = false;+ if (!currentPath.includes(ffmpegDir)) {+ enhancedEnv.PATH = `${ffmpegDir}${pathSeparator}${currentPath}`;+ }- // Set timeout for longer recordings- const timeout = setTimeout(() => {- if (!isResolved) {- whisperProcess.kill('SIGTERM');- reject(new Error('Whisper transcription timed out (60 seconds)'));+ } else {+ console.warn("No valid FFmpeg path found, transcription may fail");}- }, 60000);- whisperProcess.stdout.on('data', (data) => {- stdout += data.toString();- });+ const whisperProcess = spawn(pythonCmd, args, {+ stdio: ["ignore", "pipe", "pipe"],+ windowsHide: true,+ env: enhancedEnv,+ });- whisperProcess.stderr.on('data', (data) => {- const stderrText = data.toString();- stderr += stderrText;+ let stdout = "";+ let stderr = "";+ let isResolved = false;- // Log FFmpeg-related messages- if (stderrText.includes('ffmpeg') ||- stderrText.includes('Error') ||- stderrText.includes('failed')) {- console.log('Whisper log:', stderrText.trim());- }- });+ // Set timeout for longer recordings+ const timeout = setTimeout(() => {+ if (!isResolved) {+ whisperProcess.kill("SIGTERM");+ reject(new Error("Whisper transcription timed out (60 seconds)"));+ }+ }, 60000);++ whisperProcess.stdout.on("data", (data) => {+ stdout += data.toString();+ });- whisperProcess.on('close', (code) => {- if (isResolved) return;- isResolved = true;- clearTimeout(timeout);+ whisperProcess.stderr.on("data", (data) => {+ const stderrText = data.toString();+ stderr += stderrText;- if (code === 0) {- resolve(stdout);- } else {- // Better error message for FFmpeg issues- let errorMessage = `Whisper transcription failed (code ${code}): ${stderr}`;-- if (stderr.includes('ffmpeg') || stderr.includes('No such file or directory')) {- errorMessage += '\n\n💡 This appears to be an FFmpeg issue. Try:\n';- errorMessage += '1. Restart the app completely\n';- errorMessage += '2. Check if FFmpeg is bundled correctly\n';- errorMessage += '3. Install FFmpeg system-wide as fallback';+ if (+ stderrText.includes("ffmpeg") ||+ stderrText.includes("Error") ||+ stderrText.includes("failed")+ ) {+ console.error("Whisper error:", stderrText.trim());}+ });- reject(new Error(errorMessage));- }- });+ whisperProcess.on("close", (code) => {+ if (isResolved) return;+ isResolved = true;+ clearTimeout(timeout);++ if (code === 0) {+ resolve(stdout);+ } else {+ // Better error message for FFmpeg issues+ let errorMessage = `Whisper transcription failed (code ${code}): ${stderr}`;++ if (+ stderr.includes("ffmpeg") ||+ stderr.includes("No such file or directory") ||+ stderr.includes("FFmpeg not found")+ ) {+ errorMessage += "\n\nFFmpeg issue detected. Try restarting the app or reinstalling.";+ }- whisperProcess.on('error', (error) => {- if (isResolved) return;- isResolved = true;- clearTimeout(timeout);- reject(new Error(`Whisper process error: ${error.message}`));+ reject(new Error(errorMessage));+ }+ });++ whisperProcess.on("error", (error) => {+ if (isResolved) return;+ isResolved = true;+ clearTimeout(timeout);+ reject(new Error(`Whisper process error: ${error.message}`));+ });});- });-}+ }parseWhisperResult(stdout) {try {@@ -219,7 +232,7 @@ class WhisperManager {try {fs.unlinkSync(tempAudioPath);} catch (cleanupError) {- console.warn("⚠️ Could not clean up temp file:", cleanupError.message);+ console.warn("Could not clean up temp file:", cleanupError.message);}}@@ -366,19 +379,9 @@ class WhisperManager {async installWhisper() {try {- console.log("🔧 Starting automatic Whisper installation...");-const pythonCmd = await this.findPythonExecutable();- console.log("🐍 Using Python:", pythonCmd);-const args = ["-m", "pip", "install", "-U", "openai-whisper"];- console.log(- "📦 Running installation command:",- pythonCmd,- args.join(" ")- );-return new Promise((resolve, reject) => {const installProcess = spawn(pythonCmd, args);@@ -386,27 +389,22 @@ class WhisperManager {let stderr = "";installProcess.stdout.on("data", (data) => {- const output = data.toString();- stdout += output;- console.log("Install output:", output);+ stdout += data.toString();});installProcess.stderr.on("data", (data) => {- const output = data.toString();- stderr += output;- console.log("Install stderr:", output);+ stderr += data.toString();});installProcess.on("close", (code) => {if (code === 0) {- console.log("✅ Whisper installation completed successfully");resolve({success: true,message: "Whisper installed successfully!",output: stdout,});} else {- console.error("❌ Whisper installation failed with code:", code);+ console.error("Whisper installation failed with code:", code);console.error("Installation stderr:", stderr);reject(new Error(`Whisper installation failed (code ${code}): ${stderr}`)@@ -415,7 +413,7 @@ class WhisperManager {});installProcess.on("error", (error) => {- console.error("❌ Whisper installation process error:", error);+ console.error("Whisper installation process error:", error);reject(new Error(`Whisper installation process error: ${error.message}`));@@ -427,15 +425,13 @@ class WhisperManager {}, 600000);});} catch (error) {- console.error("❌ Whisper installation error:", error);+ console.error("Whisper installation error:", error);throw error;}}async downloadWhisperModel(modelName, progressCallback = null) {try {- console.log(`📥 Starting download of Whisper model: ${modelName}`);-const pythonCmd = await this.findPythonExecutable();const whisperScriptPath = this.getWhisperScriptPath();@@ -489,10 +485,9 @@ class WhisperManager {if (code === 0) {try {const result = JSON.parse(stdout);- console.log(`✅ Model ${modelName} download completed`);resolve(result);} catch (parseError) {- console.error("❌ Failed to parse download result:", parseError);+ console.error("Failed to parse download result:", parseError);reject(new Error(`Failed to parse download result: ${parseError.message}`@@ -500,12 +495,10 @@ class WhisperManager {);}} else {- // Check if this was a cancellation (SIGTERM = 143, SIGKILL = 137)if (code === 143 || code === 137) {- console.log(`🛑 Model ${modelName} download cancelled`);reject(new Error("Download interrupted by user"));} else {- console.error("❌ Model download failed with code:", code);+ console.error("Model download failed with code:", code);reject(new Error(`Model download failed (code ${code}): ${stderr}`));@@ -514,24 +507,18 @@ class WhisperManager {});downloadProcess.on("error", (error) => {- this.currentDownloadProcess = null; // Clear process reference- console.error("❌ Model download process error:", error);+ this.currentDownloadProcess = null;+ console.error("Model download process error:", error);reject(new Error(`Model download process error: ${error.message}`));});const timeout = setTimeout(() => {- console.warn(- "⚠️ Model download timed out, attempting graceful shutdown..."- );downloadProcess.kill("SIGTERM");-setTimeout(() => {if (!downloadProcess.killed) {- console.warn("⚠️ Force killing download process...");downloadProcess.kill("SIGKILL");}}, 5000);-reject(new Error("Model download timed out (20 minutes)"));}, 1200000);@@ -540,7 +527,7 @@ class WhisperManager {});});} catch (error) {- console.error("❌ Model download error:", error);+ console.error("Model download error:", error);throw error;}}@@ -548,23 +535,18 @@ class WhisperManager {async cancelDownload() {if (this.currentDownloadProcess) {try {- console.log("🛑 Cancelling current download...");this.currentDownloadProcess.kill("SIGTERM");-- // Force kill after 3 seconds if still runningsetTimeout(() => {if (this.currentDownloadProcess &&!this.currentDownloadProcess.killed) {- console.log("🛑 Force killing download process...");this.currentDownloadProcess.kill("SIGKILL");}}, 3000);-return { success: true, message: "Download cancelled" };} catch (error) {- console.error("❌ Error cancelling download:", error);+ console.error("Error cancelling download:", error);return { success: false, error: error.message };}} else {@@ -574,8 +556,6 @@ class WhisperManager {async checkModelStatus(modelName) {try {- console.log(`🔍 Checking status of Whisper model: ${modelName}`);-const pythonCmd = await this.findPythonExecutable();const whisperScriptPath = this.getWhisperScriptPath();@@ -599,16 +579,15 @@ class WhisperManager {if (code === 0) {try {const result = JSON.parse(stdout);- console.log(`📊 Model ${modelName} status:`, result);resolve(result);} catch (parseError) {- console.error("❌ Failed to parse model status:", parseError);+ console.error("Failed to parse model status:", parseError);reject(new Error(`Failed to parse model status: ${parseError.message}`));}} else {- console.error("❌ Model status check failed with code:", code);+ console.error("Model status check failed with code:", code);reject(new Error(`Model status check failed (code ${code}): ${stderr}`));@@ -616,20 +595,18 @@ class WhisperManager {});checkProcess.on("error", (error) => {- console.error("❌ Model status check error:", error);+ console.error("Model status check error:", error);reject(new Error(`Model status check error: ${error.message}`));});});} catch (error) {- console.error("❌ Model status check error:", error);+ console.error("Model status check error:", error);throw error;}}async listWhisperModels() {try {- console.log("📋 Listing all Whisper models...");-const pythonCmd = await this.findPythonExecutable();const whisperScriptPath = this.getWhisperScriptPath();@@ -653,35 +630,32 @@ class WhisperManager {if (code === 0) {try {const result = JSON.parse(stdout);- console.log("📋 Model list retrieved:", result);resolve(result);} catch (parseError) {- console.error("❌ Failed to parse model list:", parseError);+ console.error("Failed to parse model list:", parseError);reject(new Error(`Failed to parse model list: ${parseError.message}`));}} else {- console.error("❌ Model list failed with code:", code);+ console.error("Model list failed with code:", code);reject(new Error(`Model list failed (code ${code}): ${stderr}`));}});listProcess.on("error", (error) => {- console.error("❌ Model list error:", error);+ console.error("Model list error:", error);reject(new Error(`Model list error: ${error.message}`));});});} catch (error) {- console.error("❌ Model list error:", error);+ console.error("Model list error:", error);throw error;}}async deleteWhisperModel(modelName) {try {- console.log(`🗑️ Deleting Whisper model: ${modelName}`);-const pythonCmd = await this.findPythonExecutable();const whisperScriptPath = this.getWhisperScriptPath();@@ -711,10 +685,9 @@ class WhisperManager {if (code === 0) {try {const result = JSON.parse(stdout);- console.log(`🗑️ Model ${modelName} delete result:`, result);resolve(result);} catch (parseError) {- console.error("❌ Failed to parse delete result:", parseError);+ console.error("Failed to parse delete result:", parseError);reject(new Error(`Failed to parse delete result: ${parseError.message}`@@ -722,18 +695,18 @@ class WhisperManager {);}} else {- console.error("❌ Model delete failed with code:", code);+ console.error("Model delete failed with code:", code);reject(new Error(`Model delete failed (code ${code}): ${stderr}`));}});deleteProcess.on("error", (error) => {- console.error("❌ Model delete error:", error);+ console.error("Model delete error:", error);reject(new Error(`Model delete error: ${error.message}`));});});} catch (error) {- console.error("❌ Model delete error:", error);+ console.error("Model delete error:", error);throw error;}}diff --git a/whisper_bridge.py b/whisper_bridge.pyindex 2dfc1b1b2..16747b8cb 100755--- a/whisper_bridge.py+++ b/whisper_bridge.py@@ -17,34 +17,54 @@ import requestsimport gcdef get_ffmpeg_path():- """Get path to bundled FFmpeg executable"""+ """Get path to bundled FFmpeg executable with proper production support"""++ # Check environment variables first (set by Node.js)+ env_paths = [+ os.environ.get("FFMPEG_PATH"),+ os.environ.get("FFMPEG_EXECUTABLE"),+ os.environ.get("FFMPEG_BINARY")+ ]++ for env_path in env_paths:+ if env_path and os.path.exists(env_path):+ return env_path++ # Determine base pathif getattr(sys, 'frozen', False):- # Running in Electron app (packed)base_path = sys._MEIPASSelse:- # Running in developmentbase_path = os.path.dirname(os.path.abspath(__file__))- # Platform-specific FFmpeg paths+ # Try multiple possible paths for production Electron app+ possible_paths = []+if sys.platform == "darwin": # macOS- ffmpeg_path = os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg")+ possible_paths = [+ # Unpacked ASAR locations+ 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"),+ ]elif sys.platform == "win32": # Windows- ffmpeg_path = os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg.exe")+ possible_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"),+ ]else: # Linux- ffmpeg_path = os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg")+ possible_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"),+ ]- # Make sure the path exists- if os.path.exists(ffmpeg_path):- return ffmpeg_path-- # Fallback: try to find system FFmpeg- import subprocess- try:- result = subprocess.run(['which', 'ffmpeg'], capture_output=True, text=True)- if result.returncode == 0:- return result.stdout.strip()- except:- pass+ # Try each possible path+ for ffmpeg_path in possible_paths:+ abs_path = os.path.abspath(ffmpeg_path)+ if os.path.exists(abs_path) and os.access(abs_path, os.X_OK):+ return abs_pathreturn None@@ -52,9 +72,6 @@ def get_ffmpeg_path():ffmpeg_path = get_ffmpeg_path()if ffmpeg_path:os.environ["FFMPEG_BINARY"] = ffmpeg_path- print(f"Using FFmpeg at: {ffmpeg_path}", file=sys.stderr)-else:- print("Warning: FFmpeg not found, Whisper may not work properly", file=sys.stderr)# Global model cache to avoid reloading_model_cache = {}@@ -111,7 +128,6 @@ def monitor_download_progress(model_name, expected_size, stop_event):model_url = whisper._MODELS[model_name]model_file = os.path.join(cache_dir, os.path.basename(model_url))- # Create cache directory if it doesn't existos.makedirs(cache_dir, exist_ok=True)last_size = 0@@ -159,13 +175,11 @@ def monitor_download_progress(model_name, expected_size, stop_event):print(f"PROGRESS:{json.dumps(progress_data)}", file=sys.stderr)last_progress_update = percentage- # Check if download is complete- if current_size >= expected_size * 0.95: # 95% threshold+ if current_size >= expected_size * 0.95:break- # Check if no progress for too long (stagnation detection)- if current_size == last_size and time_diff > 5: # 5 seconds no progress- if current_size > expected_size * 0.9: # If we're close to done, assume complete+ if current_size == last_size and current_time - last_update_time > 10:+ if current_size > expected_size * 0.9:breaklast_size = current_size