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: migrate to whisper.cpp
Gabriel Stein7d75401066a3
diff --git a/CLAUDE.md b/CLAUDE.mdindex 612faabc9..6291cdc22 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4,7 +4,7 @@ This document provides comprehensive technical details about the OpenWhispr proj## Project Overview-OpenWhispr is an Electron-based desktop dictation application that uses OpenAI Whisper for speech-to-text transcription. It supports both local (privacy-focused) and cloud (OpenAI API) processing modes.+OpenWhispr is an Electron-based desktop dictation application that uses whisper.cpp for speech-to-text transcription. It supports both local (privacy-focused) and cloud (OpenAI API) processing modes.## Architecture Overview@@ -13,7 +13,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses OpenAI W- **Desktop Framework**: Electron 36 with context isolation- **Database**: better-sqlite3 for local transcription history- **UI Components**: shadcn/ui with Radix primitives-- **Speech Processing**: OpenAI Whisper (local Python bridge + API)+- **Speech Processing**: whisper.cpp (bundled native binary) + OpenAI API- **Audio Processing**: FFmpeg (bundled via ffmpeg-static)### Key Architectural Decisions@@ -29,7 +29,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses OpenAI W- Preload Script: Secure bridge between processes3. **Audio Pipeline**:- - MediaRecorder API → Blob → ArrayBuffer → Base64 → IPC → File → FFmpeg → Whisper+ - MediaRecorder API → Blob → ArrayBuffer → IPC → File → whisper.cpp- Automatic cleanup of temporary files after processing## File Structure and Responsibilities@@ -51,9 +51,8 @@ OpenWhispr is an Electron-based desktop dictation application that uses OpenAI W- **hotkeyManager.js**: Global hotkey registration and management- **ipcHandlers.js**: Centralized IPC handler registration- **menuManager.js**: Application menu management-- **pythonInstaller.js**: Automatic Python installation for all platforms- **tray.js**: System tray icon and menu-- **whisper.js**: Local Whisper integration and Python bridge+- **whisper.js**: Local whisper.cpp integration and model management- **windowConfig.js**: Centralized window configuration- **windowManager.js**: Window creation and lifecycle management@@ -74,9 +73,8 @@ OpenWhispr is an Electron-based desktop dictation application that uses OpenAI W- **useHotkey.js**: Hotkey state management- **useLocalStorage.ts**: Type-safe localStorage wrapper- **usePermissions.ts**: System permission checks-- **usePython.ts**: Python installation state- **useSettings.ts**: Application settings management-- **useWhisper.ts**: Whisper model management+- **useWhisper.ts**: Whisper binary availability check### Services@@ -86,13 +84,13 @@ OpenWhispr is an Electron-based desktop dictation application that uses OpenAI W- Removes agent name from final output- Supports GPT-5, Claude Opus 4.1, and Gemini 2.5 models-### Python Bridge+### whisper.cpp Integration-- **whisper_bridge.py**: Standalone Python script for local Whisper- - Accepts audio file path and model selection- - Returns JSON with transcription result- - Handles FFmpeg path resolution for bundled executable- - 30-second timeout protection+- **whisper.js**: Native binary wrapper for local transcription+ - Bundled binaries in `resources/bin/whisper-cpp-{platform}-{arch}`+ - Falls back to system installation (`brew install whisper-cpp`)+ - GGML model downloads from HuggingFace+ - Models stored in `~/.cache/openwhispr/whisper-models/`## Key Implementation Details@@ -101,8 +99,6 @@ OpenWhispr is an Electron-based desktop dictation application that uses OpenAI WFFmpeg is bundled with the app and doesn't require system installation:```javascript// FFmpeg is unpacked from ASAR to app.asar.unpacked/node_modules/ffmpeg-static/-// Python bridge receives FFmpeg path via environment variables:-// FFMPEG_PATH, FFMPEG_EXECUTABLE, FFMPEG_BINARY```### 2. Audio Recording Flow@@ -111,20 +107,20 @@ FFmpeg is bundled with the app and doesn't require system installation:2. Audio chunks collected in array3. User presses hotkey again → Recording stops4. Blob created from chunks → Converted to ArrayBuffer-5. Sent via IPC as Base64 string (size limits)+5. Sent via IPC6. Main process writes to temporary file-7. Whisper processes file → Result sent back+7. whisper.cpp processes file → Result sent back8. Temporary file deleted-### 3. Local Whisper Models+### 3. Local Whisper Models (GGML format)-Models stored in `~/.cache/whisper/`:-- tiny: 39MB (fastest, lowest quality)-- base: 74MB (recommended balance)-- small: 244MB (better quality)-- medium: 769MB (high quality)-- large: 1.5GB (best quality)-- turbo: 809MB (fast with good quality)+Models stored in `~/.cache/openwhispr/whisper-models/`:+- tiny: ~75MB (fastest, lowest quality)+- base: ~142MB (recommended balance)+- small: ~466MB (better quality)+- medium: ~1.5GB (high quality)+- large: ~3GB (best quality)+- turbo: ~1.6GB (fast with good quality)### 4. Database Schema@@ -161,7 +157,7 @@ Settings stored in localStorage with these keys:58 languages supported (see src/utils/languages.ts):- Each language has a two-letter code and label- "auto" for automatic detection-- Passed to Whisper via --language parameter+- Passed to whisper.cpp via -l parameter### 7. Agent Naming System@@ -235,7 +231,7 @@ All AI model definitions are centralized in `src/models/modelRegistryData.json`- Keys stored in environment variables and reloaded on app start- Centralized `saveAllKeysToEnvFile()` method ensures consistency-### 9. Debug Mode+### 10. Debug ModeEnable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `.env`):- Logs saved to platform-specific app data directory@@ -259,7 +255,7 @@ Enable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `- [ ] Verify hotkey works globally- [ ] Check clipboard pasting on all platforms- [ ] Test with different audio input devices-- [ ] Verify Python auto-installation+- [ ] Verify whisper.cpp binary detection- [ ] Test all Whisper models- [ ] Check agent naming functionality@@ -271,7 +267,8 @@ Enable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `- Check audio levels in debug logs2. **Transcription Fails**:- - Ensure Python/Whisper installed+ - Ensure whisper.cpp binary is available+ - Check model is downloaded- Check temporary file creation- Verify FFmpeg is executable@@ -282,7 +279,8 @@ Enable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `4. **Build Issues**:- Use `npm run pack` for unsigned builds (CSC_IDENTITY_AUTO_DISCOVERY=false)- Signing requires Apple Developer account- - ASAR unpacking needed for FFmpeg/Python bridge+ - ASAR unpacking needed for FFmpeg+ - Run `npm run download:whisper-cpp` before packaging- afterSign.js automatically skips signing when CSC_IDENTITY_AUTO_DISCOVERY=false### Platform-Specific Notes@@ -292,16 +290,18 @@ Enable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `- Uses AppleScript for reliable pasting- Notarization needed for distribution- Shows in dock with indicator dot when running (LSUIElement: false)+- whisper.cpp bundled for both arm64 and x64**Windows**:-- Python installer handles PATH automatically- No special permissions needed- NSIS installer for distribution+- whisper.cpp bundled for x64**Linux**:- Multiple package manager support- Standard XDG directories- AppImage for distribution+- whisper.cpp bundled for x64## Code Style and Conventions@@ -318,7 +318,7 @@ Enable with `--log-level=debug` or `OPENWHISPR_LOG_LEVEL=debug` (can be set in `- Audio blob size limits for IPC (10MB)- Temporary file cleanup- Memory usage with large models-- Process timeout protection (30s)+- Process timeout protection (5 minutes)## Security Considerationsdiff --git a/DEBUG.md b/DEBUG.mdindex e026237e7..8c74739ff 100644--- a/DEBUG.md+++ b/DEBUG.md@@ -49,7 +49,7 @@ Look for:### Transcription FailsLook for:-- `Whisper stderr:` → Python/FFmpeg errors+- `Whisper stderr:` → whisper.cpp/FFmpeg errors- `Process closed with code: [non-zero]` → Process failure- `Failed to parse Whisper output` → Invalid JSONdiff --git a/LOCAL_WHISPER_SETUP.md b/LOCAL_WHISPER_SETUP.mdindex b8fdf735e..e2ebb62c0 100644--- a/LOCAL_WHISPER_SETUP.md+++ b/LOCAL_WHISPER_SETUP.md@@ -1,6 +1,6 @@# Local Whisper Setup-OpenWhispr supports local speech-to-text processing using OpenAI's Whisper models. This keeps your audio completely private—nothing leaves your device.+OpenWhispr supports local speech-to-text processing using whisper.cpp. This keeps your audio completely private—nothing leaves your device.## Quick Start@@ -16,54 +16,40 @@ The first transcription will download the model automatically.| Model | Size | Speed | Quality | RAM | Best For ||--------|--------|----------|---------|--------|-----------------------|-| tiny | 39MB | Fastest | Basic | ~1GB | Quick notes |-| base | 74MB | Fast | Good | ~1GB | **Recommended** |-| small | 244MB | Medium | Better | ~2GB | Professional use |-| medium | 769MB | Slow | High | ~5GB | High accuracy |-| large | 1.5GB | Slowest | Best | ~10GB | Maximum quality |-| turbo | 809MB | Fast | High | ~6GB | Best speed/quality |+| tiny | 75MB | Fastest | Basic | ~1GB | Quick notes |+| base | 142MB | Fast | Good | ~1GB | **Recommended** |+| small | 466MB | Medium | Better | ~2GB | Professional use |+| medium | 1.5GB | Slow | High | ~5GB | High accuracy |+| large | 3GB | Slowest | Best | ~10GB | Maximum quality |## How It Works-OpenWhispr automatically:-1. Creates an isolated Python virtual environment (no system modifications)-2. Installs Whisper and dependencies into that environment-3. Downloads the selected model on first use-4. Processes audio locally using FFmpeg (bundled with the app)+OpenWhispr uses whisper.cpp, a high-performance C++ implementation of OpenAI's Whisper model:++1. whisper.cpp binary is bundled with the app (or uses system installation as fallback)+2. GGML models are downloaded on first use to `~/.cache/openwhispr/whisper-models/`+3. Audio is processed locally using FFmpeg (bundled with the app)## Requirements-- **Disk Space**: 39MB–1.5GB depending on model+- **Disk Space**: 75MB–3GB depending on model- **RAM**: 1GB–10GB depending on model-- **Python**: System Python 3.7+ (used only to create the venv)+- **No additional dependencies required** - whisper.cpp is bundled## File Locations| Data | macOS | Windows | Linux ||-------------------|----------------------------------------------|--------------------------------------|---------------------------------|-| Virtual Env | `~/Library/Application Support/OpenWhispr/python/venv` | `%APPDATA%\OpenWhispr\python\venv` | `~/.config/OpenWhispr/python/venv` |-| Models | `~/.cache/whisper/` | `%USERPROFILE%\.cache\whisper\` | `~/.cache/whisper/` |--## Advanced: Custom Python--To use a specific Python interpreter instead of the managed venv:--```bash-# macOS/Linux-export OPENWHISPR_PYTHON=/usr/local/bin/python3.11--# Windows (permanent)-setx OPENWHISPR_PYTHON "C:\Python311\python.exe"-```--When set, OpenWhispr uses this interpreter directly. Ensure Whisper is installed in that environment.+| Models | `~/.cache/openwhispr/whisper-models/` | `%USERPROFILE%\.cache\openwhispr\whisper-models\` | `~/.cache/openwhispr/whisper-models/` |## Troubleshooting### "Not Found" Status1. Click **Recheck Installation** in Control Panel2. Restart the app-3. Check console logs for Python/Whisper errors+3. If bundled binary fails, install via package manager:+ - macOS: `brew install whisper-cpp`+ - Linux: Build from source at https://github.com/ggml-org/whisper.cpp### Transcription Fails1. Verify microphone permissionsdiff --git a/README.md b/README.mdindex 6e8f6909f..071164790 100644--- a/README.md+++ b/README.md@@ -36,7 +36,6 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file- **Node.js 18+** and npm (Download from [nodejs.org](https://nodejs.org/))- **macOS 10.15+**, **Windows 10+**, or **Linux**- On macOS, Globe key support requires the Xcode Command Line Tools (`xcode-select --install`) so the bundled Swift helper can run-- **Python 3.7+** (Optional - the app can install it automatically for local Whisper processing)## Quick Start@@ -280,7 +279,6 @@ The AI automatically detects when you're giving it commands versus dictating regopen-whispr/├── main.js # Electron main process & IPC handlers├── preload.js # Electron preload script & API bridge-├── whisper_bridge.py # Python script for local Whisper processing├── setup.js # First-time setup script├── package.json # Dependencies and scripts├── env.example # Environment variables template@@ -321,8 +319,7 @@ open-whispr/- **Desktop**: Electron 36 with context isolation- **UI Components**: shadcn/ui with Radix primitives- **Database**: better-sqlite3 for local transcription storage-- **Speech-to-Text**: OpenAI Whisper (local models + API)-- **Local Processing**: Python with OpenAI Whisper package+- **Speech-to-Text**: whisper.cpp (local) + OpenAI Whisper API (cloud)- **Icons**: Lucide React for consistent iconography## Development@@ -356,7 +353,7 @@ Both use the same React codebase but render different components based on URL pa- **preload.js**: Secure bridge between main and renderer processes- **App.jsx**: Main dictation interface with recording controls- **ControlPanel.tsx**: Settings, history, and model management-- **whisper_bridge.py**: Python bridge for local Whisper processing+- **src/helpers/whisper.js**: whisper.cpp integration for local processing- **better-sqlite3**: Local database for transcription history### Tailwind CSS v4 Setup@@ -410,25 +407,18 @@ DEBUG=false### Local Whisper Setup-For local processing, OpenWhispr offers automated setup:+For local processing, OpenWhispr uses whisper.cpp - a high-performance C++ implementation:-1. **Isolated Python Environment** (default):- - The app creates a per-user virtual environment under your app data folder- - Uses a bundled Python runtime if present; otherwise uses system Python only to create the venv- - No system-wide `pip install` is performed+1. **Bundled Binary**: whisper.cpp is bundled with the app for all platforms+2. **GGML Models**: Downloads optimized GGML models on first use to `~/.cache/openwhispr/whisper-models/`+3. **No Dependencies**: No Python or other runtime required-2. **Automatic Whisper Setup**:- - Installs OpenAI Whisper inside the isolated environment- - Downloads your chosen model on first use- - Handles all transcription locally--Optional override: set `OPENWHISPR_PYTHON` to force a specific Python interpreter (advanced use).--Release packaging note: place a per-platform Python runtime under `resources/python` to bundle it with the app.+**System Fallback**: If the bundled binary fails, install via package manager:+- macOS: `brew install whisper-cpp`+- Linux: Build from source at https://github.com/ggml-org/whisper.cpp**Requirements**:-- Sufficient disk space for models (39MB - 1.5GB depending on model)-- Admin/sudo access may be required only if you choose to install system Python+- Sufficient disk space for models (75MB - 3GB depending on model)### Customization@@ -478,9 +468,9 @@ OpenWhispr is designed with privacy and security in mind:3. **API key errors** (cloud processing only): Ensure your OpenAI API key is valid and has credits- Set key through Control Panel or .env file- Check logs for "OpenAI API Key present: Yes/No"-4. **Local Whisper installation**:- - OpenWhispr creates an isolated Python environment automatically- - Use Control Panel to install Whisper into that environment+4. **Local Whisper issues**:+ - whisper.cpp is bundled with the app+ - If bundled binary fails, install via `brew install whisper-cpp` (macOS)- Check available disk space for models5. **Global hotkey conflicts**: Change the hotkey in the Control Panel - any key can be used6. **Text not pasting**: Check accessibility permissions and try manual paste with Cmd+V@@ -490,7 +480,7 @@ OpenWhispr is designed with privacy and security in mind:- Check the [Issues](https://github.com/your-repo/open-whispr/issues) page- Review the console logs for debugging information-- For local processing: Ensure the managed Python environment initializes successfully+- For local processing: Ensure whisper.cpp is accessible and models are downloaded- For cloud processing: Verify your OpenAI API key and billing status- Check the Control Panel for system status and diagnosticsdiff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.mdindex 12b71077e..293627b65 100644--- a/TROUBLESHOOTING.md+++ b/TROUBLESHOOTING.md@@ -6,7 +6,7 @@|-------|---------|| Host architecture | `uname -m` || Node architecture | `node -p "process.arch"` |-| Python install | `python3 --version && which python3` |+| whisper.cpp install | `which whisper` or `which whisper-cpp` || FFmpeg availability | `ffmpeg -version` |## Common Issues@@ -45,21 +45,22 @@2. Run `npm run setup` to verify FFmpeg3. If using packaged app, try reinstalling-### Python/Whisper Issues+### whisper.cpp Issues-**Symptoms:** Local transcription fails, "spawn python ENOENT"+**Symptoms:** Local transcription fails, "whisper.cpp not found"**Fix:**-1. OpenWhispr creates an isolated venv automatically-2. If failing, delete the venv folder and retry (see [LOCAL_WHISPER_SETUP.md](LOCAL_WHISPER_SETUP.md))-3. Check if `python3 --version` works in terminal+1. The whisper.cpp binary is bundled with the app+2. If bundled binary fails, install via package manager:+ - macOS: `brew install whisper-cpp`+ - Linux: Build from source at https://github.com/ggml-org/whisper.cpp+3. Clear model cache: `rm -rf ~/.cache/openwhispr/whisper-models`4. Try cloud transcription as fallback### Windows-Specific IssuesSee [WINDOWS_TROUBLESHOOTING.md](WINDOWS_TROUBLESHOOTING.md) for:- Window visibility issues-- Python path detection- FFmpeg permission problems## Enable Debug Modediff --git a/WINDOWS_TROUBLESHOOTING.md b/WINDOWS_TROUBLESHOOTING.mdindex e66bbbb08..49eb84987 100644--- a/WINDOWS_TROUBLESHOOTING.md+++ b/WINDOWS_TROUBLESHOOTING.md@@ -20,15 +20,15 @@2. Verify mic is selected: Sound settings → Input3. Test recording in Windows Voice Recorder first-### Python Not Found+### whisper.cpp Not Working-**Symptoms:** "spawn python ENOENT" error+**Symptoms:** Local transcription fails**Solutions:**-1. Use OpenWhispr's built-in Python installer (Control Panel → Settings)-2. Or install Python 3.11+ from [python.org](https://python.org) with "Add to PATH" checked-3. Verify: `python --version` in Command Prompt-4. Set custom path: `setx OPENWHISPR_PYTHON "C:\Path\To\python.exe"`+1. whisper.cpp is bundled with the app - try reinstalling+2. Check antivirus isn't blocking the whisper-cpp executable+3. Clear model cache: delete `%USERPROFILE%\.cache\openwhispr\whisper-models`+4. Try cloud mode as fallback### FFmpeg Issues@@ -56,9 +56,9 @@ Logs saved to: `%APPDATA%\OpenWhispr\logs\`| Error | Meaning | Fix ||-------|---------|-----|| Audio buffer empty | Mic not capturing | Check permissions, try different mic |-| Python version check failed | Python not responding | Reinstall Python, check PATH |+| whisper.cpp not found | Binary not accessible | Reinstall app, check antivirus || FFmpeg not found | Can't find FFmpeg | Reinstall app, check antivirus |-| Whisper installation failed | Can't install Whisper | Check Python, internet; try cloud mode |+| Model download failed | Can't download GGML model | Check internet; try cloud mode |## Windows-Specific Tipsdiff --git a/electron-builder.json b/electron-builder.jsonindex 7c347f27b..ef9a5e698 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -9,7 +9,6 @@"files": ["main.js","preload.js",- "whisper_bridge.py","package.json","node_modules/**/*","src/dist/**/*",@@ -24,7 +23,6 @@"!src/node_modules/**/*"],"asarUnpack": [- "whisper_bridge.py","**/node_modules/ffmpeg-static/**/*","**/node_modules/better-sqlite3/**/*"],@@ -32,7 +30,7 @@"src/assets/**/*","resources/macos-globe-listener.swift","resources/bin/macos-globe-listener",- "resources/python/**/*"+ "resources/bin/whisper-cpp-*"],"mac": {"category": "public.app-category.productivity",@@ -97,10 +95,10 @@},"deb": {"afterRemove": "resources/linux/after-remove.sh",- "fpm": ["--deb-recommends", "xdotool", "--deb-recommends", "wtype", "--deb-recommends", "python3"]+ "fpm": ["--deb-recommends", "xdotool", "--deb-recommends", "wtype"]},"rpm": {- "fpm": ["--rpm-tag", "Recommends: xdotool", "--rpm-tag", "Recommends: wtype", "--rpm-tag", "Recommends: python3"]+ "fpm": ["--rpm-tag", "Recommends: xdotool", "--rpm-tag", "Recommends: wtype"]},"nsis": {"oneClick": false,diff --git a/main.js b/main.jsindex 2d0bd62b4..f9f10d8ee 100644--- a/main.js+++ b/main.js@@ -32,7 +32,7 @@ const IPCHandlers = require("./src/helpers/ipcHandlers");const UpdateManager = require("./src/updater");const GlobeKeyManager = require("./src/helpers/globeKeyManager");-// Set up PATH for production builds to find system Python+// Set up PATH for production builds to find system tools (whisper.cpp, ffmpeg)function setupProductionPath() {if (process.platform === 'darwin' && process.env.NODE_ENV !== 'development') {const commonPaths = [@@ -41,15 +41,12 @@ function setupProductionPath() {'/usr/bin','/bin','/usr/sbin',- '/sbin',- '/Library/Frameworks/Python.framework/Versions/3.11/bin',- '/Library/Frameworks/Python.framework/Versions/3.10/bin',- '/Library/Frameworks/Python.framework/Versions/3.9/bin'+ '/sbin'];-+const currentPath = process.env.PATH || '';const pathsToAdd = commonPaths.filter(p => !currentPath.includes(p));-+if (pathsToAdd.length > 0) {process.env.PATH = `${currentPath}:${pathsToAdd.join(':')}`;}diff --git a/package.json b/package.jsonindex 0118d6ca5..133f6fb86 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "open-whispr","version": "1.1.2",- "description": "A desktop dictation application using OpenAI Whisper for speech-to-text transcription",+ "description": "A desktop dictation application using whisper.cpp for speech-to-text transcription","main": "main.js","private": true,"scripts": {@@ -28,10 +28,10 @@"pack": "npm run build:renderer && CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --dir","predist": "npm run compile:globe","dist": "npm run build:renderer && electron-builder",+ "download:whisper-cpp": "node scripts/download-whisper-cpp.js","format:js": "eslint . --fix && cd src && eslint . --fix && prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\"",- "format:py": "python3 -m ruff check --fix *.py && python3 -m ruff format *.py",- "format": "npm run format:js && npm run format:py",- "format:check": "eslint . && cd src && eslint . && prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\" && python3 -m ruff check *.py",+ "format": "npm run format:js",+ "format:check": "eslint . && cd src && eslint . && prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\"","preview": "cd src && vite preview","clean": "node cleanup.js"},@@ -39,7 +39,7 @@"dictation","speech-to-text","whisper",- "openai",+ "whisper.cpp","electron","desktop-app"],diff --git a/preload.js b/preload.jsindex 401962557..0afcb9fa9 100644--- a/preload.js+++ b/preload.js@@ -70,19 +70,11 @@ contextBridge.exposeInMainWorld("electronAPI", {writeClipboard: (text) => ipcRenderer.invoke("write-clipboard", text),checkPasteTools: () => ipcRenderer.invoke("check-paste-tools"),- // Python installation functions- checkPythonInstallation: () =>- ipcRenderer.invoke("check-python-installation"),- installPython: () => ipcRenderer.invoke("install-python"),- onPythonInstallProgress: registerListener("python-install-progress"),-- // Local Whisper functions+ // Local Whisper functions (whisper.cpp)transcribeLocalWhisper: (audioBlob, options) =>ipcRenderer.invoke("transcribe-local-whisper", audioBlob, options),checkWhisperInstallation: () =>ipcRenderer.invoke("check-whisper-installation"),- installWhisper: () => ipcRenderer.invoke("install-whisper"),- onWhisperInstallProgress: registerListener("whisper-install-progress"),downloadWhisperModel: (modelName) =>ipcRenderer.invoke("download-whisper-model", modelName),onWhisperDownloadProgress: registerListener("whisper-download-progress"),diff --git a/pyproject.toml b/pyproject.tomldeleted file mode 100644index ff08f5e50..000000000--- a/pyproject.toml+++ /dev/null@@ -1,22 +0,0 @@-[tool.ruff]-# Relaxed Python linting and formatting-line-length = 120-target-version = "py311"--[tool.ruff.lint]-# Only catch important issues, not style nitpicks-select = [- "E", # pycodestyle errors (syntax issues)- "F", # pyflakes (undefined names, unused imports)- "W", # pycodestyle warnings-]-ignore = [- "E501", # line too long (let formatter handle it)- "E402", # module level import not at top-]--[tool.ruff.format]-# Use double quotes like Prettier-quote-style = "double"-indent-style = "space"-line-ending = "lf"diff --git a/resources/python/README.md b/resources/python/README.mddeleted file mode 100644index 531a9c111..000000000--- a/resources/python/README.md+++ /dev/null@@ -1,20 +0,0 @@-Bundled Python runtime--Place per-platform Python runtimes in this folder during packaging.-OpenWhispr will prefer these binaries if present and create an isolated-virtual environment under the user's app data directory.--IMPORTANT: The bundled Python MUST include venv and ensurepip modules.-The Windows embeddable distribution does NOT include these - use the full-installer or a relocatable build instead.--Expected layouts:-- Windows: resources/python/python.exe (full installer, NOT embeddable)-- macOS/Linux: resources/python/bin/python3 (relocatable Python build)--Requirements for bundled Python:-- Python 3.8+ (3.11 recommended)-- venv module (python -m venv must work)-- ensurepip module (for pip bootstrapping)--This folder ships with the app via electron-builder extraResources.diff --git a/scripts/download-whisper-cpp.js b/scripts/download-whisper-cpp.jsnew file mode 100644index 000000000..336c9ea80--- /dev/null+++ b/scripts/download-whisper-cpp.js@@ -0,0 +1,255 @@+#!/usr/bin/env node+/**+ * Downloads whisper.cpp binaries from OpenWhispr's fork releases.+ *+ * Binaries are built via GitHub Actions and published to:+ * https://github.com/gabrielste1n/whisper.cpp/releases+ */++const https = require("https");+const fs = require("fs");+const path = require("path");+const { execSync } = require("child_process");++// Configuration - Update WHISPER_CPP_VERSION when releasing new builds+const WHISPER_CPP_REPO = "gabrielste1n/whisper.cpp";+const WHISPER_CPP_VERSION = "0.0.3";++// Platform-specific binary info+const BINARIES = {+ "darwin-arm64": {+ zipName: "whisper-cpp-darwin-arm64.zip",+ binaryName: "whisper-cpp-darwin-arm64",+ outputName: "whisper-cpp-darwin-arm64",+ },+ "darwin-x64": {+ zipName: "whisper-cpp-darwin-x64.zip",+ binaryName: "whisper-cpp-darwin-x64",+ outputName: "whisper-cpp-darwin-x64",+ },+ "win32-x64": {+ zipName: "whisper-cpp-win32-x64.zip",+ binaryName: "whisper-cpp-win32-x64.exe",+ outputName: "whisper-cpp-win32-x64.exe",+ },+ "linux-x64": {+ zipName: "whisper-cpp-linux-x64.zip",+ binaryName: "whisper-cpp-linux-x64",+ outputName: "whisper-cpp-linux-x64",+ },+};++const BIN_DIR = path.join(__dirname, "..", "resources", "bin");++function getDownloadUrl(zipName) {+ return `https://github.com/${WHISPER_CPP_REPO}/releases/download/${WHISPER_CPP_VERSION}/${zipName}`;+}++const REQUEST_TIMEOUT = 30000; // 30 seconds for connection+const MAX_RETRIES = 3;+const RETRY_DELAY = 2000; // 2 seconds between retries++function sleep(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function downloadFile(url, dest, retryCount = 0) {+ return new Promise((resolve, reject) => {+ const file = fs.createWriteStream(dest);+ let activeRequest = null;++ const cleanup = () => {+ if (activeRequest) {+ activeRequest.destroy();+ activeRequest = null;+ }+ file.close();+ };++ const request = (currentUrl, redirectCount = 0) => {+ // Prevent infinite redirects+ if (redirectCount > 5) {+ cleanup();+ reject(new Error("Too many redirects"));+ return;+ }++ activeRequest = https.get(currentUrl, (response) => {+ if (response.statusCode === 302 || response.statusCode === 301) {+ const redirectUrl = response.headers.location;+ if (!redirectUrl) {+ cleanup();+ reject(new Error("Redirect without location header"));+ return;+ }+ request(redirectUrl, redirectCount + 1);+ return;+ }++ if (response.statusCode !== 200) {+ cleanup();+ reject(new Error(`Failed to download: HTTP ${response.statusCode}`));+ return;+ }++ const total = parseInt(response.headers["content-length"], 10);+ let downloaded = 0;++ response.on("data", (chunk) => {+ downloaded += chunk.length;+ const pct = total ? Math.round((downloaded / total) * 100) : 0;+ process.stdout.write(`\r Downloading: ${pct}%`);+ });++ response.on("error", (err) => {+ cleanup();+ reject(err);+ });++ response.pipe(file);+ file.on("finish", () => {+ file.close();+ console.log(" Done");+ resolve();+ });++ file.on("error", (err) => {+ cleanup();+ reject(err);+ });+ });++ activeRequest.on("error", (err) => {+ cleanup();+ reject(err);+ });++ // Connection timeout+ activeRequest.setTimeout(REQUEST_TIMEOUT, () => {+ cleanup();+ reject(new Error("Connection timed out"));+ });+ };++ request(url);+ }).catch(async (error) => {+ // Retry logic for transient failures+ if (retryCount < MAX_RETRIES) {+ console.log(`\n Retry ${retryCount + 1}/${MAX_RETRIES}: ${error.message}`);+ await sleep(RETRY_DELAY);+ // Clean up partial file before retry+ if (fs.existsSync(dest)) {+ fs.unlinkSync(dest);+ }+ return downloadFile(url, dest, retryCount + 1);+ }+ throw error;+ });+}++function extractZip(zipPath, destDir) {+ if (process.platform === "win32") {+ execSync(`powershell -command "Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force"`, { stdio: "inherit" });+ } else {+ execSync(`unzip -o "${zipPath}" -d "${destDir}"`, { stdio: "inherit" });+ }+}++async function downloadBinary(platformArch) {+ const config = BINARIES[platformArch];+ if (!config) {+ console.log(` ${platformArch}: Not supported`);+ return false;+ }++ const outputPath = path.join(BIN_DIR, config.outputName);++ if (fs.existsSync(outputPath)) {+ console.log(` ${platformArch}: Already exists, skipping`);+ return true;+ }++ const url = getDownloadUrl(config.zipName);+ console.log(` ${platformArch}: Downloading from ${url}`);++ const zipPath = path.join(BIN_DIR, config.zipName);++ try {+ await downloadFile(url, zipPath);++ const extractDir = path.join(BIN_DIR, `temp-${platformArch}`);+ fs.mkdirSync(extractDir, { recursive: true });+ extractZip(zipPath, extractDir);++ // Find and copy the binary+ const binaryPath = path.join(extractDir, config.binaryName);+ if (fs.existsSync(binaryPath)) {+ fs.copyFileSync(binaryPath, outputPath);+ if (process.platform !== "win32") {+ fs.chmodSync(outputPath, 0o755);+ }+ console.log(` ${platformArch}: Extracted to ${config.outputName}`);+ } else {+ console.error(` ${platformArch}: Binary not found in archive`);+ return false;+ }++ // Cleanup+ fs.rmSync(extractDir, { recursive: true, force: true });+ fs.unlinkSync(zipPath);+ return true;++ } catch (error) {+ console.error(` ${platformArch}: Failed - ${error.message}`);+ if (fs.existsSync(zipPath)) fs.unlinkSync(zipPath);+ return false;+ }+}++async function main() {+ console.log(`\nDownloading whisper.cpp binaries (${WHISPER_CPP_VERSION})...\n`);++ // Create bin directory+ fs.mkdirSync(BIN_DIR, { recursive: true });++ const currentPlatform = process.platform;+ const currentArch = process.arch;+ const currentPlatformArch = `${currentPlatform}-${currentArch}`;++ if (process.argv.includes("--current")) {+ // Only download for current platform+ console.log(`Downloading for current platform (${currentPlatformArch}):`);+ await downloadBinary(currentPlatformArch);+ } else if (process.argv.includes("--all")) {+ // Download all platforms+ console.log("Downloading all platform binaries:");+ for (const platformArch of Object.keys(BINARIES)) {+ await downloadBinary(platformArch);+ }+ } else {+ // Default: download for build targets (all platforms)+ console.log("Downloading binaries for all platforms:");+ for (const platformArch of Object.keys(BINARIES)) {+ await downloadBinary(platformArch);+ }+ }++ console.log("\n---");++ // List what we have+ const files = fs.readdirSync(BIN_DIR).filter(f => f.startsWith("whisper-cpp"));+ if (files.length > 0) {+ console.log("Available binaries:");+ files.forEach(f => {+ const stats = fs.statSync(path.join(BIN_DIR, f));+ console.log(` - ${f} (${Math.round(stats.size / 1024 / 1024)}MB)`);+ });+ } else {+ console.log("No binaries downloaded yet.");+ console.log("\nMake sure you've created a release in your whisper.cpp fork:");+ console.log(` https://github.com/${WHISPER_CPP_REPO}/releases`);+ console.log("\nRun the GitHub Actions workflow 'Build Binaries for OpenWhispr' first.");+ }+}++main().catch(console.error);diff --git a/setup.js b/setup.jsindex 76a0d8816..32af970f2 100644--- a/setup.js+++ b/setup.js@@ -44,6 +44,6 @@ Note: Make sure you have the necessary system permissions for:- Microphone access- Accessibility permissions (for text pasting)-For local Whisper processing, OpenWhispr will create an isolated Python environment automatically.-If you want to use a custom interpreter, set OPENWHISPR_PYTHON to a valid Python 3.x path.+For local Whisper processing, OpenWhispr uses whisper.cpp (bundled with the app).+Models are downloaded automatically on first use.`);diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex de0351edb..95cedaf8b 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -9,7 +9,6 @@ import {Check,Settings,Mic,- Download,Key,Shield,Command,@@ -29,8 +28,6 @@ import StepProgress from "./ui/StepProgress";import { AlertDialog, ConfirmDialog } from "./ui/dialog";import { useLocalStorage } from "../hooks/useLocalStorage";import { useDialogs } from "../hooks/useDialogs";-import { useWhisper } from "../hooks/useWhisper";-import { usePython } from "../hooks/usePython";import { usePermissions } from "../hooks/usePermissions";import { useClipboard } from "../hooks/useClipboard";import { useSettings } from "../hooks/useSettings";@@ -313,9 +310,6 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {return match?.label || reasoningModel;}, [displayedReasoningModels, reasoningModel]);- const whisperHook = useWhisper(showAlertDialog);- const { setupProgressListener } = whisperHook;- const pythonHook = usePython(showAlertDialog);const permissionsHook = usePermissions(showAlertDialog);const { pasteFromClipboard } = useClipboard(showAlertDialog);@@ -330,13 +324,6 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {{ title: "Finish", icon: Check },];- useEffect(() => {- const dispose = setupProgressListener();- return () => {- dispose?.();- };- }, [setupProgressListener]);-const updateProcessingMode = (useLocal: boolean) => {updateTranscriptionSettings({ useLocalWhisper: useLocal });};@@ -586,140 +573,30 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {{useLocalWhisper ? (<div className="space-y-4">- {/* Python Installation Section */}- {!pythonHook.hasChecked ? (- <div className="text-center space-y-4">- <div className="w-16 h-16 mx-auto bg-blue-50 rounded-full flex items-center justify-center">- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>- </div>- <h3 className="font-semibold text-gray-900">Looking for Python...</h3>- <p className="text-sm text-gray-600 max-w-md mx-auto">- OpenWhispr is scanning for your existing Python install (including{" "}- <code>py.exe</code> and any paths supplied via <code>OPENWHISPR_PYTHON</code>- ). Sit tight—if we find one, we’ll skip this step automatically.- </p>- </div>- ) : !pythonHook.pythonInstalled ? (- <div className="text-center space-y-4">- <div className="w-16 h-16 mx-auto bg-blue-100 rounded-full flex items-center justify-center">- <Download className="w-8 h-8 text-blue-600" />- </div>- <div>- <h3 className="font-semibold text-gray-900 mb-2">Install Python</h3>- <p className="text-sm text-gray-600 mb-4">- Python is required for local processing. We'll install it automatically for- you.- </p>- </div>-- {pythonHook.installingPython ? (- <div className="bg-blue-50 p-4 rounded-lg">- <div className="flex items-center justify-center gap-3 mb-3">- <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>- <span className="font-medium text-blue-900">Installing Python...</span>- </div>- {pythonHook.installProgress && (- <div className="text-xs text-blue-600 bg-white p-2 rounded font-mono">- {pythonHook.installProgress}- </div>- )}- <p className="text-xs text-blue-600 mt-2">- This may take a few minutes. Please keep the app open.- </p>- </div>- ) : (- <div className="space-y-3">- <Button- onClick={() => {- pythonHook.installPython();- }}- className="w-full bg-blue-600 hover:bg-blue-700"- disabled={pythonHook.isChecking}- >- {pythonHook.isChecking ? "Please Wait..." : "Install Python"}- </Button>- <Button- variant="ghost"- size="sm"- className="w-full justify-center text-indigo-600"- disabled={pythonHook.isChecking}- onClick={() =>- showConfirmDialog({- title: "Use existing Python?",- description:- "We’ll skip the installer and search for the interpreter already on your system (including OPENWHISPR_PYTHON and the Windows py launcher). Continue?",- confirmText: "Use Existing Python",- cancelText: "Keep Installing",- onConfirm: () => {- pythonHook.checkPythonInstallation();- },- })- }- >- Use Existing Python Instead- </Button>- </div>- )}- </div>- ) : !whisperHook.whisperInstalled ? (- <div className="text-center space-y-4">- <div className="w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center">- <Download className="w-8 h-8 text-purple-600" />- </div>- <div>- <h3 className="font-semibold text-gray-900 mb-2">Install Whisper</h3>- <p className="text-sm text-gray-600 mb-4">- Python is ready! Now we'll install Whisper for speech recognition.- </p>- </div>-- {whisperHook.installingWhisper ? (- <div className="bg-purple-50 p-4 rounded-lg">- <div className="flex items-center justify-center gap-3 mb-3">- <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-purple-600"></div>- <span className="font-medium text-purple-900">Installing...</span>- </div>- {whisperHook.installProgress && (- <div className="text-xs text-purple-600 bg-white p-2 rounded font-mono">- {whisperHook.installProgress}- </div>- )}- <p className="text-xs text-purple-600 mt-2">- This may take a few minutes. Please keep the app open.- </p>- </div>- ) : (- <Button onClick={whisperHook.installWhisper} className="w-full">- Install Whisper- </Button>- )}+ <div className="text-center">+ <div className="w-16 h-16 mx-auto bg-blue-100 rounded-full flex items-center justify-center mb-4">+ <Mic className="w-8 h-8 text-blue-600" /></div>- ) : (- <div className="space-y-4">- <div className="text-center">- <div className="w-16 h-16 mx-auto bg-green-100 rounded-full flex items-center justify-center mb-4">- <Check className="w-8 h-8 text-green-600" />- </div>- <h3 className="font-semibold text-green-900 mb-2">Whisper Installed!</h3>- <p className="text-sm text-gray-600">Now choose your model quality:</p>- </div>+ <h3 className="font-semibold text-gray-900 mb-2">Choose Your Model</h3>+ <p className="text-sm text-gray-600">+ Select a transcription model based on your needs.+ </p>+ </div>- <div>- <label className="block text-sm font-medium text-gray-700 mb-3">- Choose your model quality below- </label>- <p className="text-xs text-gray-500">- Download and select the model that best fits your needs.- </p>- </div>+ <div>+ <label className="block text-sm font-medium text-gray-700 mb-3">+ Model quality+ </label>+ <p className="text-xs text-gray-500">+ Larger models are more accurate but slower. Base is recommended for most users.+ </p>+ </div>- <LocalWhisperPicker- selectedModel={whisperModel}- onModelSelect={setWhisperModel}- variant="onboarding"- />- </div>- )}+ <LocalWhisperPicker+ selectedModel={whisperModel}+ onModelSelect={setWhisperModel}+ variant="onboarding"+ /></div>) : (<div className="space-y-4">@@ -1139,7 +1016,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {return true; // Mode selectioncase 2:if (useLocalWhisper) {- return pythonHook.pythonInstalled && whisperHook.whisperInstalled;+ return whisperModel !== ""; // Just need a model selected} else {const trimmedKey = apiKey.trim();if (!trimmedKey) {diff --git a/src/helpers/debugLogger.js b/src/helpers/debugLogger.jsindex 038436ca8..d37932902 100644--- a/src/helpers/debugLogger.js+++ b/src/helpers/debugLogger.js@@ -296,22 +296,6 @@ class DebugLogger {this.debug(`FFmpeg Debug - ${context}`, debugInfo, "ffmpeg");}- logWindowsPythonSearch(context, details) {- if (!this.isDebugEnabled() || process.platform !== "win32") return;-- this.debug(- `Windows Python Search - ${context}`,- {- ...details,- platform: process.platform,- PATH: process.env.PATH?.substring(0, 300) + "...",- LOCALAPPDATA: process.env.LOCALAPPDATA,- ProgramFiles: process.env.ProgramFiles,- },- "python"- );- }-logAudioData(context, audioBlob) {if (!this.isDebugEnabled()) return;diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 058fb3bbb..e265a5837 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -180,55 +180,6 @@ class IPCHandlers {return this.whisperManager.checkWhisperInstallation();});- ipcMain.handle("check-python-installation", async (event) => {- return this.whisperManager.checkPythonInstallation();- });-- ipcMain.handle("install-python", async (event) => {- try {- const result = await this.whisperManager.installPython((progress) => {- event.sender.send("python-install-progress", {- type: "progress",- stage: progress.stage,- percentage: progress.percentage,- });- });- return result;- } catch (error) {- throw error;- }- });-- ipcMain.handle("install-whisper", async (event) => {- try {- // Set up progress forwarding for installation- const originalConsoleLog = console.log;- console.log = (...args) => {- const message = args.join(" ");- if (- message.includes("Installing") ||- message.includes("Downloading") ||- message.includes("Collecting")- ) {- event.sender.send("whisper-install-progress", {- type: "progress",- message: message,- });- }- originalConsoleLog(...args);- };-- const result = await this.whisperManager.installWhisper();-- // Restore original console.log- console.log = originalConsoleLog;-- return result;- } catch (error) {- throw error;- }- });-ipcMain.handle("download-whisper-model", async (event, modelName) => {try {const result = await this.whisperManager.downloadWhisperModel(modelName, (progressData) => {diff --git a/src/helpers/pythonInstaller.js b/src/helpers/pythonInstaller.jsdeleted file mode 100644index 812b675f5..000000000--- a/src/helpers/pythonInstaller.js+++ /dev/null@@ -1,382 +0,0 @@-const fs = require("fs");-const path = require("path");-const https = require("https");-const os = require("os");-const { runCommand, TIMEOUTS } = require("../utils/process");--class PythonInstaller {- constructor() {- this.pythonVersion = "3.11.9"; // Latest stable version compatible with Whisper- }-- async downloadFile(url, outputPath, progressCallback = null) {- return new Promise((resolve, reject) => {- const file = fs.createWriteStream(outputPath);-- https- .get(url, (response) => {- if (response.statusCode !== 200) {- reject(new Error(`Failed to download: HTTP ${response.statusCode}`));- return;- }-- const totalSize = parseInt(response.headers["content-length"], 10);- let downloadedSize = 0;-- response.on("data", (chunk) => {- downloadedSize += chunk.length;- if (progressCallback && totalSize) {- progressCallback({- downloaded: downloadedSize,- total: totalSize,- percentage: Math.round((downloadedSize / totalSize) * 100),- });- }- });-- response.pipe(file);-- file.on("finish", () => {- file.close();- resolve();- });-- file.on("error", (error) => {- fs.unlink(outputPath, () => {}); // Clean up on error- reject(error);- });- })- .on("error", (error) => {- reject(error);- });- });- }-- async installPythonMacOS(progressCallback = null) {- const platform = process.arch === "arm64" ? "macos11" : "macosx10.9";- const installerUrl = `https://www.python.org/ftp/python/${this.pythonVersion}/python-${this.pythonVersion}-${platform}.pkg`;-- const tempDir = os.tmpdir();- const installerPath = path.join(tempDir, `python-${this.pythonVersion}.pkg`);-- try {- // Check if Homebrew is available first (preferred method)- try {- await runCommand("brew", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });- console.log("Installing Python via Homebrew...");-- if (progressCallback) {- progressCallback({ stage: "Installing Python via Homebrew...", percentage: 25 });- }-- await runCommand("brew", ["install", "[email protected]"], { timeout: TIMEOUTS.INSTALL });-- if (progressCallback) {- progressCallback({ stage: "Python installation complete!", percentage: 100 });- }-- return { success: true, method: "homebrew" };- } catch (brewError) {- console.log("Homebrew not available, using official installer...");-- if (progressCallback) {- progressCallback({ stage: "Downloading Python installer...", percentage: 10 });- }-- // Download official Python installer- await this.downloadFile(installerUrl, installerPath, (progress) => {- if (progressCallback) {- progressCallback({- stage: `Downloading Python installer... ${progress.percentage}%`,- percentage: 10 + progress.percentage * 0.4, // 10-50%- });- }- });-- if (progressCallback) {- progressCallback({ stage: "Installing Python...", percentage: 60 });- }-- // Install Python silently- await runCommand("sudo", ["installer", "-pkg", installerPath, "-target", "/"], {- timeout: TIMEOUTS.INSTALL,- });-- // Clean up- fs.unlink(installerPath, () => {});-- if (progressCallback) {- progressCallback({ stage: "Python installation complete!", percentage: 100 });- }-- return { success: true, method: "official_installer" };- }- } catch (error) {- // Clean up on error- if (fs.existsSync(installerPath)) {- fs.unlink(installerPath, () => {});- }- throw error;- }- }-- async checkWindowsAdmin() {- try {- // Try to read a protected registry key to check admin rights- await runCommand("reg", ["query", "HKU\\S-1-5-19"], { timeout: TIMEOUTS.QUICK_CHECK });- return true;- } catch (error) {- return false;- }- }-- async installPythonWindows(progressCallback = null) {- const arch = process.arch === "ia32" ? "" : "-amd64";- const installerUrl = `https://www.python.org/ftp/python/${this.pythonVersion}/python-${this.pythonVersion}${arch}.exe`;-- const tempDir = os.tmpdir();- const installerPath = path.join(tempDir, `python-${this.pythonVersion}.exe`);-- try {- // Check for admin rights- const isAdmin = await this.checkWindowsAdmin();-- if (progressCallback) {- progressCallback({ stage: "Downloading Python installer...", percentage: 10 });- }-- // Download Python installer- await this.downloadFile(installerUrl, installerPath, (progress) => {- if (progressCallback) {- progressCallback({- stage: `Downloading Python installer... ${progress.percentage}%`,- percentage: 10 + progress.percentage * 0.4, // 10-50%- });- }- });-- if (progressCallback) {- progressCallback({ stage: "Installing Python...", percentage: 60 });- }-- // Determine install target directory for later verification- // Version without dots for folder name (e.g., "311" from "3.11.9")- const versionShort = this.pythonVersion.split(".").slice(0, 2).join("");- let expectedPythonPath;-- // Install Python with appropriate options based on admin rights- const installArgs = isAdmin- ? [- "/quiet",- "InstallAllUsers=1",- "PrependPath=1",- "Include_test=0",- "Include_doc=0",- "Include_dev=0",- "Include_debug=0",- "Include_launcher=1",- "InstallLauncherAllUsers=1",- ]- : [- "/quiet",- "InstallAllUsers=0",- "PrependPath=1",- "Include_test=0",- "Include_doc=0",- "Include_dev=0",- "Include_debug=0",- "Include_launcher=1",- "InstallLauncherAllUsers=0",- `DefaultJustForMeTargetDir=${process.env.LOCALAPPDATA}\\Programs\\Python\\Python${versionShort}`,- ];-- // Determine expected install path based on admin rights- if (isAdmin) {- // System-wide install goes to Program Files- expectedPythonPath = path.join(- process.env.ProgramFiles || "C:\\Program Files",- `Python${versionShort}`,- "python.exe"- );- } else {- // User install goes to LOCALAPPDATA- expectedPythonPath = path.join(- process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"),- "Programs",- "Python",- `Python${versionShort}`,- "python.exe"- );- }-- await runCommand(installerPath, installArgs, { timeout: TIMEOUTS.INSTALL });-- // Clean up installer- fs.unlink(installerPath, () => {});-- if (progressCallback) {- progressCallback({ stage: "Verifying installation...", percentage: 90 });- }-- // Verify the installation by checking if python.exe exists at expected location- // Give Windows a moment to finalize the installation- await new Promise((resolve) => setTimeout(resolve, 1000));-- let installedPythonPath = null;-- // Check expected path first- if (fs.existsSync(expectedPythonPath)) {- installedPythonPath = expectedPythonPath;- } else {- // Fallback: scan common Windows Python install locations- const possiblePaths = [- path.join(process.env.LOCALAPPDATA || "", "Programs", "Python", `Python${versionShort}`, "python.exe"),- path.join(process.env.ProgramFiles || "", `Python${versionShort}`, "python.exe"),- path.join(process.env["ProgramFiles(x86)"] || "", `Python${versionShort}`, "python.exe"),- path.join("C:", `Python${versionShort}`, "python.exe"),- ];-- for (const p of possiblePaths) {- if (p && fs.existsSync(p)) {- installedPythonPath = p;- break;- }- }- }-- if (progressCallback) {- progressCallback({ stage: "Python installation complete!", percentage: 100 });- }-- return {- success: true,- method: "official_installer",- pythonPath: installedPythonPath, // Return the actual path for immediate use- };- } catch (error) {- // Clean up on error- if (fs.existsSync(installerPath)) {- fs.unlink(installerPath, () => {});- }- throw error;- }- }-- async installPythonLinux(progressCallback = null) {- try {- if (progressCallback) {- progressCallback({ stage: "Detecting Linux distribution...", percentage: 10 });- }-- // Detect package manager and install Python- try {- // Try apt (Debian/Ubuntu)- await runCommand("apt", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });-- if (progressCallback) {- progressCallback({ stage: "Installing Python via apt...", percentage: 30 });- }-- await runCommand("sudo", ["apt", "update"], { timeout: TIMEOUTS.PIP_UPGRADE });-- const preferredPackages = [- "python3.11",- "python3.11-pip",- "python3.11-dev",- "python3.11-venv",- ];-- try {- await runCommand("sudo", ["apt", "install", "-y", ...preferredPackages], {- timeout: TIMEOUTS.INSTALL,- });- } catch (installError) {- const fallbackPackages = ["python3", "python3-pip", "python3-dev", "python3-venv"];- await runCommand("sudo", ["apt", "install", "-y", ...fallbackPackages], {- timeout: TIMEOUTS.INSTALL,- });- }-- if (progressCallback) {- progressCallback({ stage: "Python installation complete!", percentage: 100 });- }-- return { success: true, method: "apt" };- } catch (aptError) {- try {- // Try yum (RHEL/CentOS/Fedora)- await runCommand("yum", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });-- if (progressCallback) {- progressCallback({ stage: "Installing Python via yum...", percentage: 30 });- }-- // Note: python311-libs typically includes venv on RHEL/Fedora, but we add it explicitly for safety- await runCommand(- "sudo",- [- "yum",- "install",- "-y",- "python311",- "python311-pip",- "python311-devel",- "python311-libs",- ],- { timeout: TIMEOUTS.INSTALL }- );-- if (progressCallback) {- progressCallback({ stage: "Python installation complete!", percentage: 100 });- }-- return { success: true, method: "yum" };- } catch (yumError) {- try {- // Try pacman (Arch Linux)- await runCommand("pacman", ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });-- if (progressCallback) {- progressCallback({ stage: "Installing Python via pacman...", percentage: 30 });- }-- await runCommand("sudo", ["pacman", "-S", "--noconfirm", "python", "python-pip"], {- timeout: TIMEOUTS.INSTALL,- });-- if (progressCallback) {- progressCallback({ stage: "Python installation complete!", percentage: 100 });- }-- return { success: true, method: "pacman" };- } catch (pacmanError) {- throw new Error("No supported package manager found (apt, yum, or pacman)");- }- }- }- } catch (error) {- throw new Error(`Linux Python installation failed: ${error.message}`);- }- }-- async installPython(progressCallback = null) {- const platform = process.platform;-- if (progressCallback) {- progressCallback({ stage: "Starting Python installation...", percentage: 5 });- }-- switch (platform) {- case "darwin":- return await this.installPythonMacOS(progressCallback);- case "win32":- return await this.installPythonWindows(progressCallback);- case "linux":- return await this.installPythonLinux(progressCallback);- default:- throw new Error(`Unsupported platform: ${platform}`);- }- }-}--module.exports = PythonInstaller;diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex 8f1b7126f..36a057fc3 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -5,259 +5,182 @@ const fsPromises = require("fs").promises;const os = require("os");const path = require("path");const crypto = require("crypto");-const PythonInstaller = require("./pythonInstaller");+const https = require("https");const { runCommand, killProcess, TIMEOUTS } = require("../utils/process");const debugLogger = require("./debugLogger");-// Cache TTL - mirrors CACHE_CONFIG.AVAILABILITY_CHECK_TTL in src/config/constants.ts+// Cache TTL for availability checksconst CACHE_TTL_MS = 30000;+// GGML model definitions with HuggingFace URLs+const WHISPER_MODELS = {+ tiny: {+ url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.bin",+ size: 75_000_000,+ },+ base: {+ url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin",+ size: 142_000_000,+ },+ small: {+ url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin",+ size: 466_000_000,+ },+ medium: {+ url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-medium.bin",+ size: 1_500_000_000,+ },+ large: {+ url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3.bin",+ size: 3_000_000_000,+ },+ turbo: {+ url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3-turbo.bin",+ size: 1_600_000_000,+ },+};+class WhisperManager {constructor() {- this.pythonCmd = null;- this.whisperInstalled = null;- this.isInitialized = false;- this.currentDownloadProcess = null;- this.pythonInstaller = new PythonInstaller();+ this.cachedBinaryPath = null;this.cachedFFmpegPath = null;- this.bundledPythonPath = null;- this.bundledPythonChecked = false;- this.venvReadyPromise = null;+ this.currentDownloadProcess = null;this.ffmpegAvailabilityCache = { result: null, expiresAt: 0 };+ this.isInitialized = false;+ }++ getModelsDir() {+ const homeDir = app?.getPath?.("home") || os.homedir();+ return path.join(homeDir, ".cache", "openwhispr", "whisper-models");}- sanitizeErrorMessage(message = "") {- if (!message) {- return "";+ validateModelName(modelName) {+ // Only allow known model names to prevent path traversal attacks+ const validModels = Object.keys(WHISPER_MODELS);+ if (!validModels.includes(modelName)) {+ throw new Error(+ `Invalid model name: ${modelName}. Valid models: ${validModels.join(", ")}`+ );}- return message.replace(/\x1B\[[0-9;]*m/g, "");+ return true;}- isTomlResolverError(message = "") {- const normalized = this.sanitizeErrorMessage(message).toLowerCase();- return normalized.includes("pyproject.toml") || normalized.includes("tomlerror");+ getModelPath(modelName) {+ this.validateModelName(modelName);+ return path.join(this.getModelsDir(), `ggml-${modelName}.bin`);}- formatWhisperInstallError(message = "") {- let formatted = this.sanitizeErrorMessage(message) || "Whisper installation failed.";- const lower = formatted.toLowerCase();+ getBundledBinaryPath() {+ const platform = process.platform;+ const arch = process.arch;+ const platformArch = `${platform}-${arch}`;- if (lower.includes("microsoft visual c++")) {- return "Microsoft Visual C++ build tools required. Install Visual Studio Build Tools.";- }+ // Binary naming matches download-whisper-cpp.js output: whisper-cpp-darwin-arm64, whisper-cpp-win32-x64.exe+ const platformBinaryName =+ platform === "win32" ? `whisper-cpp-${platformArch}.exe` : `whisper-cpp-${platformArch}`;+ const genericBinaryName = platform === "win32" ? "whisper-cpp.exe" : "whisper-cpp";- if (- lower.includes("externally-managed-environment") ||- lower.includes("externally managed environment") ||- lower.includes("pep 668") ||- lower.includes("--break-system-packages")- ) {- return "System Python is externally managed (PEP 668). OpenWhispr installs Whisper into an isolated environment by default. If you set OPENWHISPR_PYTHON, unset it or point it to a virtual environment, then try again.";- }+ const candidates = [];- if (lower.includes("no matching distribution")) {- return "Python version incompatible. Whisper requires a supported Python 3.x runtime.";+ // Production: check resources path+ if (process.resourcesPath) {+ candidates.push(+ path.join(process.resourcesPath, "bin", platformBinaryName),+ path.join(process.resourcesPath, "bin", genericBinaryName)+ );}- return formatted;- }+ // Development: check project resources+ candidates.push(+ path.join(__dirname, "..", "..", "resources", "bin", platformBinaryName),+ path.join(__dirname, "..", "..", "resources", "bin", genericBinaryName)+ );- getUserDataDir() {- try {- if (app && app.getPath) {- return app.getPath("userData");+ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) {+ return candidate;}- } catch (error) {- // Fall back to home directory}- return path.join(os.homedir(), ".openwhispr");- }-- getManagedPythonRoot() {- return path.join(this.getUserDataDir(), "python");- }- getVenvPath() {- return path.join(this.getManagedPythonRoot(), "venv");- }-- getVenvPythonPath() {- const venvPath = this.getVenvPath();- if (process.platform === "win32") {- return path.join(venvPath, "Scripts", "python.exe");- }- const python3Path = path.join(venvPath, "bin", "python3");- if (fs.existsSync(python3Path)) {- return python3Path;- }- return path.join(venvPath, "bin", "python");+ return null;}- getBundledPythonCandidates() {- const baseDirs = [];- if (process.resourcesPath) {- baseDirs.push(path.join(process.resourcesPath, "python"));- }- baseDirs.push(path.join(__dirname, "..", "..", "resources", "python"));+ async getSystemBinaryPath() {+ const binaryNames =+ process.platform === "win32"+ ? ["whisper.exe", "whisper-cpp.exe"]+ : ["whisper", "whisper-cpp", "main"];- const candidates = [];- const uniqueBaseDirs = Array.from(new Set(baseDirs));-- for (const baseDir of uniqueBaseDirs) {- if (!baseDir) {+ for (const name of binaryNames) {+ try {+ const checkCmd = process.platform === "win32" ? "where" : "which";+ const { output } = await runCommand(checkCmd, [name], { timeout: TIMEOUTS.QUICK_CHECK });+ const binaryPath = output.trim().split("\n")[0];+ if (binaryPath && fs.existsSync(binaryPath)) {+ return binaryPath;+ }+ } catch {continue;}- if (process.platform === "win32") {- candidates.push(- path.join(baseDir, "python.exe"),- path.join(baseDir, "python", "python.exe")- );- } else {- candidates.push(- path.join(baseDir, "bin", "python3"),- path.join(baseDir, "bin", "python"),- path.join(baseDir, "python3")- );- }}- return candidates;- }-- resolveBundledPython() {- if (this.bundledPythonChecked) {- return this.bundledPythonPath;- }+ // Check common installation paths+ const commonPaths =+ process.platform === "darwin"+ ? ["/opt/homebrew/bin/whisper", "/usr/local/bin/whisper"]+ : ["/usr/bin/whisper", "/usr/local/bin/whisper"];- this.bundledPythonChecked = true;- for (const candidate of this.getBundledPythonCandidates()) {- if (candidate && fs.existsSync(candidate)) {- this.bundledPythonPath = candidate;- return candidate;+ for (const p of commonPaths) {+ if (fs.existsSync(p)) {+ return p;}}- this.bundledPythonPath = null;return null;}- normalizePathForCompare(candidate) {- if (!candidate) {- return "";+ async getWhisperBinaryPath() {+ if (this.cachedBinaryPath && fs.existsSync(this.cachedBinaryPath)) {+ return this.cachedBinaryPath;}- const normalized = path.normalize(candidate);- return process.platform === "win32" ? normalized.toLowerCase() : normalized;- }-- getPythonSource(pythonPath) {- const normalizedPath = this.normalizePathForCompare(pythonPath);- // Check venv first (most common case when using managed environment)- const normalizedVenv = this.normalizePathForCompare(this.getVenvPath());- if (normalizedVenv && normalizedPath.startsWith(normalizedVenv)) {- return "venv";- }+ // Priority: bundled > system+ let binaryPath = this.getBundledBinaryPath();- // Check override before bundled (user preference takes priority)- if (process.env.OPENWHISPR_PYTHON) {- const normalizedOverride = this.normalizePathForCompare(process.env.OPENWHISPR_PYTHON);- if (normalizedOverride && normalizedPath === normalizedOverride) {- return "override";- }+ if (!binaryPath) {+ binaryPath = await this.getSystemBinaryPath();}- // Only check bundled if needed (avoids filesystem scan)- if (this.bundledPythonPath || !this.bundledPythonChecked) {- const bundled = this.resolveBundledPython();- if (bundled) {- const normalizedBundled = this.normalizePathForCompare(bundled);- if (normalizedBundled && normalizedPath === normalizedBundled) {- return "bundled";- }- }+ if (binaryPath) {+ this.cachedBinaryPath = binaryPath;+ debugLogger.log("Using whisper.cpp binary:", binaryPath);}- return "system";+ return binaryPath;}- async ensureManagedVenv() {- if (process.env.OPENWHISPR_PYTHON) {- return process.env.OPENWHISPR_PYTHON;- }-- if (this.venvReadyPromise) {- return this.venvReadyPromise;+ async initializeAtStartup() {+ try {+ await this.getWhisperBinaryPath();+ this.isInitialized = true;+ } catch (error) {+ debugLogger.log("whisper.cpp not available at startup:", error.message);+ this.isInitialized = true;}-- // Assign promise synchronously to prevent race conditions- const venvPath = this.getVenvPath();- const venvPython = this.getVenvPythonPath();-- this.venvReadyPromise = (async () => {- if (fs.existsSync(venvPython)) {- const version = await this.getPythonVersion(venvPython);- if (this.isPythonVersionSupported(version)) {- this.pythonCmd = venvPython;- return venvPython;- }-- try {- fs.rmSync(venvPath, { recursive: true, force: true });- } catch (error) {- debugLogger.log("Failed to remove outdated venv:", error.message);- }- }-- let basePython;- try {- basePython = await this.findPythonExecutable({ allowVenv: false });- } catch (error) {- throw new Error(- "Python 3.x not found. Install Python from Settings or set OPENWHISPR_PYTHON to a valid interpreter."- );- }-- fs.mkdirSync(this.getManagedPythonRoot(), { recursive: true });- try {- await runCommand(basePython, ["-m", "venv", venvPath], { timeout: TIMEOUTS.INSTALL });- } catch (error) {- const cleanMessage = this.sanitizeErrorMessage(error.message).toLowerCase();- if (cleanMessage.includes("no module named venv")) {- throw new Error(- "Python venv module missing. Install the venv package for your Python distribution and try again."- );- }- throw error;- }-- this.pythonCmd = venvPython;- return venvPython;- })().catch((error) => {- this.venvReadyPromise = null;- throw error;- });-- return this.venvReadyPromise;}- getWhisperScriptPath() {- // In production, the file is unpacked from ASAR- if (process.env.NODE_ENV === "development") {- return path.join(__dirname, "..", "..", "whisper_bridge.py");- } else {- // In production, use the unpacked path- return path.join(process.resourcesPath, "app.asar.unpacked", "whisper_bridge.py");+ async checkWhisperInstallation() {+ const binaryPath = await this.getWhisperBinaryPath();+ if (!binaryPath) {+ return { installed: false, working: false };}- }- async initializeAtStartup() {+ // Verify binary workstry {- await this.findPythonExecutable();- await this.checkWhisperInstallation();- this.isInitialized = true;+ await runCommand(binaryPath, ["--help"], { timeout: TIMEOUTS.QUICK_CHECK });+ return { installed: true, working: true, path: binaryPath };} catch (error) {- // Whisper not available at startup is not critical- this.isInitialized = true;+ return { installed: true, working: false, error: error.message };}}@@ -268,21 +191,26 @@ class WhisperManager {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 binaryPath = await this.getWhisperBinaryPath();+ if (!binaryPath) {+ throw new Error(+ "whisper.cpp not found. Please install it via Homebrew (brew install whisper-cpp) or ensure it is bundled with the app."+ );}const tempAudioPath = await this.createTempAudioFile(audioBlob);const model = options.model || "base";const language = options.language || null;+ const modelPath = this.getModelPath(model);++ // Check if model exists+ if (!fs.existsSync(modelPath)) {+ await this.cleanupTempFile(tempAudioPath);+ throw new Error(`Whisper model "${model}" not downloaded. Please download it from Settings.`);+ }try {- const result = await this.runWhisperProcess(tempAudioPath, model, language);+ const result = await this.runWhisperProcess(binaryPath, tempAudioPath, modelPath, language);return this.parseWhisperResult(result);} finally {await this.cleanupTempFile(tempAudioPath);@@ -295,7 +223,6 @@ class WhisperManager {const tempAudioPath = path.join(tempDir, filename);debugLogger.logAudioData("createTempAudioFile", audioBlob);- debugLogger.log("Creating temp file at:", tempAudioPath);let buffer;if (audioBlob instanceof ArrayBuffer) {@@ -307,331 +234,53 @@ 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);-- // Validate buffer before writingif (!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)+ // WAV header is 44 bytes minimum (RIFF + fmt + data chunk headers)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 correctlyconst stats = await fsPromises.stat(tempAudioPath);- const fileInfo = {+ debugLogger.logWhisperPipeline("Temp audio file created", {path: tempAudioPath,size: stats.size,- isFile: stats.isFile(),- 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 - 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;- }+ async runWhisperProcess(binaryPath, audioPath, modelPath, language) {+ const args = ["-m", modelPath, "-f", audioPath, "--output-json", "--no-prints"];- // 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;+ if (language && language !== "auto") {+ args.push("-l", language);}- }- async getFFmpegPath() {- if (this.cachedFFmpegPath) {- return this.cachedFFmpegPath;- }-- let ffmpegPath;+ debugLogger.logProcessStart(binaryPath, args, {});- try {- 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";- }-- 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);- } else if (process.env.NODE_ENV !== "development") {- const possiblePaths = [- ffmpegPath.replace(/app\.asar([/\\])/, "app.asar.unpacked$1"),- ffmpegPath.replace(/app\.asar/g, "app.asar.unpacked"),- ffmpegPath.replace(/.*app\.asar/, path.join(__dirname, "..", "..", "app.asar.unpacked")),- process.resourcesPath- ? path.join(- process.resourcesPath,- "app.asar.unpacked",- "node_modules",- "ffmpeg-static",- process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"- )- : null,- 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)) {- continue;- }- // Validate on non-Windows platforms- if (process.platform !== "win32") {- try {- fs.accessSync(normalizedPath, fs.constants.X_OK);- } catch (e) {- continue;- }- }- ffmpegPath = normalizedPath;- debugLogger.log("FFmpeg found at:", normalizedPath);- break;- }- }-- if (!ffmpegPath || !fs.existsSync(ffmpegPath)) {- 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);- ffmpegPath = candidate;- break;- } catch (error) {- continue;- }- }-- if (!ffmpegPath) {- debugLogger.error("No FFmpeg found (bundled or system)");- return null;- }- }-- this.cachedFFmpegPath = ffmpegPath;- return ffmpegPath;- }-- 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();-- 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) => {- const ffmpegPath = await this.getFFmpegPath();- if (!ffmpegPath) {- reject(- new Error("FFmpeg not found. Please ensure FFmpeg is installed or bundled correctly.")- );- return;- }-- let effectiveFfmpegPath = ffmpegPath;- if (- effectiveFfmpegPath.includes("app.asar") &&- !effectiveFfmpegPath.includes("app.asar.unpacked")- ) {- const unpackedPath = effectiveFfmpegPath.replace("app.asar", "app.asar.unpacked");- if (fs.existsSync(unpackedPath)) {- effectiveFfmpegPath = unpackedPath;- debugLogger.log("Using unpacked FFmpeg path:", unpackedPath);- }- }-- const absoluteFFmpegPath = path.resolve(effectiveFfmpegPath);- const enhancedEnv = {- ...process.env,- 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 path- if (ffmpegPath) {- const ffmpegDir = path.dirname(absoluteFFmpegPath);- const currentPath = enhancedEnv.PATH || "";- const pathSeparator = process.platform === "win32" ? ";" : ":";-- if (!currentPath.includes(ffmpegDir)) {- enhancedEnv.PATH = `${ffmpegDir}${pathSeparator}${currentPath}`;- }- }-- // 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");- }- }-- debugLogger.logProcessStart(pythonCmd, args, { env: enhancedEnv });-- const whisperProcess = spawn(pythonCmd, args, {+ return new Promise((resolve, reject) => {+ const whisperProcess = spawn(binaryPath, args, {stdio: ["ignore", "pipe", "pipe"],windowsHide: true,- env: enhancedEnv,});let stdout = "";let stderr = "";let isResolved = false;- // Set timeout for longer recordingsconst timeout = setTimeout(() => {if (!isResolved) {killProcess(whisperProcess, "SIGTERM");- reject(new Error("Whisper transcription timed out (20 minutes)"));+ reject(new Error("Whisper transcription timed out"));}}, TIMEOUTS.TRANSCRIPTION);@@ -641,9 +290,7 @@ class WhisperManager {});whisperProcess.stderr.on("data", (data) => {- const stderrText = data.toString();- stderr += stderrText;-+ stderr += data.toString();debugLogger.logProcessOutput("Whisper", "stderr", data);});@@ -659,21 +306,9 @@ class WhisperManager {});if (code === 0) {- debugLogger.log("Transcription successful");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.";- }-- reject(new Error(errorMessage));+ reject(new Error(`Whisper transcription failed (code ${code}): ${stderr}`));}});@@ -681,23 +316,6 @@ class WhisperManager {if (isResolved) return;isResolved = true;clearTimeout(timeout);-- if (error.code === "ENOENT") {- const platformHelp =- process.platform === "win32"- ? 'Install Python 3.11+ from python.org with the "Install launcher" option, or set OPENWHISPR_PYTHON to the full path (for example C:\\\\Python312\\\\python.exe).'- : "Install Python 3.11+ (for example `brew install [email protected]`) or set OPENWHISPR_PYTHON to the interpreter you want OpenWhispr to use.";- const fallbackHelp =- "You can also disable Local Whisper or enable the OpenAI fallback in Settings to continue using cloud transcription.";- const message = [- "Local Whisper could not start because Python was not found on this system.",- platformHelp,- fallbackHelp,- ].join(" ");- reject(new Error(message));- return;- }-reject(new Error(`Whisper process error: ${error.message}`));});});@@ -705,32 +323,39 @@ class WhisperManager {parseWhisperResult(stdout) {debugLogger.logWhisperPipeline("Parsing result", { stdoutLength: stdout.length });+try {- // Clean stdout by removing any non-JSON content- const lines = stdout.split("\n").filter((line) => line.trim());- let jsonLine = "";-- // Find the line that looks like JSON (starts with { and ends with })- for (const line of lines) {- const trimmed = line.trim();- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {- jsonLine = trimmed;- break;+ // whisper.cpp outputs JSON with transcription array+ const result = JSON.parse(stdout);++ // Handle whisper.cpp JSON format+ if (result.transcription && Array.isArray(result.transcription)) {+ const text = result.transcription+ .map((seg) => seg.text)+ .join("")+ .trim();+ if (!text) {+ return { success: false, message: "No audio detected" };}+ return { success: true, text };}- if (!jsonLine) {- throw new Error("No JSON output found in Whisper response");+ // Fallback for simple text output+ if (result.text) {+ const text = result.text.trim();+ if (!text) {+ return { success: false, message: "No audio detected" };+ }+ return { success: true, text };}- 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() };+ return { success: false, message: "No audio detected" };} catch (parseError) {- debugLogger.error("Failed to parse Whisper output");+ // Try parsing as plain text (non-JSON output)+ const text = stdout.trim();+ if (text) {+ return { success: true, text };+ }throw new Error(`Failed to parse Whisper output: ${parseError.message}`);}}@@ -738,789 +363,327 @@ class WhisperManager {async cleanupTempFile(tempAudioPath) {try {await fsPromises.unlink(tempAudioPath);- } catch (cleanupError) {+ } catch {// Temp file cleanup error is not critical}}- async findPythonExecutable(options = {}) {- const { allowVenv = true, allowBundled = true, allowOverride = true } = options;-- if (this.pythonCmd) {- const cachedSource = this.getPythonSource(this.pythonCmd);- const cachedExists = !path.isAbsolute(this.pythonCmd) || fs.existsSync(this.pythonCmd);- if (- cachedExists &&- (cachedSource !== "venv" || allowVenv) &&- (cachedSource !== "bundled" || allowBundled) &&- (cachedSource !== "override" || allowOverride)- ) {- return this.pythonCmd;- }- this.pythonCmd = null;- }-- const candidateSet = new Set();- const addCandidate = (candidate) => {- if (!candidate || typeof candidate !== "string") {- return;- }- const sanitized = candidate.trim().replace(/^["']|["']$/g, "");- if (sanitized.length === 0) {- return;- }- candidateSet.add(sanitized);- };+ // Model management methods+ async downloadWhisperModel(modelName, progressCallback = null) {+ this.validateModelName(modelName);+ const modelConfig = WHISPER_MODELS[modelName];- if (allowOverride && process.env.OPENWHISPR_PYTHON) {- addCandidate(process.env.OPENWHISPR_PYTHON);- }+ const modelPath = this.getModelPath(modelName);+ const modelsDir = this.getModelsDir();- if (allowVenv) {- addCandidate(this.getVenvPythonPath());- }+ // Create models directory+ await fsPromises.mkdir(modelsDir, { recursive: true });- if (allowBundled) {- const bundledPython = this.resolveBundledPython();- if (bundledPython) {- addCandidate(bundledPython);- }+ // Check if already downloaded+ if (fs.existsSync(modelPath)) {+ const stats = await fsPromises.stat(modelPath);+ return {+ model: modelName,+ downloaded: true,+ path: modelPath,+ size_bytes: stats.size,+ size_mb: Math.round(stats.size / (1024 * 1024)),+ success: true,+ };}- if (process.platform === "win32") {- // Windows: Get registry-based candidates first (most reliable)- const registryCandidates = await this.getWindowsRegistryPython();- registryCandidates.forEach(addCandidate);+ const tempPath = `${modelPath}.tmp`;- // Then add filesystem candidates- this.getWindowsPythonCandidates().forEach(addCandidate);- }+ // Track active download for cancellation+ let activeRequest = null;+ let activeFile = null;+ let isCancelled = false;- const commonCandidates = [- "python3.12",- "python3.11",- "python3.10",- "python3",- "python",- "/usr/bin/python3.12",- "/usr/bin/python3.11",- "/usr/bin/python3.10",- "/usr/bin/python3",- "/usr/local/bin/python3.12",- "/usr/local/bin/python3.11",- "/usr/local/bin/python3.10",- "/usr/local/bin/python3",- "/opt/homebrew/bin/python3.12",- "/opt/homebrew/bin/python3.11",- "/opt/homebrew/bin/python3.10",- "/opt/homebrew/bin/python3",- "/usr/bin/python",- "/usr/local/bin/python",- ];- commonCandidates.forEach(addCandidate);-- for (const pythonPath of candidateSet) {- // 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;+ const cleanup = () => {+ if (activeRequest) {+ activeRequest.destroy();+ activeRequest = null;}-- try {- const version = await this.getPythonVersion(resolvedPath);- if (this.isPythonVersionSupported(version)) {- 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;+ if (activeFile) {+ activeFile.close();+ activeFile = null;}- }+ fs.unlink(tempPath, () => {});+ };- throw new Error(- 'Python 3.x not found. Click "Install Python" in Settings or set OPENWHISPR_PYTHON to a valid interpreter path.'- );- }+ // Store cancellation function+ this.currentDownloadProcess = {+ abort: () => {+ isCancelled = true;+ cleanup();+ },+ };- async getWindowsRegistryPython() {- if (process.platform !== "win32") {- return [];- }+ return new Promise((resolve, reject) => {+ const downloadWithRedirect = (url, redirectCount = 0) => {+ if (isCancelled) {+ reject(new Error("Download cancelled by user"));+ return;+ }- const candidates = [];- debugLogger.logWindowsPythonSearch?.("Starting registry search", { method: "registry" });+ // Prevent infinite redirects+ if (redirectCount > 5) {+ cleanup();+ reject(new Error("Too many redirects"));+ return;+ }- 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 { output } = await runCommand("reg", ["query", registryKey], {- timeout: TIMEOUTS.QUICK_CHECK,- });+ activeRequest = https.get(url, (response) => {+ if (isCancelled) {+ cleanup();+ reject(new Error("Download cancelled by user"));+ return;+ }- // Parse version folders (e.g., "3.11", "3.12")- const versionMatches = output.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 { output: 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}`);- }+ // Handle redirects+ if (response.statusCode === 302 || response.statusCode === 301) {+ const redirectUrl = response.headers.location;+ if (!redirectUrl) {+ cleanup();+ reject(new Error("Redirect without location header"));+ return;}+ downloadWithRedirect(redirectUrl, redirectCount + 1);+ return;}- } 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,- });+ if (response.statusCode !== 200) {+ cleanup();+ reject(new Error(`Failed to download model: HTTP ${response.statusCode}`));+ return;+ }- return candidates;- }+ const totalSize = parseInt(response.headers["content-length"], 10) || modelConfig.size;+ let downloadedSize = 0;- async resolveWindowsCommand(command) {- if (process.platform !== "win32") {- return command;- }-- try {- // Use 'where' command to find executable in PATH- const { output } = await runCommand("where", [command], {- timeout: TIMEOUTS.QUICK_CHECK,- });+ activeFile = fs.createWriteStream(tempPath);- // 'where' returns multiple paths, take the first one- const paths = output.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- }+ response.on("data", (chunk) => {+ if (isCancelled) {+ cleanup();+ return;+ }- return null;- }+ downloadedSize += chunk.length;+ const percentage = Math.round((downloadedSize / totalSize) * 100);- getWindowsPythonCandidates() {- const candidates = [];- const versionSuffixes = ["313", "312", "311", "310", "39", "38"];-- const systemDrive = process.env.SystemDrive || "C:";- const windowsDir = process.env.WINDIR || path.join(systemDrive, "Windows");-- candidates.push("py");- candidates.push("py.exe");- candidates.push("python3");- candidates.push("python3.exe");- candidates.push("python");- candidates.push("python.exe");- candidates.push(path.join(windowsDir, "py.exe"));-- const baseDirs = [];- if (process.env.LOCALAPPDATA) {- baseDirs.push(path.join(process.env.LOCALAPPDATA, "Programs", "Python"));- const windowsApps = path.join(process.env.LOCALAPPDATA, "Microsoft", "WindowsApps");- candidates.push(path.join(windowsApps, "python.exe"));- candidates.push(path.join(windowsApps, "python3.exe"));- }- if (process.env.ProgramFiles) {- baseDirs.push(process.env.ProgramFiles);- }- if (process.env["ProgramFiles(x86)"]) {- baseDirs.push(process.env["ProgramFiles(x86)"]);- }- baseDirs.push(systemDrive);+ if (progressCallback) {+ progressCallback({+ type: "progress",+ model: modelName,+ downloaded_bytes: downloadedSize,+ total_bytes: totalSize,+ percentage,+ });+ }+ });- for (const baseDir of baseDirs) {- if (!baseDir) {- continue;- }+ response.pipe(activeFile);- for (const suffix of versionSuffixes) {- const folderName = `Python${suffix}`;- candidates.push(path.join(baseDir, folderName, "python.exe"));- }- }+ activeFile.on("finish", async () => {+ if (isCancelled) {+ cleanup();+ reject(new Error("Download cancelled by user"));+ return;+ }- return candidates;- }+ activeFile.close();+ activeFile = null;+ this.currentDownloadProcess = null;- async installPython(progressCallback = null) {- try {- // Clear cached Python command since we're installing new one- this.pythonCmd = null;+ // Rename temp to final+ try {+ await fsPromises.rename(tempPath, modelPath);+ } catch {+ // Cross-device move fallback+ await fsPromises.copyFile(tempPath, modelPath);+ await fsPromises.unlink(tempPath);+ }- // If OPENWHISPR_PYTHON is set, skip installation and use that- if (process.env.OPENWHISPR_PYTHON) {- if (progressCallback) {- progressCallback({ stage: "Using custom Python override...", percentage: 50 });- }- const version = await this.getPythonVersion(process.env.OPENWHISPR_PYTHON);- if (!this.isPythonVersionSupported(version)) {- throw new Error(- `OPENWHISPR_PYTHON points to an invalid or unsupported Python. ` +- `Ensure it exists and is Python 3.x, or unset the variable.`- );- }- if (progressCallback) {- progressCallback({ stage: "Python ready", percentage: 100 });- }- return { success: true, method: "override" };- }+ const stats = await fsPromises.stat(modelPath);- const bundledPython = this.resolveBundledPython();- if (bundledPython) {- if (progressCallback) {- progressCallback({ stage: "Using bundled Python runtime...", percentage: 40 });- }+ if (progressCallback) {+ progressCallback({+ type: "complete",+ model: modelName,+ percentage: 100,+ });+ }- await this.ensureManagedVenv();+ resolve({+ model: modelName,+ downloaded: true,+ path: modelPath,+ size_bytes: stats.size,+ size_mb: Math.round(stats.size / (1024 * 1024)),+ success: true,+ });+ });- if (progressCallback) {- progressCallback({ stage: "Python ready", percentage: 100 });- }+ activeFile.on("error", (err) => {+ cleanup();+ reject(err);+ });- return { success: true, method: "bundled" };- }+ response.on("error", (err) => {+ cleanup();+ reject(err);+ });+ });- const result = await this.pythonInstaller.installPython(progressCallback);+ activeRequest.on("error", (err) => {+ cleanup();+ reject(err);+ });- // On Windows, the installer returns the exact path to python.exe- // Use it directly since PATH environment won't be updated in running process- if (process.platform === "win32" && result.pythonPath) {- debugLogger.log(`Using freshly installed Python at: ${result.pythonPath}`);- this.pythonCmd = result.pythonPath;- }+ // Request timeout (10 minutes for large models)+ activeRequest.setTimeout(600000, () => {+ cleanup();+ reject(new Error("Download request timed out"));+ });+ };- // After installation, prepare isolated environment- await this.ensureManagedVenv();+ downloadWithRedirect(modelConfig.url);+ });+ }- return result;- } catch (error) {- console.error("Python installation failed:", error);- throw error;+ async cancelDownload() {+ if (this.currentDownloadProcess) {+ this.currentDownloadProcess.abort();+ this.currentDownloadProcess = null;+ return { success: true, message: "Download cancelled" };}+ return { success: false, error: "No active download to cancel" };}- async checkPythonInstallation() {- try {- const pythonPath = await this.findPythonExecutable();- const version = await this.getPythonVersion(pythonPath);- const normalizedVersion = version- ? parseFloat(`${version.major}.${version.minor}`)- : undefined;+ async checkModelStatus(modelName) {+ const modelPath = this.getModelPath(modelName);+ if (fs.existsSync(modelPath)) {+ const stats = await fsPromises.stat(modelPath);return {- installed: !!version,- command: pythonPath,- version: normalizedVersion,- source: this.getPythonSource(pythonPath),+ model: modelName,+ downloaded: true,+ path: modelPath,+ size_bytes: stats.size,+ size_mb: Math.round(stats.size / (1024 * 1024)),+ success: true,};- } catch (error) {- return { installed: false };}- }-- async getPythonVersion(pythonPath) {- return new Promise((resolve) => {- // Use shell: false on Windows to ensure exact path is used- const spawnOptions = process.platform === "win32" ? { windowsHide: true, shell: false } : {};-- let testProcess;- let resolved = false;-- // Timeout to prevent hanging on slow/stuck Python executables (common on Windows)- const timeout = setTimeout(() => {- if (!resolved) {- resolved = true;- debugLogger.log(`Python version check timed out for ${pythonPath}`);- if (testProcess && !testProcess.killed) {- killProcess(testProcess, "SIGTERM");- }- resolve(null);- }- }, TIMEOUTS.QUICK_CHECK);-- try {- testProcess = spawn(pythonPath, ["--version"], spawnOptions);- } catch (error) {- clearTimeout(timeout);- debugLogger.log(`Failed to spawn Python process for ${pythonPath}: ${error.message}`);- resolve(null);- return;- }-- let output = "";- testProcess.stdout.on("data", (data) => (output += data));- testProcess.stderr.on("data", (data) => (output += data));-- testProcess.on("close", (code) => {- if (resolved) return;- resolved = true;- clearTimeout(timeout);-- if (code === 0) {- const match = output.match(/Python (\d+)\.(\d+)/i);- resolve(match ? { major: +match[1], minor: +match[2] } : null);- } else {- resolve(null);- }- });-- testProcess.on("error", (error) => {- if (resolved) return;- resolved = true;- clearTimeout(timeout);- debugLogger.log(`Python version check error for ${pythonPath}: ${error.message}`);- resolve(null);- });- });+ return { model: modelName, downloaded: false, success: true };}- isPythonVersionSupported(version) {- // Accept any Python 3.x version- return version && version.major === 3;- }+ async listWhisperModels() {+ const models = Object.keys(WHISPER_MODELS);+ const modelInfo = [];- async checkWhisperInstallation() {- // Return cached result if available- if (this.whisperInstalled !== null) {- return this.whisperInstalled;+ for (const model of models) {+ const status = await this.checkModelStatus(model);+ modelInfo.push(status);}- try {- const pythonCmd = await this.findPythonExecutable();-- const result = await new Promise((resolve) => {- const checkProcess = spawn(pythonCmd, ["-c", 'import whisper; print("OK")']);-- let output = "";- checkProcess.stdout.on("data", (data) => {- output += data.toString();- });-- checkProcess.on("close", (code) => {- if (code === 0 && output.includes("OK")) {- resolve({ installed: true, working: true });- } else {- resolve({ installed: false, working: false });- }- });-- checkProcess.on("error", (error) => {- resolve({ installed: false, working: false, error: error.message });- });- });-- this.whisperInstalled = result; // Cache the result- return result;- } catch (error) {- const errorResult = {- installed: false,- working: false,- error: error.message,- };- this.whisperInstalled = errorResult;- return errorResult;- }+ return {+ models: modelInfo,+ cache_dir: this.getModelsDir(),+ success: true,+ };}- async checkFFmpegAvailability() {- debugLogger.logWhisperPipeline("checkFFmpegAvailability - start", {});-- try {- const now = Date.now();- if (- this.ffmpegAvailabilityCache &&- now < this.ffmpegAvailabilityCache.expiresAt &&- this.ffmpegAvailabilityCache.result !== null- ) {- return this.ffmpegAvailabilityCache.result;- }-- const pythonCmd = await this.findPythonExecutable();- const whisperScriptPath = this.getWhisperScriptPath();- const ffmpegPath = await this.getFFmpegPath();- if (!ffmpegPath) {- debugLogger.log("FFmpeg not found by resolver");- const result = {- available: false,- error: "FFmpeg not found",- };- this.ffmpegAvailabilityCache = {- result,- expiresAt: Date.now() + CACHE_TTL_MS,- };- return result;- }-- debugLogger.log("FFmpeg resolved for availability check:", ffmpegPath);-- const result = await new Promise((resolve) => {- 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 = "";-- checkProcess.stdout.on("data", (data) => {- output += data.toString();- });-- checkProcess.stderr.on("data", (data) => {- stderr += data.toString();- });-- 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",- });- }- });-- checkProcess.on("error", (error) => {- resolve({ available: false, error: error.message });- });- });+ async deleteWhisperModel(modelName) {+ const modelPath = this.getModelPath(modelName);- this.ffmpegAvailabilityCache = {- result,- expiresAt: Date.now() + CACHE_TTL_MS,- };- return result;- } catch (error) {- const result = { available: false, error: error.message };- this.ffmpegAvailabilityCache = {- result,- expiresAt: Date.now() + CACHE_TTL_MS,+ if (fs.existsSync(modelPath)) {+ const stats = await fsPromises.stat(modelPath);+ await fsPromises.unlink(modelPath);+ return {+ model: modelName,+ deleted: true,+ freed_bytes: stats.size,+ freed_mb: Math.round(stats.size / (1024 * 1024)),+ success: true,};- return result;}- }- upgradePip(pythonCmd) {- return runCommand(pythonCmd, ["-m", "pip", "install", "--upgrade", "pip"], {- timeout: TIMEOUTS.PIP_UPGRADE,- });+ return { model: modelName, deleted: false, error: "Model not found", success: false };}- async installWhisper() {- let pythonCmd;-- if (process.env.OPENWHISPR_PYTHON) {- // Validate the override path before using it- const overridePath = process.env.OPENWHISPR_PYTHON;- const version = await this.getPythonVersion(overridePath);- if (!this.isPythonVersionSupported(version)) {- throw new Error(- `OPENWHISPR_PYTHON points to an invalid or unsupported Python: ${overridePath}. ` +- `Ensure it exists and is Python 3.x, or unset the variable to use the managed environment.`- );- }- pythonCmd = overridePath;- } else {- console.log("Preparing isolated Python environment...");- pythonCmd = await this.ensureManagedVenv();+ // FFmpeg methods (still needed for audio format conversion)+ async getFFmpegPath() {+ if (this.cachedFFmpegPath) {+ return this.cachedFFmpegPath;}- // Upgrade pip inside the isolated environment to avoid resolver issues+ let ffmpegPath;+try {- await this.upgradePip(pythonCmd);- } catch (error) {- const cleanUpgradeError = this.sanitizeErrorMessage(error.message);- debugLogger.log("Pip upgrade failed in managed environment:", cleanUpgradeError);- }+ ffmpegPath = require("ffmpeg-static");+ ffmpegPath = path.normalize(ffmpegPath);- const buildInstallArgs = ({ legacy = false } = {}) => {- const args = ["-m", "pip", "install"];- if (legacy) {- args.push("--use-deprecated=legacy-resolver");+ if (process.platform === "win32" && !ffmpegPath.endsWith(".exe")) {+ ffmpegPath += ".exe";}- args.push("-U", "openai-whisper");- return args;- };- try {- const result = await runCommand(pythonCmd, buildInstallArgs(), {- timeout: TIMEOUTS.DOWNLOAD,- });- this.whisperInstalled = null;- return result;- } catch (error) {- const cleanMessage = this.sanitizeErrorMessage(error.message);-- if (this.isTomlResolverError(cleanMessage)) {- try {- const result = await runCommand(pythonCmd, buildInstallArgs({ legacy: true }), {- timeout: TIMEOUTS.DOWNLOAD,- });- this.whisperInstalled = null;- return result;- } catch (legacyError) {- const legacyMessage = this.sanitizeErrorMessage(legacyError.message);- throw new Error(this.formatWhisperInstallError(legacyMessage));+ if (fs.existsSync(ffmpegPath)) {+ if (process.platform !== "win32") {+ fs.accessSync(ffmpegPath, fs.constants.X_OK);}+ this.cachedFFmpegPath = ffmpegPath;+ return ffmpegPath;}- throw new Error(this.formatWhisperInstallError(cleanMessage));+ // Try unpacked ASAR path+ if (process.env.NODE_ENV !== "development") {+ const unpackedPath = ffmpegPath.replace(/app\.asar([/\\])/, "app.asar.unpacked$1");+ if (fs.existsSync(unpackedPath)) {+ this.cachedFFmpegPath = unpackedPath;+ return unpackedPath;+ }+ }+ } catch {+ // Bundled FFmpeg not available}- }-- async downloadWhisperModel(modelName, progressCallback = null) {- try {- const pythonCmd = await this.findPythonExecutable();- const whisperScriptPath = this.getWhisperScriptPath();-- const args = [whisperScriptPath, "--mode", "download", "--model", modelName];-- return new Promise((resolve, reject) => {- const downloadProcess = spawn(pythonCmd, args);- this.currentDownloadProcess = downloadProcess; // Store for potential cancellation-- let stdout = "";- let stderr = "";-- downloadProcess.stdout.on("data", (data) => {- stdout += data.toString();- });- downloadProcess.stderr.on("data", (data) => {- const output = data.toString();- stderr += output;-- // Parse progress updates from stderr- const lines = output.split("\n");- for (const line of lines) {- const trimmed = line.trim();- if (trimmed.startsWith("PROGRESS:")) {- try {- const progressData = JSON.parse(trimmed.substring(9));- if (progressCallback) {- progressCallback({- type: "progress",- model: modelName,- ...progressData,- });- }- } catch (parseError) {- // Ignore parsing errors for progress data- }- }- }- });-- const timeout = setTimeout(() => {- killProcess(downloadProcess, "SIGTERM");- setTimeout(() => {- if (!downloadProcess.killed) {- killProcess(downloadProcess, "SIGKILL");- }- }, 5000);- reject(new Error("Model download timed out (10 minutes)"));- }, TIMEOUTS.DOWNLOAD);-- downloadProcess.on("close", (code) => {- clearTimeout(timeout);- this.currentDownloadProcess = null;-- if (code === 0) {- try {- const result = JSON.parse(stdout);- resolve(result);- } catch (parseError) {- console.error("Failed to parse download result:", parseError);- reject(new Error(`Failed to parse download result: ${parseError.message}`));- }- } else {- // Handle cancellation cases (SIGTERM, SIGKILL, or null exit codes)- if (code === 143 || code === 137 || code === null) {- reject(new Error("Download interrupted by user"));- } else {- console.error("Model download failed with code:", code);- reject(new Error(`Model download failed (exit code ${code})`));- }- }- });-- downloadProcess.on("error", (error) => {- clearTimeout(timeout);- this.currentDownloadProcess = null;- console.error("Model download process error:", error);- reject(new Error(`Model download process error: ${error.message}`));- });- });- } catch (error) {- console.error("Model download error:", error);- throw error;- }- }+ // Try system FFmpeg+ const systemCandidates =+ process.platform === "darwin"+ ? ["ffmpeg", "/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"]+ : ["ffmpeg", "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg"];- async cancelDownload() {- if (this.currentDownloadProcess) {+ for (const candidate of systemCandidates) {try {- killProcess(this.currentDownloadProcess, "SIGTERM");- setTimeout(() => {- if (this.currentDownloadProcess && !this.currentDownloadProcess.killed) {- killProcess(this.currentDownloadProcess, "SIGKILL");- }- }, 3000);- return { success: true, message: "Download cancelled" };- } catch (error) {- console.error("Error cancelling download:", error);- return { success: false, error: error.message };+ await runCommand(candidate, ["-version"], { timeout: TIMEOUTS.QUICK_CHECK });+ this.cachedFFmpegPath = candidate;+ return candidate;+ } catch {+ continue;}- } else {- return { success: false, error: "No active download to cancel" };}- }- /**- * Helper method to run whisper_bridge.py commands and parse JSON output.- * Reduces code duplication across model management methods.- */- async runWhisperBridgeCommand(args, operationName) {- const pythonCmd = await this.findPythonExecutable();- const whisperScriptPath = this.getWhisperScriptPath();- const fullArgs = [whisperScriptPath, ...args];-- return new Promise((resolve, reject) => {- const childProcess = spawn(pythonCmd, fullArgs);- let stdout = "";- let stderr = "";-- childProcess.stdout.on("data", (data) => {- stdout += data.toString();- });-- childProcess.stderr.on("data", (data) => {- stderr += data.toString();- });-- childProcess.on("close", (code) => {- if (code === 0) {- try {- resolve(JSON.parse(stdout));- } catch (parseError) {- console.error(`Failed to parse ${operationName} result:`, parseError);- reject(new Error(`Failed to parse ${operationName} result: ${parseError.message}`));- }- } else {- console.error(`${operationName} failed with code:`, code);- reject(new Error(`${operationName} failed (code ${code}): ${stderr}`));- }- });-- childProcess.on("error", (error) => {- reject(new Error(`${operationName} error: ${error.message}`));- });- });+ return null;}- async checkModelStatus(modelName) {- return this.runWhisperBridgeCommand(- ["--mode", "check", "--model", modelName],- "Model status check"- );- }+ async checkFFmpegAvailability() {+ const now = Date.now();+ if (+ this.ffmpegAvailabilityCache.result !== null &&+ now < this.ffmpegAvailabilityCache.expiresAt+ ) {+ return this.ffmpegAvailabilityCache.result;+ }- async listWhisperModels() {- return this.runWhisperBridgeCommand(["--mode", "list"], "Model list");- }+ const ffmpegPath = await this.getFFmpegPath();+ const result = ffmpegPath+ ? { available: true, path: ffmpegPath }+ : { available: false, error: "FFmpeg not found" };- async deleteWhisperModel(modelName) {- return this.runWhisperBridgeCommand(["--mode", "delete", "--model", modelName], "Model delete");+ this.ffmpegAvailabilityCache = { result, expiresAt: now + CACHE_TTL_MS };+ return result;}}diff --git a/src/hooks/usePython.ts b/src/hooks/usePython.tsdeleted file mode 100644index f92b790da..000000000--- a/src/hooks/usePython.ts+++ /dev/null@@ -1,172 +0,0 @@-import { useState, useEffect, useCallback, useRef } from "react";-import logger from "../utils/logger";--interface PythonInstallation {- installed: boolean;- command?: string;- version?: number;-}--interface PythonInstallProgress {- stage: string;- percentage: number;-}--interface ShowAlertDialog {- (options: { title: string; description: string }): void;-}--const ERROR_MESSAGES: Record<string, string> = {- "Permission denied": "Please run the application as administrator and try again.",- "access is denied": "Please run the application as administrator and try again.",- Network: "Please check your internet connection and try again.",- "No supported package manager": "Please install Python manually from python.org",- "not found in PATH": "Python installed but not found in PATH. Please restart the application.",-};--function getPythonInstallErrorMessage(error: Error): string {- const errorMessage = error.message || "";-- for (const [key, message] of Object.entries(ERROR_MESSAGES)) {- if (errorMessage.includes(key)) {- return message;- }- }-- return `Python installation failed: ${errorMessage}`;-}--export function usePython(showAlertDialog: ShowAlertDialog) {- const [pythonInstalled, setPythonInstalled] = useState<boolean>(false);- const [installingPython, setInstallingPython] = useState<boolean>(false);- const [installProgress, setInstallProgress] = useState<string>("");- const [pythonInfo, setPythonInfo] = useState<PythonInstallation | null>(null);- const [isChecking, setIsChecking] = useState<boolean>(false);- const [hasChecked, setHasChecked] = useState<boolean>(false);-- const isCheckingRef = useRef(false);- const hasInitialCheckRef = useRef(false);- const pythonInfoRef = useRef<PythonInstallation | null>(null);-- // Keep ref in sync with state for use in callbacks without re-creating them- pythonInfoRef.current = pythonInfo;-- const checkPythonInstallation = useCallback(async () => {- // Prevent concurrent checks- if (isCheckingRef.current) {- return pythonInfoRef.current;- }-- try {- isCheckingRef.current = true;- setIsChecking(true);-- if (!window.electronAPI) {- return { installed: false };- }-- const result = await window.electronAPI.checkPythonInstallation();-- if (result) {- setPythonInstalled(result.installed);- setPythonInfo(result);- return result;- }- return { installed: false };- } catch (error) {- logger.error("Python installation check failed", error, "usePython");- setPythonInstalled(false);- return { installed: false };- } finally {- isCheckingRef.current = false;- setIsChecking(false);- setHasChecked(true);- }- }, []); // No dependencies - uses refs to avoid re-creating callback-- const installPython = useCallback(async () => {- if (!window.electronAPI) {- showAlertDialog({- title: "Installation Error",- description: "Unable to communicate with the main process. Please restart the application.",- });- return;- }-- let progressListener: ((event: any, data: PythonInstallProgress) => void) | null = null;- let disposeProgress: (() => void) | void;-- try {- setInstallingPython(true);- setInstallProgress("Starting Python installation...");-- progressListener = (_event: any, data: any) => {- if (data?.type === "progress" && data?.stage && data?.percentage !== undefined) {- setInstallProgress(`${data.stage} (${data.percentage}%)`);- }- };-- // Listen for progress updates- if (window.electronAPI.onPythonInstallProgress) {- disposeProgress = window.electronAPI.onPythonInstallProgress(progressListener);- }-- const result = await window.electronAPI.installPython();-- if (result?.success) {- setPythonInstalled(true);- setInstallProgress("Python installed successfully!");-- // Re-check installation to get updated info- await checkPythonInstallation();-- showAlertDialog({- title: "Python Installed",- description: `Python has been installed successfully using ${result.method}!`,- });- }-- return result;- } catch (error: any) {- const errorMessage = getPythonInstallErrorMessage(error);-- showAlertDialog({- title: "Installation Failed",- description: errorMessage,- });-- throw error;- } finally {- setInstallingPython(false);- // Clean up the listener- disposeProgress?.();- }- }, [showAlertDialog, checkPythonInstallation]);-- // Check Python installation on mount with a small delay to ensure preload is ready- // Only runs once - uses ref to prevent re-triggering- useEffect(() => {- if (hasInitialCheckRef.current) {- return;- }- hasInitialCheckRef.current = true;-- // In development, there might be a race condition where React loads before preload- const timer = setTimeout(() => {- checkPythonInstallation();- }, 100); // Small delay to ensure preload script is ready-- return () => clearTimeout(timer);- }, [checkPythonInstallation]);-- return {- pythonInstalled,- installingPython,- installProgress,- pythonInfo,- installPython,- checkPythonInstallation,- isChecking,- hasChecked,- };-}diff --git a/src/hooks/useWhisper.ts b/src/hooks/useWhisper.tsindex 78e039e2b..9fc764f56 100644--- a/src/hooks/useWhisper.ts+++ b/src/hooks/useWhisper.ts@@ -1,29 +1,15 @@import { useState, useCallback, useEffect } from "react";-import { WhisperCheckResult, WhisperInstallResult } from "../types/electron";+import { WhisperCheckResult } from "../types/electron";export interface UseWhisperReturn {- // StatewhisperInstalled: boolean;checkingWhisper: boolean;- installingWhisper: boolean;- installProgress: string;-checkWhisperInstallation: () => Promise<void>;- installWhisper: () => Promise<void>;- setupProgressListener: () => (() => void) | void;-}--export interface UseWhisperProps {- showAlertDialog: (dialog: { title: string; description?: string }) => void;}-export const useWhisper = (- showAlertDialog?: UseWhisperProps["showAlertDialog"]-): UseWhisperReturn => {+export const useWhisper = (): UseWhisperReturn => {const [whisperInstalled, setWhisperInstalled] = useState(false);const [checkingWhisper, setCheckingWhisper] = useState(false);- const [installingWhisper, setInstallingWhisper] = useState(false);- const [installProgress, setInstallProgress] = useState("");const checkWhisperInstallation = useCallback(async () => {try {@@ -31,62 +17,13 @@ export const useWhisper = (const result: WhisperCheckResult = await window.electronAPI.checkWhisperInstallation();setWhisperInstalled(result.installed && result.working);} catch (error) {- console.error("Error checking Whisper installation:", error);+ console.error("Error checking whisper.cpp installation:", error);setWhisperInstalled(false);} finally {setCheckingWhisper(false);}}, []);- const installWhisper = useCallback(async () => {- try {- setInstallingWhisper(true);- setInstallProgress("Starting Whisper installation...");-- const result: WhisperInstallResult = await window.electronAPI.installWhisper();-- if (result.success) {- setWhisperInstalled(true);- setInstallProgress("Installation complete!");- } else {- if (showAlertDialog) {- showAlertDialog({- title: "❌ Whisper Installation Failed",- description: `Failed to install Whisper: ${result.message}`,- });- } else {- alert(`❌ Failed to install Whisper: ${result.message}`);- }- }- } catch (error) {- console.error("Error installing Whisper:", error);- if (showAlertDialog) {- showAlertDialog({- title: "❌ Whisper Installation Failed",- description: `Failed to install Whisper: ${error}`,- });- } else {- alert(`❌ Failed to install Whisper: ${error}`);- }- } finally {- setInstallingWhisper(false);- setTimeout(() => setInstallProgress(""), 2000); // Clear progress after 2 seconds- }- }, [showAlertDialog]);-- const setupProgressListener = useCallback(() => {- if (!window.electronAPI?.onWhisperInstallProgress) {- return;- }-- const dispose = window.electronAPI.onWhisperInstallProgress((_, data) => {- setInstallProgress(data.message);- });-- return () => dispose?.();- }, []);-- // Check Whisper installation on mountuseEffect(() => {checkWhisperInstallation();}, [checkWhisperInstallation]);@@ -94,10 +31,6 @@ export const useWhisper = (return {whisperInstalled,checkingWhisper,- installingWhisper,- installProgress,checkWhisperInstallation,- installWhisper,- setupProgressListener,};};diff --git a/src/types/electron.ts b/src/types/electron.tsindex f96a3764a..e6c097477 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -5,12 +5,6 @@ export interface TranscriptionItem {created_at: string;}-export interface WhisperInstallResult {- success: boolean;- message: string;- output: string;-}-export interface WhisperCheckResult {installed: boolean;working: boolean;@@ -80,30 +74,6 @@ export interface WhisperDownloadProgressData {result?: any;}-export interface WhisperInstallProgressData {- type: string;- message: string;- output?: string;-}--export interface PythonInstallation {- installed: boolean;- command?: string;- version?: number;- source?: string;-}--export interface PythonInstallResult {- success: boolean;- method: string;-}--export interface PythonInstallProgressData {- type: string;- stage: string;- percentage: number;-}-export interface PasteToolsResult {platform: "darwin" | "win32" | "linux";available: boolean;@@ -169,20 +139,9 @@ declare global {}>;onNoAudioDetected: (callback: (event: any, data?: any) => void) => (() => void) | void;- // Python operations- checkPythonInstallation: () => Promise<PythonInstallation>;- installPython: () => Promise<PythonInstallResult>;- onPythonInstallProgress: (- callback: (event: any, data: PythonInstallProgressData) => void- ) => (() => void) | void;-- // Whisper operations+ // Whisper operations (whisper.cpp)transcribeLocalWhisper: (audioBlob: Blob | ArrayBuffer, options?: any) => Promise<any>;checkWhisperInstallation: () => Promise<WhisperCheckResult>;- installWhisper: () => Promise<WhisperInstallResult>;- onWhisperInstallProgress: (- callback: (event: any, data: WhisperInstallProgressData) => void- ) => (() => void) | void;downloadWhisperModel: (modelName: string) => Promise<WhisperModelResult>;onWhisperDownloadProgress: (callback: (event: any, data: WhisperDownloadProgressData) => voiddiff --git a/whisper_bridge.py b/whisper_bridge.pydeleted file mode 100755index 8dc5c0417..000000000--- a/whisper_bridge.py+++ /dev/null@@ -1,506 +0,0 @@-#!/usr/bin/env python3-"""-Whisper Bridge Script for OpenWhispr-Handles local speech-to-text processing using OpenAI's Whisper model-"""--import sys-import json-import os-import argparse-import whisper-import threading-import time-import requests-import gc---def get_whisper_cache_dir():- """Get platform-appropriate cache directory for Whisper models"""- if sys.platform == "win32":- # Windows: use %LOCALAPPDATA%\whisper or fallback to %USERPROFILE%\.cache\whisper- local_app_data = os.environ.get("LOCALAPPDATA")- if local_app_data:- return os.path.join(local_app_data, "whisper")- # Fallback to user profile- user_profile = os.environ.get("USERPROFILE", os.path.expanduser("~"))- return os.path.join(user_profile, ".cache", "whisper")- else:- # macOS/Linux: use ~/.cache/whisper- return os.path.expanduser("~/.cache/whisper")---def get_ffmpeg_path():- """Get path to bundled FFmpeg executable with proper production support"""- # Check environment variables first- env_paths = [- ("FFMPEG_PATH", os.environ.get("FFMPEG_PATH")),- ("FFMPEG_EXECUTABLE", os.environ.get("FFMPEG_EXECUTABLE")),- ("FFMPEG_BINARY", os.environ.get("FFMPEG_BINARY")),- ]-- for env_name, env_path in env_paths:- # On Windows, skip X_OK check since it doesn't use Unix-style execute permissions- if env_path and os.path.exists(env_path):- if sys.platform == "win32" or os.access(env_path, os.X_OK):- return env_path-- # Determine base path- if getattr(sys, "frozen", False):- base_path = sys._MEIPASS- else:- base_path = os.path.dirname(os.path.abspath(__file__))-- # Try multiple possible paths for production Electron app- possible_paths = []-- if sys.platform == "darwin": # macOS- 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"),- # Alternative development path- os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg"),- ]- elif sys.platform == "win32": # Windows- 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"),- os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg.exe"),- ]- else: # Linux- 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"),- os.path.join(base_path, "..", "node_modules", "ffmpeg-static", "ffmpeg"),- ]-- # Try each possible path- for ffmpeg_path in possible_paths:- abs_path = os.path.abspath(ffmpeg_path)- # On Windows, skip X_OK check since it doesn't use Unix-style execute permissions- if os.path.exists(abs_path):- if sys.platform == "win32" or 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 Whisper-ffmpeg_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}{os.pathsep}{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 = {}---def load_model(model_name="base"):- """Load Whisper model with caching for performance"""- global _model_cache-- # Return cached model if available- if model_name in _model_cache:- return _model_cache[model_name]-- try:- model = whisper.load_model(model_name)-- if len(_model_cache) >= 2:- oldest_key = next(iter(_model_cache))- del _model_cache[oldest_key]- gc.collect()-- _model_cache[model_name] = model- return model- except Exception:- return None---def get_expected_model_size(model_name):- """Get expected file size for a model by checking the remote URL"""- try:- model_url = whisper._MODELS[model_name]- response = requests.head(model_url, timeout=10)- if response.status_code == 200:- content_length = response.headers.get("content-length")- if content_length:- return int(content_length)- except Exception:- pass-- approximate_sizes = {- "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)---def monitor_download_progress(model_name, expected_size, stop_event):- """Monitor download progress by watching file size growth"""- cache_dir = get_whisper_cache_dir()- model_url = whisper._MODELS[model_name]- model_file = os.path.join(cache_dir, os.path.basename(model_url))-- os.makedirs(cache_dir, exist_ok=True)-- last_size = 0- last_update_time = time.time()- speed_samples = []- last_progress_update = 0-- while not stop_event.is_set():- try:- current_size = 0- if os.path.exists(model_file):- current_size = os.path.getsize(model_file)-- current_time = time.time()- time_diff = current_time - last_update_time-- speed_mbps = 0- if 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)-- speed_samples.append(speed_mbps)- if len(speed_samples) > 10:- speed_samples.pop(0)- speed_mbps = sum(speed_samples) / len(speed_samples)-- percentage = min((current_size / expected_size * 100) if expected_size > 0 else 0, 100)-- if current_time - last_progress_update > 0.5 or abs(percentage - last_progress_update) > 1.0:- progress_data = {- "type": "progress",- "model": model_name,- "downloaded_bytes": current_size,- "total_bytes": expected_size,- "percentage": round(percentage, 1),- "speed_mbps": round(speed_mbps, 2) if speed_mbps > 0 else 0,- }-- print(f"PROGRESS:{json.dumps(progress_data)}", file=sys.stderr)- last_progress_update = percentage-- if current_size >= expected_size * 0.95:- break-- if current_size == last_size and current_time - last_update_time > 10:- if current_size > expected_size * 0.9:- break-- last_size = current_size- last_update_time = current_time-- except Exception:- pass-- time.sleep(0.5)---def download_model(model_name="base"):- """Download Whisper model with real-time progress monitoring"""- stop_event = threading.Event()- progress_thread = None-- try:- # Check if model is already downloaded- cache_dir = get_whisper_cache_dir()- model_url = whisper._MODELS[model_name]- model_file = os.path.join(cache_dir, os.path.basename(model_url))-- if os.path.exists(model_file):- file_size = os.path.getsize(model_file)- return {- "model": model_name,- "downloaded": True,- "path": model_file,- "size_bytes": file_size,- "size_mb": round(file_size / (1024 * 1024), 1),- "success": True,- }-- # Get expected file size- expected_size = get_expected_model_size(model_name)-- # Start progress monitoring in background thread- progress_thread = threading.Thread(- target=monitor_download_progress, args=(model_name, expected_size, stop_event), daemon=True- )- progress_thread.start()-- # Start the actual download (this will block until complete)- whisper.load_model(model_name)-- # Stop progress monitoring- stop_event.set()-- # Wait for progress thread to finish- if progress_thread and progress_thread.is_alive():- progress_thread.join(timeout=1)-- # Get final file info- final_size = 0- if os.path.exists(model_file):- final_size = os.path.getsize(model_file)-- # Send completion signal- completion_data = {- "type": "complete",- "model": model_name,- "downloaded_bytes": final_size,- "total_bytes": expected_size,- "percentage": 100,- }- print(f"PROGRESS:{json.dumps(completion_data)}", file=sys.stderr)-- return {- "model": model_name,- "downloaded": True,- "path": model_file,- "size_bytes": final_size,- "size_mb": round(final_size / (1024 * 1024), 1),- "success": True,- }-- except KeyboardInterrupt:- stop_event.set()- return {"model": model_name, "downloaded": False, "error": "Download interrupted by user", "success": False}- except Exception as e:- stop_event.set()- return {"model": model_name, "downloaded": False, "error": str(e), "success": False}---def check_model_status(model_name="base"):- """Check if a model is already downloaded"""- try:- cache_dir = get_whisper_cache_dir()- model_url = whisper._MODELS[model_name]- model_file = os.path.join(cache_dir, os.path.basename(model_url))-- if os.path.exists(model_file):- file_size = os.path.getsize(model_file)- return {- "model": model_name,- "downloaded": True,- "path": model_file,- "size_bytes": file_size,- "size_mb": round(file_size / (1024 * 1024), 1),- "success": True,- }- else:- return {"model": model_name, "downloaded": False, "success": True}- except Exception as e:- return {"model": model_name, "error": str(e), "success": False}---def list_models():- """List all available models and their download status"""- models = ["tiny", "base", "small", "medium", "large", "turbo"]- model_info = []-- for model in models:- status = check_model_status(model)- model_info.append(status)-- return {"models": model_info, "cache_dir": get_whisper_cache_dir(), "success": True}---def delete_model(model_name="base"):- """Delete a downloaded Whisper model"""- try:- cache_dir = get_whisper_cache_dir()- model_url = whisper._MODELS[model_name]- model_file = os.path.join(cache_dir, os.path.basename(model_url))-- if os.path.exists(model_file):- file_size = os.path.getsize(model_file)- os.remove(model_file)- return {- "model": model_name,- "deleted": True,- "freed_bytes": file_size,- "freed_mb": round(file_size / (1024 * 1024), 1),- "success": True,- }- else:- return {"model": model_name, "deleted": False, "error": "Model not found", "success": False}- except Exception as e:- return {"model": model_name, "deleted": False, "error": str(e), "success": False}---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}-- options = {- "fp16": False,- "verbose": False,- }- if language:- options["language"] = language-- result = model.transcribe(audio_path, **options)-- text = result.get("text", "").strip()- language = result.get("language", "unknown")-- return {"text": text, "language": language, "success": True}-- except Exception as e:- return {"error": str(e), "success": False}---def check_ffmpeg():- """Check if FFmpeg is available and working"""- try:- import subprocess-- 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": test_path, "version": version_line, "success": True}- else:- return {- "available": False,- "error": f"FFmpeg returned code {result.returncode}: {result.stderr}",- "success": False,- }- except subprocess.TimeoutExpired:- return {"available": False, "error": "FFmpeg check timed out", "success": False}- except FileNotFoundError:- return {"available": False, "error": "FFmpeg not found in PATH", "success": False}- except Exception as e:- return {"available": False, "error": str(e), "success": False}---def main():- parser = argparse.ArgumentParser(description="Whisper Bridge for OpenWhispr")- parser.add_argument(- "--mode",- default="transcribe",- choices=["transcribe", "download", "check", "list", "delete", "check-ffmpeg"],- help="Operation mode (default: transcribe)",- )- parser.add_argument("audio_file", nargs="?", help="Path to audio file to transcribe")- parser.add_argument(- "--model",- default="base",- choices=["tiny", "base", "small", "medium", "large", "turbo"],- help="Whisper model to use (default: base)",- )- parser.add_argument("--language", help="Language code (optional)")- parser.add_argument(- "--output-format", default="json", choices=["json", "text"], help="Output format (default: json)"- )-- args = parser.parse_args()-- # Handle different modes- if args.mode == "download":- result = download_model(args.model)- print(json.dumps(result))- return- elif args.mode == "check":- result = check_model_status(args.model)- print(json.dumps(result))- return- elif args.mode == "list":- result = list_models()- print(json.dumps(result))- return- elif args.mode == "delete":- result = delete_model(args.model)- print(json.dumps(result))- return- elif args.mode == "check-ffmpeg":- result = check_ffmpeg()- print(json.dumps(result))- return- elif args.mode == "transcribe":- # Check if audio file exists- if not args.audio_file:- error_result = {"error": "Audio file required for transcription mode", "success": False}- print(json.dumps(error_result))- sys.exit(1)-- if not os.path.exists(args.audio_file):- error_result = {"error": f"Audio file not found: {args.audio_file}", "success": False}- print(json.dumps(error_result))- sys.exit(1)-- # Transcribe- result = transcribe_audio(args.audio_file, args.model, args.language)-- # Output results- if args.output_format == "json":- print(json.dumps(result))- else:- if result.get("success"):- print(result.get("text", ""))- else:- print(f"Error: {result.get('error', 'Unknown error')}", file=sys.stderr)- sys.exit(1)---if __name__ == "__main__":- main()