Skip to content

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

feat: add python detection support

Gabriel Steinf1e7852224d3
diff --git a/electron-builder.json b/electron-builder.json
index 59ef22bdb..12a009b93 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -15,6 +15,7 @@
"src/hooks/**/*",
"src/types/**/*",
"src/utils.js",
+ "src/utils/**/*",
"src/updater.js",
"src/components.json",
"!node_modules/.cache/**/*",
@@ -40,7 +41,7 @@
"entitlementsInherit": "build/entitlements.mac.plist",
"identity": "HeroTools Inc. (9R85XFMH59)",
"extendInfo": {
- "LSUIElement": false,
+ "LSUIElement": true,
"NSMicrophoneUsageDescription": "OpenWispr needs microphone access for speech-to-text transcription.",
"NSAccessibilityUsageDescription": "OpenWispr needs accessibility permissions to paste transcribed text into other applications."
}
diff --git a/package.json b/package.json
index 94068ec14..9f969ca48 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-wispr",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "A desktop dictation application using OpenAI Whisper for speech-to-text transcription",
"main": "main.js",
"private": true,
diff --git a/preload.js b/preload.js
index 12e43adc0..f01016c90 100644
--- a/preload.js
+++ b/preload.js
@@ -28,6 +28,13 @@ contextBridge.exposeInMainWorld("electronAPI", {
readClipboard: () => ipcRenderer.invoke("read-clipboard"),
writeClipboard: (text) => ipcRenderer.invoke("write-clipboard", text),
+ // Python installation functions
+ checkPythonInstallation: () =>
+ ipcRenderer.invoke("check-python-installation"),
+ installPython: () => ipcRenderer.invoke("install-python"),
+ onPythonInstallProgress: (callback) =>
+ ipcRenderer.on("python-install-progress", callback),
+
// Local Whisper functions
transcribeLocalWhisper: (audioBlob, options) =>
ipcRenderer.invoke("transcribe-local-whisper", audioBlob, options),
@@ -84,4 +91,9 @@ contextBridge.exposeInMainWorld("electronAPI", {
// External link opener
openExternal: (url) => ipcRenderer.invoke("open-external", url),
+
+ // Remove all listeners for a channel
+ removeAllListeners: (channel) => {
+ ipcRenderer.removeAllListeners(channel);
+ },
});
diff --git a/scripts/notarize.js b/scripts/notarize.js
index 9bd9104ef..91c026c9e 100644
--- a/scripts/notarize.js
+++ b/scripts/notarize.js
@@ -18,7 +18,8 @@ exports.default = async function notarizing(context) {
const result = await notarize({
tool: 'notarytool',
appPath,
- keychainProfile: 'openwispr-profile'
+ keychainProfile: 'openwispr-profile',
+ staple: true
});
console.log('✓ Notarization completed successfully');
return result;
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 047675940..b3c7d96ae 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -29,6 +29,7 @@ import { AlertDialog } 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";
@@ -76,6 +77,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
const practiceTextareaRef = useRef<HTMLInputElement>(null);
const whisperHook = useWhisper(showAlertDialog);
+ const pythonHook = usePython(showAlertDialog);
const permissionsHook = usePermissions(showAlertDialog);
const { pasteFromClipboard } = useClipboard(showAlertDialog);
@@ -92,7 +94,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
useEffect(() => {
whisperHook.setupProgressListener();
- }, [whisperHook]);
+ return () => {
+ // Clean up listeners on unmount
+ window.electronAPI?.removeAllListeners?.("whisper-install-progress");
+ };
+ }, []);
const updateProcessingMode = (useLocal: boolean) => {
updateTranscriptionSettings({ useLocalWhisper: useLocal });
@@ -253,7 +259,50 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
{useLocalWhisper ? (
<div className="space-y-4">
- {!whisperHook.whisperInstalled ? (
+ {/* Python Installation Section */}
+ {!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>
+ ) : (
+ <Button
+ onClick={() => {
+ pythonHook.installPython();
+ }}
+ className="w-full bg-blue-600 hover:bg-blue-700"
+ >
+ Install Python
+ </Button>
+ )}
+ </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" />
@@ -263,8 +312,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
Install Whisper
</h3>
<p className="text-sm text-gray-600 mb-4">
- We'll automatically install Whisper for you. No
- technical setup required.
+ Python is ready! Now we'll install Whisper for speech recognition.
</p>
</div>
@@ -286,22 +334,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</p>
</div>
) : (
- <div className="space-y-3">
- <Button
- onClick={whisperHook.installWhisper}
- className="w-full"
- >
- Install Whisper
- </Button>
- <Button
- onClick={whisperHook.checkWhisperInstallation}
- variant="outline"
- size="sm"
- className="w-full"
- >
- Check if already installed
- </Button>
- </div>
+ <Button
+ onClick={whisperHook.installWhisper}
+ className="w-full"
+ >
+ Install Whisper
+ </Button>
)}
</div>
) : (
@@ -714,7 +752,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
return true; // Mode selection
case 2:
if (useLocalWhisper) {
- return whisperHook.whisperInstalled;
+ return pythonHook.pythonInstalled && whisperHook.whisperInstalled;
} else {
return apiKey.trim() !== "";
}
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 7fa9da509..1dde914b7 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -340,6 +340,82 @@ export default function SettingsPage({
</>
)}
</Button>
+
+ {updateStatus.updateAvailable && !updateStatus.updateDownloaded && (
+ <Button
+ onClick={async () => {
+ setDownloadingUpdate(true);
+ setUpdateDownloadProgress(0);
+ try {
+ await window.electronAPI?.downloadUpdate();
+ } catch (error: any) {
+ setDownloadingUpdate(false);
+ showAlertDialog({
+ title: "Download Failed",
+ description: `Failed to download update: ${error.message}`,
+ });
+ }
+ }}
+ disabled={downloadingUpdate}
+ className="w-full bg-green-600 hover:bg-green-700"
+ >
+ {downloadingUpdate ? (
+ <>
+ <Download size={16} className="animate-pulse mr-2" />
+ Downloading... {Math.round(updateDownloadProgress)}%
+ </>
+ ) : (
+ <>
+ <Download size={16} className="mr-2" />
+ Download Update v{updateInfo.version}
+ </>
+ )}
+ </Button>
+ )}
+
+ {updateStatus.updateDownloaded && (
+ <Button
+ onClick={async () => {
+ showConfirmDialog({
+ title: "Install Update",
+ description: `Ready to install update v${updateInfo.version}. The app will restart to complete installation.`,
+ onConfirm: async () => {
+ try {
+ await window.electronAPI?.installUpdate();
+ } catch (error: any) {
+ showAlertDialog({
+ title: "Install Failed",
+ description: `Failed to install update: ${error.message}`,
+ });
+ }
+ },
+ });
+ }}
+ className="w-full bg-blue-600 hover:bg-blue-700"
+ >
+ <span className="mr-2">🚀</span>
+ Install Update & Restart
+ </Button>
+ )}
+
+ {updateInfo.version && (
+ <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
+ <h4 className="font-medium text-blue-900 mb-2">
+ Update v{updateInfo.version}
+ </h4>
+ {updateInfo.releaseDate && (
+ <p className="text-sm text-blue-700 mb-2">
+ Released: {new Date(updateInfo.releaseDate).toLocaleDateString()}
+ </p>
+ )}
+ {updateInfo.releaseNotes && (
+ <div className="text-sm text-blue-800">
+ <p className="font-medium mb-1">What's New:</p>
+ <div className="whitespace-pre-wrap">{updateInfo.releaseNotes}</div>
+ </div>
+ )}
+ </div>
+ )}
</div>
</div>
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index c66bbbd7c..e3b77aea9 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -138,6 +138,26 @@ 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) {
+ console.error("❌ Python installation error:", error);
+ throw error;
+ }
+ });
+
ipcMain.handle("install-whisper", async (event) => {
try {
// Set up progress forwarding for installation
diff --git a/src/helpers/pythonInstaller.js b/src/helpers/pythonInstaller.js
new file mode 100644
index 000000000..ffd9983b7
--- /dev/null
+++ b/src/helpers/pythonInstaller.js
@@ -0,0 +1,326 @@
+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
+ }
+
+ // Removed - now using shared runCommand from utils/process.js
+
+ 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 });
+ }
+
+ // 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=%LOCALAPPDATA%\\Programs\\Python\\Python311"
+ ];
+
+ await runCommand(installerPath, installArgs, { 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 installPythonLinux(progressCallback = null) {
+ const platform = process.platform;
+
+ 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 });
+ await runCommand("sudo", ["apt", "install", "-y", "python3.11", "python3.11-pip", "python3.11-dev"], { 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 });
+ }
+
+ await runCommand("sudo", ["yum", "install", "-y", "python311", "python311-pip", "python311-devel"], { 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 error;
+ }
+ }
+
+ async installPython(progressCallback = null) {
+ const platform = process.platform;
+
+ try {
+ 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}`);
+ }
+
+ } catch (error) {
+ console.error("Python installation failed:", error);
+ throw error;
+ }
+ }
+
+ async isPythonInstalled() {
+ const possibleCommands = ['python3.11', 'python3', 'python'];
+
+ for (const cmd of possibleCommands) {
+ try {
+ const result = await runCommand(cmd, ['--version'], { timeout: TIMEOUTS.QUICK_CHECK });
+ const versionMatch = result.output.match(/Python (\d+\.\d+)/);
+ if (versionMatch) {
+ const version = parseFloat(versionMatch[1]);
+ // Accept any Python 3.x version
+ if (version >= 3.0) {
+ return { installed: true, command: cmd, version: version };
+ }
+ }
+ } catch (error) {
+ continue;
+ }
+ }
+
+ return { installed: false };
+ }
+}
+
+module.exports = PythonInstaller;
\ No newline at end of file
diff --git a/src/helpers/tray.js b/src/helpers/tray.js
index 20c448226..d07abc929 100644
--- a/src/helpers/tray.js
+++ b/src/helpers/tray.js
@@ -80,15 +80,17 @@ class TrayManager {
"assets",
),
+ path.join(app.getPath("exe"), "..", "Resources", "assets", "[email protected]"),
+ path.join(app.getAppPath(), "assets", "[email protected]"),
];
-
+
for (const testPath of possiblePaths) {
try {
if (fs.existsSync(testPath)) {
return nativeImage.createFromPath(testPath);
}
} catch (e) {
- // Ignore and try next path
+ console.log("❌ Error checking path:", testPath, e.message);
}
}
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index 9b468d2c1..e5bc90e5d 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -1,8 +1,11 @@
const { spawn } = require("child_process");
const fs = require("fs");
+const fsPromises = require("fs").promises;
const os = require("os");
const path = require("path");
const crypto = require("crypto");
+const PythonInstaller = require("./pythonInstaller");
+const { runCommand, TIMEOUTS } = require("../utils/process");
class WhisperManager {
constructor() {
@@ -10,6 +13,7 @@ class WhisperManager {
this.whisperInstalled = null; // Cache installation status
this.isInitialized = false; // Track if startup init completed
this.currentDownloadProcess = null; // Track current download process for cancellation
+ this.pythonInstaller = new PythonInstaller();
}
getWhisperScriptPath() {
@@ -53,7 +57,7 @@ class WhisperManager {
console.error("Local Whisper transcription error:", error);
throw error;
} finally {
- this.cleanupTempFile(tempAudioPath);
+ await this.cleanupTempFile(tempAudioPath);
}
}
@@ -75,7 +79,7 @@ class WhisperManager {
throw new Error(`Unsupported audio data type: ${typeof audioBlob}`);
}
- fs.writeFileSync(tempAudioPath, buffer);
+ await fsPromises.writeFile(tempAudioPath, buffer);
return tempAudioPath;
}
@@ -88,37 +92,68 @@ class WhisperManager {
}
args.push("--output-format", "json");
- return new Promise((resolve, reject) => {
- // Get FFmpeg path with proper production/development handling
+ return new Promise(async (resolve, reject) => {
+ // Get FFmpeg path with robust production/development handling
let ffmpegPath;
try {
ffmpegPath = require("ffmpeg-static");
+
+ // Add Windows .exe extension if missing
+ if (process.platform === "win32" && !ffmpegPath.endsWith(".exe")) {
+ ffmpegPath += ".exe";
+ }
- // In production, try unpacked version if original doesn't exist
- if (
- process.env.NODE_ENV !== "development" &&
- !fs.existsSync(ffmpegPath)
- ) {
- const unpackedPath = ffmpegPath.replace(
- "app.asar",
- "app.asar.unpacked"
- );
- if (fs.existsSync(unpackedPath)) {
- ffmpegPath = unpackedPath;
+ // In production, handle ASAR unpacking more robustly
+ if (process.env.NODE_ENV !== "development" && !fs.existsSync(ffmpegPath)) {
+ const possiblePaths = [
+ // Direct ASAR replacement
+ ffmpegPath.replace("app.asar", "app.asar.unpacked"),
+ // Alternative unpacked locations
+ ffmpegPath.replace(/.*app\.asar/, path.join(__dirname, "..", "..", "app.asar.unpacked")),
+ // Resources folder fallback
+ path.join(process.resourcesPath, "app.asar.unpacked", "node_modules", "ffmpeg-static", process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg")
+ ];
+
+ for (const possiblePath of possiblePaths) {
+ if (fs.existsSync(possiblePath)) {
+ ffmpegPath = possiblePath;
+ break;
+ }
}
}
+
+ // Final validation of bundled FFmpeg
+ if (!fs.existsSync(ffmpegPath)) {
+ throw new Error(`Bundled FFmpeg not found at ${ffmpegPath}`);
+ }
+
+ // Validate it's actually executable
+ try {
+ fs.accessSync(ffmpegPath, fs.constants.X_OK);
+ } catch (e) {
+ throw new Error(`FFmpeg exists but is not executable: ${ffmpegPath}`);
+ }
+
} catch (e) {
- console.error("Could not resolve FFmpeg path:", e.message);
- ffmpegPath = "ffmpeg"; // Try system ffmpeg as fallback
+ console.warn("Bundled FFmpeg not available:", e.message);
+
+ // Try system FFmpeg with validation
+ const systemFFmpeg = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
+ try {
+ await runCommand(systemFFmpeg, ["--version"], { timeout: TIMEOUTS.QUICK_CHECK });
+ ffmpegPath = systemFFmpeg;
+ console.log("Using system FFmpeg");
+ } catch (systemError) {
+ console.error("System FFmpeg also unavailable:", systemError.message);
+ ffmpegPath = systemFFmpeg; // Last resort - let Python handle the error
+ }
}
// Enhanced environment setup
const enhancedEnv = {
...process.env,
FFMPEG_PATH: ffmpegPath,
- FFMPEG_EXECUTABLE: ffmpegPath,
- FFMPEG_BINARY: ffmpegPath,
};
// Add ffmpeg directory to PATH if we have a valid path
@@ -232,9 +267,9 @@ class WhisperManager {
}
}
- cleanupTempFile(tempAudioPath) {
+ async cleanupTempFile(tempAudioPath) {
try {
- fs.unlinkSync(tempAudioPath);
+ await fsPromises.unlink(tempAudioPath);
} catch (cleanupError) {
console.warn("Could not clean up temp file:", cleanupError.message);
}
@@ -247,10 +282,14 @@ class WhisperManager {
}
const possiblePaths = [
+ "python3.11",
"python3",
"python",
+ "/usr/bin/python3.11",
"/usr/bin/python3",
+ "/usr/local/bin/python3.11",
"/usr/local/bin/python3",
+ "/opt/homebrew/bin/python3.11",
"/opt/homebrew/bin/python3",
"/usr/bin/python",
"/usr/local/bin/python",
@@ -269,10 +308,35 @@ class WhisperManager {
}
throw new Error(
- "Python 3.8-3.11 not found. Please ensure a compatible Python version is installed."
+ "Python 3.x not found. Use installPython() to install it automatically."
);
}
+ async installPython(progressCallback = null) {
+ try {
+ // Clear cached Python command since we're installing new one
+ this.pythonCmd = null;
+
+ const result = await this.pythonInstaller.installPython(progressCallback);
+
+ // After installation, try to find Python again
+ try {
+ await this.findPythonExecutable();
+ return result;
+ } catch (findError) {
+ throw new Error("Python installed but not found in PATH. Please restart the application.");
+ }
+
+ } catch (error) {
+ console.error("Python installation failed:", error);
+ throw error;
+ }
+ }
+
+ async checkPythonInstallation() {
+ return await this.pythonInstaller.isPythonInstalled();
+ }
+
async getPythonVersion(pythonPath) {
return new Promise((resolve) => {
const testProcess = spawn(pythonPath, ["--version"]);
@@ -295,7 +359,8 @@ class WhisperManager {
}
isPythonVersionSupported(version) {
- return version && version.major === 3 && version.minor >= 8 && version.minor <= 11;
+ // Accept any Python 3.x version
+ return version && version.major === 3;
}
async checkWhisperInstallation() {
@@ -397,92 +462,42 @@ class WhisperManager {
}
}
- async upgradePip(pythonCmd) {
- return new Promise((resolve) => {
- const upgradeProcess = spawn(pythonCmd, ["-m", "pip", "install", "--upgrade", "pip"]);
-
- const timeout = setTimeout(() => {
- upgradeProcess.kill("SIGTERM");
- resolve();
- }, 60000); // 1 minute timeout
-
- upgradeProcess.on("close", () => {
- clearTimeout(timeout);
- resolve();
- });
-
- upgradeProcess.on("error", () => {
- clearTimeout(timeout);
- resolve();
- });
- });
+ upgradePip(pythonCmd) {
+ return runCommand(pythonCmd, ["-m", "pip", "install", "--upgrade", "pip"], { timeout: TIMEOUTS.PIP_UPGRADE });
}
+ // Removed - now using shared runCommand from utils/process.js
+
async installWhisper() {
+ const pythonCmd = await this.findPythonExecutable();
+
+ // Upgrade pip first to avoid version issues
try {
- const pythonCmd = await this.findPythonExecutable();
-
- // First upgrade pip to ensure compatibility
await this.upgradePip(pythonCmd);
-
- const args = ["-m", "pip", "install", "-U", "openai-whisper"];
-
- return new Promise((resolve, reject) => {
- const installProcess = spawn(pythonCmd, args);
-
- let stdout = "";
- let stderr = "";
-
- installProcess.stdout.on("data", (data) => {
- stdout += data.toString();
- });
-
- installProcess.stderr.on("data", (data) => {
- stderr += data.toString();
- });
-
- installProcess.on("close", (code) => {
- if (code === 0) {
- resolve({
- success: true,
- message: "Whisper installed successfully!",
- output: stdout,
- });
- } else {
- console.error("Whisper installation failed with code:", code);
- console.error("Installation stderr:", stderr);
-
- let errorMessage = "Whisper installation failed";
-
- if (stderr.includes("pyproject.toml") && stderr.includes("TomlError")) {
- errorMessage = "Outdated pip version. Please upgrade pip manually and retry.";
- } else if (stderr.includes("No module named pip")) {
- errorMessage = "pip not installed.";
- } else if (stderr.includes("Permission denied")) {
- errorMessage = "Permission denied. May need administrator privileges.";
- } else if (stderr.includes("No matching distribution")) {
- errorMessage = "Incompatible Python version. Use Python 3.8-3.11.";
- }
-
- reject(new Error(errorMessage));
- }
- });
-
- installProcess.on("error", (error) => {
- console.error("Whisper installation process error:", error);
- reject(
- new Error(`Whisper installation process error: ${error.message}`)
- );
- });
-
- setTimeout(() => {
- installProcess.kill("SIGTERM");
- reject(new Error("Whisper installation timed out (10 minutes)"));
- }, 600000);
- });
} catch (error) {
- console.error("Whisper installation error:", error);
- throw error;
+ console.warn("Pip upgrade failed, continuing anyway:", error.message);
+ }
+
+ // Try regular install, then user install if permission issues
+ try {
+ return await runCommand(pythonCmd, ["-m", "pip", "install", "-U", "openai-whisper"], { timeout: TIMEOUTS.DOWNLOAD });
+ } catch (error) {
+ if (error.message.includes("Permission denied") || error.message.includes("access is denied")) {
+ console.log("Retrying with user installation...");
+ return await runCommand(pythonCmd, ["-m", "pip", "install", "--user", "-U", "openai-whisper"], { timeout: TIMEOUTS.DOWNLOAD });
+ }
+
+ // Enhanced error messages for common issues
+ let message = error.message;
+ if (message.includes("pyproject.toml") && message.includes("TomlError")) {
+ message = "Outdated pip version. Try manually running: python -m pip install --upgrade pip";
+ } else if (message.includes("Microsoft Visual C++")) {
+ message = "Microsoft Visual C++ build tools required. Install Visual Studio Build Tools.";
+ } else if (message.includes("No matching distribution")) {
+ message = "Python version incompatible. OpenAI Whisper requires Python 3.8-3.11.";
+ }
+
+ throw new Error(message);
}
}
diff --git a/src/hooks/usePython.ts b/src/hooks/usePython.ts
new file mode 100644
index 000000000..457c3e05d
--- /dev/null
+++ b/src/hooks/usePython.ts
@@ -0,0 +1,148 @@
+import { useState, useEffect, useCallback, useRef } from "react";
+
+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 mountedRef = useRef(true);
+
+ // Cleanup on unmount
+ useEffect(() => {
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+
+ const checkPythonInstallation = useCallback(async () => {
+ try {
+ const result = await window.electronAPI?.checkPythonInstallation();
+ if (result && mountedRef.current) {
+ setPythonInstalled(result.installed);
+ setPythonInfo(result);
+ return result;
+ }
+ return { installed: false };
+ } catch (error) {
+ console.error("Error checking Python installation:", error);
+ if (mountedRef.current) {
+ setPythonInstalled(false);
+ }
+ return { installed: false };
+ }
+ }, []);
+
+ const installPython = useCallback(async () => {
+ console.log("installPython called");
+ if (!mountedRef.current) return;
+
+ let progressListener: ((event: any, data: PythonInstallProgress) => void) | null = null;
+
+ try {
+ setInstallingPython(true);
+ setInstallProgress("Starting Python installation...");
+
+ progressListener = (_event: any, data: PythonInstallProgress) => {
+ if (!mountedRef.current) return;
+
+ if (data.type === "progress") {
+ setInstallProgress(`${data.stage} (${data.percentage}%)`);
+ }
+ };
+
+ // Listen for progress updates
+ if (window.electronAPI?.onPythonInstallProgress) {
+ window.electronAPI.onPythonInstallProgress(progressListener);
+ }
+
+ console.log("Calling window.electronAPI.installPython");
+ const result = await window.electronAPI?.installPython();
+ console.log("Install result:", result);
+
+ if (mountedRef.current && 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) {
+ if (!mountedRef.current) return;
+
+ console.error("Python installation failed:", error);
+
+ const errorMessage = getPythonInstallErrorMessage(error);
+
+ showAlertDialog({
+ title: "Installation Failed",
+ description: errorMessage,
+ });
+
+ throw error;
+ } finally {
+ if (mountedRef.current) {
+ setInstallingPython(false);
+ }
+ // Clean up the listener
+ if (progressListener) {
+ window.electronAPI?.removeAllListeners?.("python-install-progress");
+ }
+ }
+ }, [showAlertDialog, checkPythonInstallation]);
+
+ // Check Python installation on mount
+ useEffect(() => {
+ checkPythonInstallation();
+ }, [checkPythonInstallation]);
+
+ return {
+ pythonInstalled,
+ installingPython,
+ installProgress,
+ pythonInfo,
+ installPython,
+ checkPythonInstallation,
+ };
+}
\ No newline at end of file
diff --git a/src/hooks/useWhisper.ts b/src/hooks/useWhisper.ts
index 25f001e0d..3a3cc58f5 100644
--- a/src/hooks/useWhisper.ts
+++ b/src/hooks/useWhisper.ts
@@ -1,4 +1,4 @@
-import { useState, useCallback } from "react";
+import { useState, useCallback, useEffect } from "react";
import { WhisperCheckResult, WhisperInstallResult } from "../types/electron";
export interface UseWhisperReturn {
@@ -77,11 +77,19 @@ export const useWhisper = (
}, [showAlertDialog]);
const setupProgressListener = useCallback(() => {
+ // Remove any existing listeners first
+ window.electronAPI?.removeAllListeners?.("whisper-install-progress");
+
window.electronAPI.onWhisperInstallProgress((_, data) => {
setInstallProgress(data.message);
});
}, []);
+ // Check Whisper installation on mount
+ useEffect(() => {
+ checkWhisperInstallation();
+ }, [checkWhisperInstallation]);
+
return {
whisperInstalled,
checkingWhisper,
diff --git a/src/types/electron.ts b/src/types/electron.ts
index e2e9f76ef..d4f6198c8 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -79,6 +79,23 @@ export interface WhisperInstallProgressData {
output?: string;
}
+export interface PythonInstallation {
+ installed: boolean;
+ command?: string;
+ version?: number;
+}
+
+export interface PythonInstallResult {
+ success: boolean;
+ method: string;
+}
+
+export interface PythonInstallProgressData {
+ type: string;
+ stage: string;
+ percentage: number;
+}
+
// Additional interface missing from preload.js
export interface SaveSettings {
useLocalWhisper: boolean;
@@ -113,6 +130,13 @@ declare global {
readClipboard: () => Promise<string>;
writeClipboard: (text: string) => Promise<{ success: boolean }>;
+ // Python operations
+ checkPythonInstallation: () => Promise<PythonInstallation>;
+ installPython: () => Promise<PythonInstallResult>;
+ onPythonInstallProgress: (
+ callback: (event: any, data: PythonInstallProgressData) => void
+ ) => void;
+
// Whisper operations
transcribeLocalWhisper: (
audioBlob: Blob | ArrayBuffer,
diff --git a/src/utils/process.js b/src/utils/process.js
new file mode 100644
index 000000000..7dabb467f
--- /dev/null
+++ b/src/utils/process.js
@@ -0,0 +1,122 @@
+const { spawn } = require("child_process");
+
+// Timeout constants
+const TIMEOUTS = {
+ QUICK_CHECK: 5000, // 5 seconds for quick checks
+ COMMAND: 30000, // 30 seconds for general commands
+ INSTALL: 300000, // 5 minutes for installations
+ DOWNLOAD: 600000, // 10 minutes for downloads
+ PIP_UPGRADE: 60000, // 1 minute for pip upgrade
+};
+
+// Command whitelist for shell operations
+const SAFE_SHELL_COMMANDS = new Set(['brew', 'apt', 'yum', 'pacman']);
+
+/**
+ * Validate command arguments for safety
+ * @param {string} cmd - Command to validate
+ * @param {string[]} args - Arguments to validate
+ * @param {boolean} shell - Whether shell is being used
+ * @throws {Error} If validation fails
+ */
+function validateCommand(cmd, args, shell) {
+ // Reject shell usage for non-whitelisted commands
+ if (shell && !SAFE_SHELL_COMMANDS.has(cmd)) {
+ throw new Error(`Shell execution not allowed for command: ${cmd}`);
+ }
+
+ // Check for dangerous characters in arguments
+ const dangerousChars = /[;&|`$<>]/;
+ if (args.some(arg => dangerousChars.test(arg))) {
+ throw new Error('Command arguments contain potentially dangerous characters');
+ }
+}
+
+/**
+ * Run a command with proper error handling and timeout
+ * @param {string} cmd - Command to run
+ * @param {string[]} args - Command arguments
+ * @param {Object} options - Options object
+ * @param {number} options.timeout - Timeout in milliseconds
+ * @param {boolean} options.shell - Whether to use shell (avoid unless necessary)
+ * @returns {Promise<{success: boolean, output: string}>}
+ */
+async function runCommand(cmd, args = [], options = {}) {
+ const { timeout = TIMEOUTS.COMMAND, shell = false } = options;
+
+ // Validate command for security
+ validateCommand(cmd, args, shell);
+
+ return new Promise((resolve, reject) => {
+ let process;
+ let stdout = "";
+ let stderr = "";
+ let completed = false;
+ let timer;
+
+ try {
+ process = spawn(cmd, args, { shell });
+ } catch (error) {
+ reject(error);
+ return;
+ }
+
+ const cleanup = () => {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ if (process && !completed) {
+ completed = true;
+ try {
+ process.kill("SIGTERM");
+ // Force kill after 5 seconds if still running
+ setTimeout(() => {
+ if (process.exitCode === null) {
+ process.kill("SIGKILL");
+ }
+ }, 5000);
+ } catch (e) {
+ // Process already dead
+ }
+ }
+ };
+
+ timer = setTimeout(() => {
+ cleanup();
+ reject(new Error(`Command timed out after ${timeout}ms`));
+ }, timeout);
+
+ process.stdout.on("data", (data) => {
+ stdout += data.toString();
+ });
+
+ process.stderr.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ process.on("close", (code) => {
+ if (completed) return; // Already handled
+ completed = true;
+ clearTimeout(timer);
+
+ if (code === 0) {
+ resolve({ success: true, output: stdout });
+ } else {
+ reject(new Error(stderr || `Command failed with code ${code}`));
+ }
+ });
+
+ process.on("error", (error) => {
+ if (completed) return; // Already handled
+ completed = true;
+ cleanup();
+ reject(error);
+ });
+ });
+}
+
+module.exports = {
+ runCommand,
+ TIMEOUTS,
+};
\ No newline at end of file