Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(windows): resolve issue #16 - add WAV validation, registry Python detection, and normalized FFmpeg paths

Gabriel Steina18167d8fa83
diff --git a/WINDOWS_TROUBLESHOOTING.md b/WINDOWS_TROUBLESHOOTING.md
new file mode 100644
index 000000000..96d2d45b4
--- /dev/null
+++ b/WINDOWS_TROUBLESHOOTING.md
@@ -0,0 +1,272 @@
+# Windows Troubleshooting Guide
+
+This guide addresses common Windows-specific issues in OpenWhispr.
+
+## Quick Fixes
+
+### Issue: "No transcriptions" or "Audio file is empty"
+
+**Symptoms:**
+- Recording indicator shows, but no text appears
+- Error: "Audio file is empty"
+- Error: "Audio data too small"
+
+**Solutions:**
+
+1. **Check Microphone Permissions**
+ - Open Windows Settings → Privacy & Security → Microphone
+ - Ensure "Microphone access" is ON
+ - Ensure "Let apps access your microphone" is ON
+ - Restart OpenWhispr
+
+2. **Verify Microphone Selection**
+ - Right-click speaker icon in system tray
+ - Select "Sound settings"
+ - Under "Input", select your microphone
+ - Test by speaking - the volume bar should move
+ - Set volume to 70-100%
+
+3. **Test Recording**
+ - Open Windows Voice Recorder
+ - Record a short clip
+ - If Voice Recorder works but OpenWhispr doesn't, enable debug mode (see below)
+
+### Issue: "Python not found" or ENOENT error
+
+**Symptoms:**
+- Error: "spawn python ENOENT"
+- Error: "Python 3.x not found"
+- Transcription fails immediately
+
+**Solutions:**
+
+1. **Install Python via OpenWhispr**
+ - Open Control Panel (click OpenWhispr icon → Control Panel)
+ - Go to Settings tab
+ - Click "Install Python" button
+ - Wait for installation to complete
+ - Restart OpenWhispr
+
+2. **Manual Python Installation**
+ - Download Python 3.11+ from [python.org](https://www.python.org/downloads/)
+ - **IMPORTANT**: Check "Add Python to PATH" during installation
+ - Choose "Install for all users" if you have admin rights
+ - After installation, restart your computer
+ - Restart OpenWhispr
+
+3. **Verify Python Installation**
+ - Open Command Prompt (Win + R, type `cmd`)
+ - Type: `python --version`
+ - Should show: `Python 3.x.x`
+ - Type: `where python`
+ - Should show path to python.exe
+
+4. **Set Python Path Manually**
+ - Find your Python installation (usually `C:\Users\YourName\AppData\Local\Programs\Python\Python311\python.exe`)
+ - Create/edit `.env` file in OpenWhispr directory
+ - Add: `OPENWHISPR_PYTHON=C:\Path\To\Your\python.exe`
+ - Restart OpenWhispr
+
+### Issue: "FFmpeg not found" or transcription fails silently
+
+**Symptoms:**
+- Recording completes but never transcribes
+- Error mentions FFmpeg
+- Local Whisper mode doesn't work
+
+**Solutions:**
+
+1. **Reinstall OpenWhispr**
+ - Uninstall OpenWhispr completely
+ - Download latest version
+ - Install to default location
+ - FFmpeg is bundled and should work automatically
+
+2. **Install System FFmpeg** (if bundled version fails)
+ - Download FFmpeg from [ffmpeg.org](https://ffmpeg.org/download.html#build-windows)
+ - Extract to `C:\ffmpeg`
+ - Add to PATH:
+ - Open System Properties → Environment Variables
+ - Edit "Path" variable
+ - Add: `C:\ffmpeg\bin`
+ - Restart OpenWhispr
+
+3. **Verify FFmpeg**
+ - Open Command Prompt
+ - Type: `ffmpeg -version`
+ - Should show FFmpeg version info
+
+## Enable Debug Mode
+
+Debug mode creates detailed logs for troubleshooting:
+
+### Method 1: Command Line
+```batch
+cd "C:\Users\YourName\AppData\Local\Programs\OpenWispr"
+OpenWhispr.exe --debug
+```
+
+### Method 2: Environment Variable
+```batch
+set OPENWISPR_DEBUG=true
+"C:\Users\YourName\AppData\Local\Programs\OpenWispr\OpenWhispr.exe"
+```
+
+### Method 3: Debug File
+```batch
+echo. > "%APPDATA%\OpenWispr\ENABLE_DEBUG"
+```
+Then restart OpenWhispr normally.
+
+### Find Debug Logs
+Logs are saved to: `%APPDATA%\OpenWispr\logs\`
+
+To open:
+1. Press Win + R
+2. Type: `%APPDATA%\OpenWispr\logs`
+3. Press Enter
+4. Open the most recent `debug-*.log` file
+
+## Common Error Messages Explained
+
+### "Audio buffer is empty - no audio data received"
+**Meaning:** The microphone didn't capture any audio data.
+
+**Fix:**
+- Check microphone is not muted
+- Check microphone permissions
+- Try a different microphone
+- Ensure no other app is blocking microphone access
+
+### "Python version check failed"
+**Meaning:** Python is installed but not responding correctly.
+
+**Fix:**
+- Reinstall Python
+- Ensure Python is in PATH
+- Check Windows Defender isn't blocking Python
+- Run OpenWhispr as Administrator (temporarily)
+
+### "FFmpeg not found at any location"
+**Meaning:** Cannot find FFmpeg executable.
+
+**Fix:**
+- Reinstall OpenWhispr to get bundled FFmpeg
+- Install FFmpeg separately (see above)
+- Check antivirus isn't quarantining FFmpeg
+
+### "Whisper installation failed"
+**Meaning:** Cannot install the Whisper AI package.
+
+**Fix:**
+- Ensure Python is installed correctly
+- Check internet connection
+- Install Microsoft Visual C++ Redistributable
+- Try Cloud mode instead (requires OpenAI API key)
+
+## Performance Tips
+
+### Slow Transcription
+- Use smaller Whisper model (tiny or base)
+- Enable GPU acceleration if you have NVIDIA GPU
+- Use Cloud mode for faster results
+- Close other apps while transcribing
+
+### High CPU Usage
+- Use "tiny" or "base" model instead of "large"
+- Enable Cloud mode
+- Reduce recording length
+
+## Windows-Specific Issues
+
+### Windows Defender Blocks
+If Windows Defender blocks OpenWhispr:
+1. Open Windows Security
+2. Go to Virus & threat protection
+3. Click "Manage settings"
+4. Add OpenWhispr to exclusions
+
+### Firewall Issues (Cloud Mode)
+If Cloud transcription fails:
+1. Open Windows Firewall settings
+2. Allow OpenWhispr through firewall
+3. Check your antivirus isn't blocking internet access
+
+### Permission Errors
+If you see "Access denied" errors:
+1. Right-click OpenWhispr shortcut
+2. Choose "Run as administrator"
+3. If it works, add permanent admin rights:
+ - Right-click → Properties → Compatibility
+ - Check "Run this program as administrator"
+
+## Getting Help
+
+If none of these solutions work:
+
+1. **Collect Debug Logs**
+ - Enable debug mode (see above)
+ - Reproduce the issue
+ - Locate log file in `%APPDATA%\OpenWispr\logs`
+
+2. **Report Issue**
+ - Go to: https://github.com/HeroTools/open-whispr/issues
+ - Create new issue
+ - Include:
+ - Windows version (Win + R → `winver`)
+ - OpenWhispr version (Help → About)
+ - Debug log contents
+ - Steps to reproduce
+
+3. **System Information**
+ Helpful to include:
+ - Python version: `python --version`
+ - FFmpeg installed: `ffmpeg -version`
+ - Microphone working: Test in Voice Recorder
+ - Other dictation apps working: Try Windows built-in dictation
+
+## Registry Cleanup (Advanced)
+
+If you want to completely uninstall and start fresh:
+
+```batch
+# Uninstall OpenWhispr first, then:
+rd /s /q "%APPDATA%\OpenWispr"
+rd /s /q "%LOCALAPPDATA%\OpenWispr"
+```
+
+Then reinstall.
+
+## Success Indicators
+
+OpenWhispr is working correctly when:
+- ✓ Microphone indicator shows activity when speaking
+- ✓ Recording stops cleanly when hotkey pressed
+- ✓ Transcribed text appears within 5-10 seconds
+- ✓ Text is pasted into active application
+- ✓ No error messages appear
+
+## Notes for IT Administrators
+
+If deploying OpenWhispr in enterprise environment:
+
+1. **Python Installation**
+ - Deploy Python 3.11+ system-wide
+ - Add to system PATH
+ - Install for all users
+
+2. **FFmpeg**
+ - Include in application deployment
+ - Whitelist in antivirus
+ - Ensure ASAR unpacking works
+
+3. **Permissions**
+ - Microphone access required
+ - Internet access for Cloud mode
+ - File write access to %APPDATA%
+ - Registry read access for Python detection
+
+4. **Group Policy**
+ - Allow microphone access
+ - Don't block Python/FFmpeg executables
+ - Allow network access if using Cloud mode
diff --git a/src/helpers/debugLogger.js b/src/helpers/debugLogger.js
index bcbfe7de0..71dbe6083 100644
--- a/src/helpers/debugLogger.js
+++ b/src/helpers/debugLogger.js
@@ -103,6 +103,7 @@ class DebugLogger {
context,
ffmpegPath,
exists: ffmpegPath ? fs.existsSync(ffmpegPath) : false,
+ platform: process.platform,
...additionalInfo,
};
@@ -112,7 +113,8 @@ class DebugLogger {
debugInfo.fileInfo = {
size: stats.size,
isFile: stats.isFile(),
- isExecutable: !!(stats.mode & fs.constants.X_OK),
+ // Skip X_OK check on Windows (not reliable)
+ isExecutable: process.platform !== "win32" ? !!(stats.mode & fs.constants.X_OK) : "N/A (Windows)",
permissions: stats.mode.toString(8),
modified: stats.mtime,
};
@@ -133,30 +135,48 @@ class DebugLogger {
}
}
- // 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);
+ // Platform-specific path checks
+ let possiblePaths = [];
+ if (process.platform === "win32") {
+ possiblePaths = [
+ ffmpegPath,
+ ffmpegPath?.replace(/app\.asar([/\\])/, 'app.asar.unpacked$1'),
+ path.join(process.resourcesPath || "", "app.asar.unpacked", "node_modules", "ffmpeg-static", "ffmpeg.exe"),
+ path.join(process.env.ProgramFiles || "C:\\Program Files", "ffmpeg", "bin", "ffmpeg.exe"),
+ "C:\\ffmpeg\\bin\\ffmpeg.exe",
+ ].filter(Boolean);
+ } else {
+ possiblePaths = [
+ ffmpegPath,
+ ffmpegPath?.replace("app.asar", "app.asar.unpacked"),
+ path.join(process.resourcesPath || "", "app.asar.unpacked", "node_modules", "ffmpeg-static", "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),
+ normalized: path.normalize(p),
}));
this.log(`🎬 FFmpeg Debug - ${context}`, debugInfo);
}
+ logWindowsPythonSearch(context, details) {
+ if (!this.debugMode || process.platform !== "win32") return;
+
+ this.log(`🐍 Windows Python Search - ${context}`, {
+ ...details,
+ platform: process.platform,
+ PATH: process.env.PATH?.substring(0, 300) + "...",
+ LOCALAPPDATA: process.env.LOCALAPPDATA,
+ ProgramFiles: process.env.ProgramFiles,
+ });
+ }
+
logAudioData(context, audioBlob) {
if (!this.debugMode) return;
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index 4a804a606..7e02dc8c4 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -122,7 +122,7 @@ 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);
@@ -139,29 +139,222 @@ class WhisperManager {
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);
+ // Validate buffer before writing
+ if (!buffer || buffer.length === 0) {
+ debugLogger.error('Buffer is empty before writing');
+ throw new Error("Audio buffer is empty - no audio data received");
+ }
+
+ // Minimum viable audio file size (WAV header is 44 bytes minimum)
+ const MIN_AUDIO_SIZE = 44;
+ if (buffer.length < MIN_AUDIO_SIZE) {
+ debugLogger.error('Buffer too small to be valid audio:', buffer.length, 'bytes');
+ throw new Error(`Audio data too small (${buffer.length} bytes) - recording may have failed`);
+ }
+
+ // Validate WAV header if present
+ const hasValidWavHeader = this.validateWavHeader(buffer);
+ if (!hasValidWavHeader) {
+ debugLogger.log('No valid WAV header detected, buffer may need conversion');
+ // Don't throw error - FFmpeg can handle headerless audio data
+ }
+
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)
+ permissions: stats.mode.toString(8),
+ hasWavHeader: hasValidWavHeader
};
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");
+ throw new Error("Audio file is empty - file write failed");
}
-
+
+ if (stats.size < MIN_AUDIO_SIZE) {
+ debugLogger.error('Audio file too small after writing:', stats.size, 'bytes');
+ throw new Error(`Audio file too small (${stats.size} bytes) - recording failed`);
+ }
+
return tempAudioPath;
}
+ validateWavHeader(buffer) {
+ try {
+ if (!buffer || buffer.length < 44) {
+ return false;
+ }
+
+ // Check RIFF header
+ const riff = buffer.toString('ascii', 0, 4);
+ if (riff !== 'RIFF') {
+ return false;
+ }
+
+ // Check WAVE format
+ const wave = buffer.toString('ascii', 8, 12);
+ if (wave !== 'WAVE') {
+ return false;
+ }
+
+ // Check fmt subchunk
+ const fmt = buffer.toString('ascii', 12, 16);
+ if (fmt !== 'fmt ') {
+ return false;
+ }
+
+ debugLogger.log('Valid WAV header detected');
+ return true;
+ } catch (error) {
+ debugLogger.error('WAV header validation error:', error.message);
+ return false;
+ }
+ }
+
+ async resolveFfmpegPath() {
+ try {
+ let ffmpegPath = require("ffmpeg-static");
+ debugLogger.logFFmpegDebug('Initial ffmpeg-static path', ffmpegPath);
+
+ // Normalize path separators for cross-platform compatibility
+ ffmpegPath = path.normalize(ffmpegPath);
+
+ // Add Windows .exe extension if missing
+ if (process.platform === "win32" && !ffmpegPath.endsWith(".exe")) {
+ ffmpegPath += ".exe";
+ }
+
+ // Check if path exists
+ if (fs.existsSync(ffmpegPath)) {
+ // Validate executable permissions (skip on Windows - uses different permission model)
+ if (process.platform !== "win32") {
+ try {
+ fs.accessSync(ffmpegPath, fs.constants.X_OK);
+ } catch (e) {
+ debugLogger.error('FFmpeg exists but is not executable:', e.message);
+ throw new Error('FFmpeg not executable');
+ }
+ }
+ debugLogger.log('Found bundled FFmpeg at:', ffmpegPath);
+ return ffmpegPath;
+ }
+
+ // Production: Handle ASAR unpacking
+ if (process.env.NODE_ENV !== "development") {
+ const possiblePaths = [
+ // Direct replacement
+ ffmpegPath.replace(/app\.asar([/\\])/, 'app.asar.unpacked$1'),
+ ffmpegPath.replace(/app\.asar/g, 'app.asar.unpacked'),
+ // Resources folder
+ process.resourcesPath ? path.join(
+ process.resourcesPath,
+ "app.asar.unpacked",
+ "node_modules",
+ "ffmpeg-static",
+ process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"
+ ) : null,
+ // Alternative resources location
+ process.resourcesPath ? path.join(
+ process.resourcesPath,
+ "app.asar.unpacked",
+ "node_modules",
+ "ffmpeg-static",
+ "bin",
+ process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"
+ ) : null,
+ ].filter(Boolean);
+
+ debugLogger.log('FFmpeg not found at primary path, checking alternatives');
+
+ for (const possiblePath of possiblePaths) {
+ const normalizedPath = path.normalize(possiblePath);
+ if (fs.existsSync(normalizedPath)) {
+ // Validate on non-Windows platforms
+ if (process.platform !== "win32") {
+ try {
+ fs.accessSync(normalizedPath, fs.constants.X_OK);
+ } catch (e) {
+ continue;
+ }
+ }
+ debugLogger.log('FFmpeg found at:', normalizedPath);
+ return normalizedPath;
+ }
+ }
+ }
+
+ debugLogger.log('Bundled FFmpeg not found, trying system FFmpeg');
+ throw new Error('Bundled FFmpeg not found');
+
+ } catch (bundledError) {
+ debugLogger.log('Bundled FFmpeg error:', bundledError.message);
+
+ // Try system FFmpeg with enhanced Windows support
+ const systemCandidates = await this.getSystemFfmpegCandidates();
+
+ for (const candidate of systemCandidates) {
+ try {
+ await runCommand(candidate, ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
+ debugLogger.log('Using system FFmpeg:', candidate);
+ return candidate;
+ } catch (error) {
+ continue;
+ }
+ }
+
+ debugLogger.error('No FFmpeg found (bundled or system)');
+ return null;
+ }
+ }
+
+ async getSystemFfmpegCandidates() {
+ const candidates = [];
+
+ if (process.platform === "win32") {
+ // Windows-specific paths
+ candidates.push("ffmpeg.exe", "ffmpeg");
+
+ // Common Windows installation directories
+ const commonDirs = [
+ path.join(process.env.ProgramFiles || "C:\\Program Files", "ffmpeg", "bin"),
+ path.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "ffmpeg", "bin"),
+ path.join(process.env.LOCALAPPDATA || "", "Programs", "ffmpeg", "bin"),
+ "C:\\ffmpeg\\bin",
+ ];
+
+ for (const dir of commonDirs) {
+ if (dir) {
+ const ffmpegExe = path.join(dir, "ffmpeg.exe");
+ if (fs.existsSync(ffmpegExe)) {
+ candidates.push(ffmpegExe);
+ }
+ }
+ }
+ } else if (process.platform === "darwin") {
+ // macOS-specific paths
+ candidates.push(
+ "ffmpeg",
+ "/opt/homebrew/bin/ffmpeg",
+ "/usr/local/bin/ffmpeg",
+ "/usr/bin/ffmpeg"
+ );
+ } else {
+ // Linux
+ candidates.push("ffmpeg", "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg");
+ }
+
+ return candidates;
+ }
+
async runWhisperProcess(tempAudioPath, model, language) {
const pythonCmd = await this.findPythonExecutable();
const whisperScriptPath = this.getWhisperScriptPath();
@@ -180,66 +373,11 @@ class WhisperManager {
return new Promise(async (resolve, reject) => {
// Get FFmpeg path with robust production/development handling
- let ffmpegPath;
+ let ffmpegPath = await this.resolveFfmpegPath();
- try {
- ffmpegPath = require("ffmpeg-static");
- debugLogger.logFFmpegDebug('Initial ffmpeg-static path', ffmpegPath);
-
- // Add Windows .exe extension if missing
- if (process.platform === "win32" && !ffmpegPath.endsWith(".exe")) {
- ffmpegPath += ".exe";
- }
-
- if (process.env.NODE_ENV !== "development" && !fs.existsSync(ffmpegPath)) {
- const possiblePaths = [
- ffmpegPath.replace("app.asar", "app.asar.unpacked"),
- ffmpegPath.replace(/.*app\.asar/, path.join(__dirname, "..", "..", "app.asar.unpacked")),
- path.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) {
- const exists = fs.existsSync(possiblePath);
-
- if (exists) {
- ffmpegPath = possiblePath;
- debugLogger.log('FFmpeg found at:', ffmpegPath);
- break;
- }
- }
- }
-
- // Final validation of bundled FFmpeg
- if (!fs.existsSync(ffmpegPath)) {
- debugLogger.error('Bundled FFmpeg not found at:', ffmpegPath);
- throw new Error(`Bundled FFmpeg not found at ${ffmpegPath}`);
- }
-
- // Validate it's actually executable
- try {
- 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) {
- debugLogger.log('Bundled FFmpeg not available, trying system FFmpeg');
-
- // Try system FFmpeg with validation
- const systemFFmpeg = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
-
- try {
- const versionResult = await runCommand(systemFFmpeg, ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
- ffmpegPath = systemFFmpeg;
- debugLogger.log('Using system FFmpeg');
- } catch (systemError) {
- debugLogger.error('System FFmpeg also unavailable:', systemError.message);
- ffmpegPath = systemFFmpeg; // Last resort - let Python handle the error
- }
+ if (!ffmpegPath) {
+ reject(new Error('FFmpeg not found. Please ensure FFmpeg is installed or bundled correctly.'));
+ return;
}
// Enhanced environment setup - Python script checks multiple env vars
@@ -251,36 +389,18 @@ class WhisperManager {
FFMPEG_EXECUTABLE: absoluteFFmpegPath,
FFMPEG_BINARY: absoluteFFmpegPath,
};
-
+
debugLogger.logFFmpegDebug('Setting FFmpeg env vars', absoluteFFmpegPath);
// Add ffmpeg directory to PATH if we have a valid path
if (ffmpegPath) {
- const ffmpegDir = path.dirname(ffmpegPath);
+ const ffmpegDir = path.dirname(absoluteFFmpegPath);
const currentPath = enhancedEnv.PATH || "";
const pathSeparator = process.platform === "win32" ? ";" : ":";
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 {
- debugLogger.error('No valid FFmpeg path found, transcription may fail');
}
// Add common system paths for macOS GUI launches
@@ -304,12 +424,6 @@ class WhisperManager {
}
}
- 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, {
@@ -461,6 +575,11 @@ class WhisperManager {
}
if (process.platform === "win32") {
+ // Windows: Get registry-based candidates first (most reliable)
+ const registryCandidates = await this.getWindowsRegistryPython();
+ registryCandidates.forEach(addCandidate);
+
+ // Then add filesystem candidates
this.getWindowsPythonCandidates().forEach(addCandidate);
}
@@ -488,17 +607,31 @@ class WhisperManager {
commonCandidates.forEach(addCandidate);
for (const pythonPath of candidateSet) {
- if (path.isAbsolute(pythonPath) && !fs.existsSync(pythonPath)) {
+ // Windows-specific: resolve relative commands to absolute paths
+ let resolvedPath = pythonPath;
+ if (process.platform === "win32" && !path.isAbsolute(pythonPath)) {
+ resolvedPath = await this.resolveWindowsCommand(pythonPath);
+ if (!resolvedPath) {
+ debugLogger.log(`Could not resolve Windows command: ${pythonPath}`);
+ continue;
+ }
+ }
+
+ // Skip absolute paths that don't exist
+ if (path.isAbsolute(resolvedPath) && !fs.existsSync(resolvedPath)) {
+ debugLogger.log(`Python path does not exist: ${resolvedPath}`);
continue;
}
try {
- const version = await this.getPythonVersion(pythonPath);
+ const version = await this.getPythonVersion(resolvedPath);
if (this.isPythonVersionSupported(version)) {
- this.pythonCmd = pythonPath;
- return pythonPath;
+ this.pythonCmd = resolvedPath;
+ debugLogger.log(`Found Python: ${resolvedPath} (version ${version.major}.${version.minor})`);
+ return resolvedPath;
}
} catch (error) {
+ debugLogger.log(`Python version check failed for ${resolvedPath}: ${error.message}`);
continue;
}
}
@@ -508,6 +641,109 @@ class WhisperManager {
);
}
+ async getWindowsRegistryPython() {
+ if (process.platform !== "win32") {
+ return [];
+ }
+
+ const candidates = [];
+ debugLogger.logWindowsPythonSearch?.('Starting registry search', { method: 'registry' });
+
+ try {
+ // Query Windows Registry for Python installations
+ const registryKeys = [
+ 'HKLM\\SOFTWARE\\Python\\PythonCore',
+ 'HKCU\\SOFTWARE\\Python\\PythonCore',
+ 'HKLM\\SOFTWARE\\Wow6432Node\\Python\\PythonCore',
+ ];
+
+ for (const registryKey of registryKeys) {
+ try {
+ debugLogger.log(`Querying registry key: ${registryKey}`);
+
+ // List all Python versions in registry
+ const { stdout } = await runCommand('reg', ['query', registryKey], {
+ timeout: TIMEOUTS.QUICK_CHECK
+ });
+
+ // Parse version folders (e.g., "3.11", "3.12")
+ const versionMatches = stdout.match(/PythonCore\\([\d.]+)/g);
+ debugLogger.log(`Found ${versionMatches?.length || 0} Python versions in ${registryKey}`);
+
+ if (versionMatches) {
+ for (const match of versionMatches) {
+ const version = match.replace('PythonCore\\', '');
+
+ // Query InstallPath for this version
+ try {
+ const installPathKey = `${registryKey}\\${version}\\InstallPath`;
+ const { stdout: pathOutput } = await runCommand('reg', ['query', installPathKey, '/ve'], {
+ timeout: TIMEOUTS.QUICK_CHECK
+ });
+
+ // Extract path from registry output
+ const pathMatch = pathOutput.match(/REG_SZ\s+(.+)/);
+ if (pathMatch && pathMatch[1]) {
+ const installPath = pathMatch[1].trim();
+ const pythonExe = path.join(installPath, 'python.exe');
+
+ debugLogger.log(`Checking Python ${version} at: ${pythonExe}`);
+
+ if (fs.existsSync(pythonExe)) {
+ candidates.push(pythonExe);
+ debugLogger.log(`✓ Found valid Python in registry: ${pythonExe}`);
+ } else {
+ debugLogger.log(`✗ Python exe not found at: ${pythonExe}`);
+ }
+ }
+ } catch (error) {
+ debugLogger.log(`Failed to query InstallPath for ${version}: ${error.message}`);
+ }
+ }
+ }
+ } catch (error) {
+ debugLogger.log(`Failed to query registry key ${registryKey}: ${error.message}`);
+ }
+ }
+ } catch (error) {
+ debugLogger.log('Registry query failed:', error.message);
+ }
+
+ debugLogger.logWindowsPythonSearch?.('Registry search complete', {
+ foundCount: candidates.length,
+ candidates
+ });
+
+ return candidates;
+ }
+
+ async resolveWindowsCommand(command) {
+ if (process.platform !== "win32") {
+ return command;
+ }
+
+ try {
+ // Use 'where' command to find executable in PATH
+ const { stdout } = await runCommand('where', [command], {
+ timeout: TIMEOUTS.QUICK_CHECK
+ });
+
+ // 'where' returns multiple paths, take the first one
+ const paths = stdout.trim().split('\n');
+ if (paths.length > 0) {
+ const resolvedPath = paths[0].trim();
+ if (fs.existsSync(resolvedPath)) {
+ debugLogger.log(`Resolved ${command} to ${resolvedPath}`);
+ return resolvedPath;
+ }
+ }
+ } catch (error) {
+ // Command not found in PATH
+ }
+
+ return null;
+ }
+
getWindowsPythonCandidates() {
const candidates = [];
const versionSuffixes = ["313", "312", "311", "310", "39", "38"];
@@ -584,12 +820,17 @@ class WhisperManager {
async getPythonVersion(pythonPath) {
return new Promise((resolve) => {
- const testProcess = spawn(pythonPath, ["--version"]);
+ // Use shell: false on Windows to ensure exact path is used
+ const spawnOptions = process.platform === "win32"
+ ? { windowsHide: true, shell: false }
+ : {};
+
+ const testProcess = spawn(pythonPath, ["--version"], spawnOptions);
let output = "";
-
+
testProcess.stdout.on("data", (data) => output += data);
testProcess.stderr.on("data", (data) => output += data);
-
+
testProcess.on("close", (code) => {
if (code === 0) {
const match = output.match(/Python (\d+)\.(\d+)/i);
@@ -598,8 +839,11 @@ class WhisperManager {
resolve(null);
}
});
-
- testProcess.on("error", () => resolve(null));
+
+ testProcess.on("error", (error) => {
+ debugLogger.log(`Python version check error for ${pythonPath}: ${error.message}`);
+ resolve(null);
+ });
});
}
@@ -656,65 +900,24 @@ 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");
- debugLogger.logFFmpegDebug('checkFFmpegAvailability', ffmpegPath, {
- NODE_ENV: process.env.NODE_ENV,
- resourcesPath: process.resourcesPath,
- __dirname: __dirname
- });
-
- // Always check if the path exists and handle ASAR unpacking
- if (!fs.existsSync(ffmpegPath)) {
- debugLogger.log('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);
-
- // Check alternative paths
- debugLogger.log('Checking alternative FFmpeg paths for availability check');
-
- for (const possiblePath of possiblePaths) {
- const exists = fs.existsSync(possiblePath);
- // Check path existence
- debugLogger.logFFmpegDebug('Checking availability path', possiblePath);
-
- if (exists) {
- ffmpegPath = possiblePath;
- // Found FFmpeg
- debugLogger.log('FFmpeg found for availability check at:', ffmpegPath);
- break;
- }
- }
- }
-
- // Final validation
- if (!ffmpegPath || !fs.existsSync(ffmpegPath)) {
- debugLogger.log('FFmpeg not found at any location');
- ffmpegPath = null;
- } else {
- // Using bundled FFmpeg
- }
- } catch (e) {
- debugLogger.log('ffmpeg-static error:', e.message);
- ffmpegPath = null;
+ // Use the centralized FFmpeg resolver
+ const ffmpegPath = await this.resolveFfmpegPath();
+
+ if (!ffmpegPath) {
+ debugLogger.log('FFmpeg not found by resolver');
+ return {
+ available: false,
+ error: "FFmpeg not found"
+ };
}
+ debugLogger.log('FFmpeg resolved for availability check:', ffmpegPath);
+
const result = await new Promise((resolve) => {
// Set up environment with FFmpeg path
const env = {