### Hotkey Manager: Registering and Handling Global Shortcuts (JavaScript) Source: https://context7.com/yan5xu/ququ/llms.txt A manager class for registering and handling global keyboard shortcuts. It allows for registering standard hotkeys, specific function keys like F2 with double-click detection, and managing the recording state to enable or disable hotkeys. It also provides functionality to get and unregister hotkeys. ```javascript const HotkeyManager = require('./src/helpers/hotkeyManager'); const manager = new HotkeyManager(); // Register standard hotkey const success = manager.registerHotkey('CommandOrControl+Shift+Space', () => { console.log('Hotkey triggered!'); // Show recording window, start recording, etc. }); // Register F2 with double-click detection manager.registerF2DoubleClick((data) => { console.log('F2 double-clicked:', data); // data: { timestamp: 1640000000000, interval: 250 } }); // Set recording state (prevents hotkey trigger during recording) manager.setRecordingState(true); // Disable hotkey manager.setRecordingState(false); // Enable hotkey // Get current recording state const isRecording = manager.getRecordingState(); // Get all registered hotkeys const hotkeys = manager.getRegisteredHotkeys(); // Returns: ['F2', 'CommandOrControl+Shift+Space'] // Unregister hotkey manager.unregisterHotkey('CommandOrControl+Shift+Space'); ``` -------------------------------- ### Recording Hook - Audio Capture Source: https://context7.com/yan5xu/ququ/llms.txt A React hook for managing audio recording using the MediaRecorder API. It provides state management for recording status, time, and audio level, along with functions to start, stop, pause, and resume recording. ```APIDOC ## Recording Hook - Audio Capture React hook for managing audio recording with MediaRecorder API. ### Hook Usage ```javascript import { useRecording } from './hooks/useRecording'; function RecordingComponent() { const { isRecording, isPaused, recordingTime, audioLevel, startRecording, stopRecording, pauseRecording, resumeRecording } = useRecording({ onRecordingComplete: async (audioBlob, duration) => { console.log(`Recording complete: ${duration}s, size: ${audioBlob.size}`); // Send to FunASR for transcription const result = await window.api.transcribeAudio(audioBlob); console.log('Transcription:', result.text); }, onError: (error) => { console.error('Recording error:', error); } }); return (
Time: {recordingTime}s Level: {Math.round(audioLevel * 100)}%
); } ``` ### Available States and Methods - `isRecording` (boolean): Indicates if recording is currently active. - `isPaused` (boolean): Indicates if recording is currently paused. - `recordingTime` (number): The elapsed time of the recording in seconds. - `audioLevel` (number): The current audio input level (0 to 1). - `startRecording()`: Starts the audio recording. - `stopRecording()`: Stops the audio recording and triggers `onRecordingComplete`. - `pauseRecording()`: Pauses the audio recording. - `resumeRecording()`: Resumes the paused audio recording. ``` -------------------------------- ### Recording Hook: Audio Capture with MediaRecorder API (JavaScript) Source: https://context7.com/yan5xu/ququ/llms.txt A React hook for managing audio recording. It utilizes the MediaRecorder API to handle starting, stopping, pausing, and resuming recordings. It provides the recording state, duration, and audio level, and includes callbacks for completion and errors. ```javascript import { useRecording } from './hooks/useRecording'; function RecordingComponent() { const { isRecording, isPaused, recordingTime, audioLevel, startRecording, stopRecording, pauseRecording, resumeRecording } = useRecording({ onRecordingComplete: async (audioBlob, duration) => { console.log(`Recording complete: ${duration}s, size: ${audioBlob.size}`); // Send to FunASR for transcription const result = await window.api.transcribeAudio(audioBlob); console.log('Transcription:', result.text); }, onError: (error) => { console.error('Recording error:', error); } }); return (
Time: {recordingTime}s Level: {Math.round(audioLevel * 100)}%
); } ``` -------------------------------- ### Electron Window Manager for Multi-Window Control (JavaScript) Source: https://context7.com/yan5xu/ququ/llms.txt The `WindowManager` class provides a centralized way to create, manage, and control multiple Electron windows. It supports creating main windows, control panels, and other types of windows with customizable properties like transparency and frameless design. It also offers methods for showing, hiding, and sending Inter-Process Communication (IPC) messages to specific windows, simplifying complex multi-window applications. ```javascript const WindowManager = require('./src/helpers/windowManager'); const manager = new WindowManager(); // Create main recording window await manager.createMainWindow(); // Properties: transparent, frameless, always-on-top, click-through initially // Create control panel window await manager.createControlPanelWindow(); // Full settings and configuration interface // Show/hide windows manager.showControlPanel(); manager.hideControlPanel(); manager.showHistoryWindow(); manager.hideHistoryWindow(); manager.showSettingsWindow(); manager.hideSettingsWindow(); // Access window instances const mainWin = manager.mainWindow; const controlPanel = manager.controlPanelWindow; // Send IPC to specific window if (mainWin && !mainWin.isDestroyed()) { mainWin.webContents.send('update-status', { status: 'ready' }); } ``` -------------------------------- ### Hotkey Manager - Global Shortcuts Source: https://context7.com/yan5xu/ququ/llms.txt A manager class for registering and handling global keyboard shortcuts. It allows for registering standard hotkeys, handling specific keys like F2 with double-click detection, and managing the recording state to enable or disable hotkeys. ```APIDOC ## Hotkey Manager - Global Shortcuts Manager class for registering and handling global keyboard shortcuts. ### Register Standard Hotkey ```javascript const success = manager.registerHotkey('CommandOrControl+Shift+Space', () => { console.log('Hotkey triggered!'); // Show recording window, start recording, etc. }); // Returns: true if registered successfully, false otherwise. ``` ### Register F2 Double-Click ```javascript manager.registerF2DoubleClick((data) => { console.log('F2 double-clicked:', data); // data: { timestamp: 1640000000000, interval: 250 } }); ``` ### Set Recording State (Enable/Disable Hotkeys) ```javascript manager.setRecordingState(true); // Disables hotkeys during recording manager.setRecordingState(false); // Enables hotkeys ``` ### Get Current Recording State ```javascript const isRecording = manager.getRecordingState(); // Returns: true if hotkeys are disabled, false otherwise. ``` ### Get All Registered Hotkeys ```javascript const hotkeys = manager.getRegisteredHotkeys(); // Returns: ['F2', 'CommandOrControl+Shift+Space'] ``` ### Unregister Hotkey ```javascript manager.unregisterHotkey('CommandOrControl+Shift+Space'); ``` ``` -------------------------------- ### FunASR Server - Python Speech Recognition Source: https://context7.com/yan5xu/ququ/llms.txt The FunASR server is a Python process that handles local speech recognition. It loads models, accepts JSON commands via stdin for transcription and status checks, and returns results via stdout. Dependencies include Python and the FunASR library. Input is audio file paths or commands; output is JSON with transcription results or status. ```python # funasr_server.py - Start server and process audio # The server initializes three models in parallel and responds with JSON python funasr_server.py --damo-root /path/to/models # Send transcription command via stdin (JSON format): { "action": "transcribe", "audio_path": "/tmp/audio.wav", "options": { "batch_size_s": 60, "use_vad": true, "use_punc": true, "language": "zh" } } # Server responds on stdout with result: { "success": true, "text": "优化后的文本内容", "raw_text": "原始识别文本", "confidence": 0.95, "duration": 3.5, "language": "zh-CN", "model_type": "pytorch" } # Check server status: {"action": "status"} # Response: {"success": true, "installed": true, "initialized": true, "models": {...}} # Get performance statistics: {"action": "stats"} # Response: {"success": true, "stats": {"transcription_count": 42, "total_audio_duration": 120.5}} # Graceful shutdown: {"action": "exit"} ``` -------------------------------- ### Clipboard Manager Source: https://context7.com/yan5xu/ququ/llms.txt Provides cross-platform clipboard operations and direct text insertion using accessibility APIs. It allows copying, reading, writing to the clipboard, pasting text via keyboard simulation, and direct text insertion on macOS. ```APIDOC ## Clipboard Manager - Text Insertion Cross-platform clipboard operations and direct text insertion using accessibility APIs. ### Copy Text to Clipboard ```javascript await manager.copyText("要复制的文本"); // Returns: { success: true } ``` ### Read Clipboard Content ```javascript const text = await manager.readClipboard(); // Returns: "clipboard content" ``` ### Write to Clipboard ```javascript await manager.writeClipboard("新的剪贴板内容"); ``` ### Paste Text (Keyboard Simulation) ```javascript await manager.pasteText("要粘贴的文本"); // Temporarily saves clipboard, sets new text, simulates Cmd+V/Ctrl+V, restores clipboard ``` ### Direct Text Insertion (macOS) ```javascript await manager.insertTextDirectly("直接插入的文本"); // Uses AppleScript with System Events for direct insertion without clipboard ``` ### Check Accessibility Permissions (macOS) ```javascript const hasPermission = await manager.checkAccessibilityPermissions(); // Returns: true/false ``` ### Enable macOS Accessibility ```javascript await manager.enableMacOSAccessibility(); // Opens System Preferences > Security & Privacy > Privacy > Accessibility ``` ### Open System Settings ```javascript manager.openSystemSettings(); // Opens appropriate system settings page for permissions ``` ``` -------------------------------- ### React Hook for Model Status Monitoring (JavaScript) Source: https://context7.com/yan5xu/ququ/llms.txt This React hook, `useModelStatus`, allows components to monitor the download and initialization status of FunASR models. It provides state variables for download progress, initialization status, model readiness, and errors, along with functions to trigger status checks and downloads. It's useful for providing real-time feedback to users during model loading processes. ```javascript import { useModelStatus } from './hooks/useModelStatus'; function ModelStatusComponent() { const { isDownloading, downloadProgress, isInitializing, modelReady, error, checkStatus, downloadModels } = useModelStatus(); const handleDownload = async () => { await downloadModels(); }; return (
{isDownloading && (
Downloading models: {downloadProgress.overall_progress}%
)} {isInitializing &&
Initializing models...
} {modelReady &&
✓ Models ready
} {error &&
Error: {error}
}
); } ``` -------------------------------- ### Model Download Script - Python Parallel Model Downloading Source: https://context7.com/yan5xu/ququ/llms.txt A Python script designed for downloading FunASR models in parallel. It utilizes the `modelscope` library and provides progress updates via JSON output to stdout. This script is essential for managing the large model files required by FunASR. Input is implicit (script execution); output is JSON-formatted progress and completion messages. ```python # download_models.py - Parallel model downloading import sys import json from modelscope import snapshot_download # Execute script (outputs JSON progress to stdout): # python download_models.py # Progress updates (JSON on stdout): { "stage": "downloading", "model": "asr", "progress": 45.5, "overall_progress": 30.2, "completed": 2, "total": 3 } # Completion message: { "success": true, "message": "所有模型下载完成", "models": ["asr", "vad", "punc"] } ``` -------------------------------- ### React Hook for System Permissions Management (JavaScript) Source: https://context7.com/yan5xu/ququ/llms.txt This React hook, `usePermissions`, simplifies the process of checking and requesting system permissions, specifically for microphone and accessibility features. It exposes boolean states indicating permission status and functions to trigger permission checks and requests. This hook is essential for applications that require access to sensitive user data or system-level functionalities. ```javascript import { usePermissions } from './hooks/usePermissions'; function PermissionsComponent() { const { hasMicrophonePermission, hasAccessibilityPermission, isCheckingPermissions, checkPermissions, requestMicrophonePermission, requestAccessibilityPermission } = usePermissions(); useEffect(() => { checkPermissions(); }, []); return (
Microphone: {hasMicrophonePermission ? '✓ Granted' : '✗ Denied'} {!hasMicrophonePermission && ( )}
Accessibility: {hasAccessibilityPermission ? '✓ Granted' : '✗ Denied'} {!hasAccessibilityPermission && ( )}
); } ``` -------------------------------- ### FunASR Manager - Node.js Integration for Speech Recognition Source: https://context7.com/yan5xu/ququ/llms.txt The FunASRManager is a Node.js class that integrates with the FunASR Python server. It handles server initialization, model management (checking status and downloading), and audio transcription. It communicates with the Python server via inter-process communication. Input is audio data (Uint8Array) and configuration options; output is a JSON object with transcription results. ```javascript const FunASRManager = require('./src/helpers/funasrManager'); const logger = console; // or custom logger const manager = new FunASRManager(logger); // Initialize at application startup (non-blocking) await manager.initializeAtStartup(); // Check FunASR installation status const status = await manager.checkFunASRInstallation(); // Returns: { installed: true, working: true } // Check if models are downloaded const modelStatus = await manager.checkModelFiles(); /* Returns: { success: true, models_downloaded: true, missing_models: [], details: { asr: { exists: true, path: "/path/to/model.pt", size: 880803840, complete: true }, vad: { exists: true, path: "/path/to/model.pt", size: 1677721, complete: true }, punc: { exists: true, path: "/path/to/model.pt", size: 291651584, complete: true } } } */ // Download models with progress tracking await manager.downloadModels((progress) => { console.log(`Stage: ${progress.stage}, Progress: ${progress.progress}%`); console.log(`Overall: ${progress.overall_progress}%`); console.log(`Model: ${progress.model}, Completed: ${progress.completed}/${progress.total}`); }); // Transcribe audio blob const audioBlob = new Uint8Array(wavFileBuffer); const result = await manager.transcribeAudio(audioBlob, { batch_size_s: 60, use_vad: true, use_punc: true }); /* Returns: { success: true, text: "这是优化后的文本内容。", raw_text: "这是 呃 优化后的 那个 文本内容", confidence: 0.95, language: "zh-CN" } */ // Check server status const serverStatus = await manager.checkStatus(); // Returns: { success: true, installed: true, initialized: true, models_downloaded: true } // Restart server after model download await manager.restartServer(); ``` -------------------------------- ### Clipboard Manager: Copy, Read, Write, Paste, and Insert Text (JavaScript) Source: https://context7.com/yan5xu/ququ/llms.txt Manages clipboard operations including copying text, reading content, writing new content, pasting using keyboard simulation, and direct text insertion via accessibility APIs. It also includes functions to check and enable macOS accessibility permissions. ```javascript const ClipboardManager = require('./src/helpers/clipboard'); const manager = new ClipboardManager(logger); // Copy text to clipboard const result = await manager.copyText("要复制的文本"); // Returns: { success: true } // Read clipboard content const text = await manager.readClipboard(); // Returns: "clipboard content" // Write to clipboard await manager.writeClipboard("新的剪贴板内容"); // Paste text using keyboard simulation (Cmd+V/Ctrl+V) await manager.pasteText("要粘贴的文本"); // Temporarily saves clipboard, sets new text, simulates Cmd+V, restores clipboard // Direct text insertion via accessibility API (macOS) await manager.insertTextDirectly("直接插入的文本"); // Uses AppleScript with System Events for direct insertion without clipboard // Check accessibility permissions (macOS only) const hasPermission = await manager.checkAccessibilityPermissions(); // Returns: true/false // Enable accessibility (opens System Preferences) await manager.enableMacOSAccessibility(); // Opens System Preferences > Security & Privacy > Privacy > Accessibility // Open system settings for manual permission grant manager.openSystemSettings(); // Opens appropriate system settings page for permissions ``` -------------------------------- ### Database Manager for Transcription Storage in JavaScript Source: https://context7.com/yan5xu/ququ/llms.txt Manages SQLite database operations for storing transcriptions, settings, and application state. It supports initializing the database, saving and retrieving transcriptions with metadata, searching, deleting, and retrieving statistics. The manager also handles key-value settings with JSON serialization and provides a function to clear all transcriptions. ```javascript const DatabaseManager = require('./src/helpers/database'); const db = new DatabaseManager(); // Initialize database (creates tables) db.initialize('/path/to/user/data'); // Save transcription with metadata const transcription = db.saveTranscription({ raw_text: "原始识别文本", processed_text: "AI优化后文本", audio_duration: 5.2, confidence: 0.95, language: "zh-CN", model: "gpt-3.5-turbo", processing_time: 1.5 }); // Returns: { id: 42, created_at: "2024-01-15T10:30:00.000Z", ... } // Retrieve transcriptions with pagination const transcriptions = db.getTranscriptions(20, 0); // limit=20, offset=0 /* Returns: [ { id: 42, raw_text: "原始文本", processed_text: "优化后文本", audio_duration: 5.2, created_at: "2024-01-15T10:30:00.000Z", confidence: 0.95 }, // ... more transcriptions ] */ // Search transcriptions by text content const results = db.searchTranscriptions("关键词", 10); // Get single transcription by ID const record = db.getTranscriptionById(42); // Delete transcription db.deleteTranscription(42); // Get statistics const stats = db.getTranscriptionStats(); /* Returns: { total: 500, total_duration: 3600.5, avg_confidence: 0.92, languages: { "zh-CN": 480, "en-US": 20 } } */ // Settings management (key-value with JSON serialization) db.setSetting('ai_api_key', 'sk-xxxxxxxx'); db.setSetting('ai_model', 'gpt-3.5-turbo'); db.setSetting('ai_base_url', 'https://api.openai.com/v1'); const apiKey = db.getSetting('ai_api_key', 'default-value'); const allSettings = db.getAllSettings(); /* Returns: { ai_api_key: "sk-xxxxxxxx", ai_model: "gpt-3.5-turbo", ai_base_url: "https://api.openai.com/v1", // ... other settings } */ // Clear all data db.clearAllTranscriptions(); ``` -------------------------------- ### IPC Handlers for AI Text Processing in JavaScript Source: https://context7.com/yan5xu/ququ/llms.txt Centralized IPC handlers for AI-powered text optimization using OpenAI-compatible APIs. These handlers facilitate communication between processes for tasks like text formatting, correction, optimization, and summarization. They also include functionality to check the AI service status and handle errors gracefully. The module relies on various managers like environment, database, clipboard, and window managers. ```javascript const IPCHandlers = require('./src/helpers/ipcHandlers'); // In main process (main.js): const ipcHandlers = new IPCHandlers({ environmentManager, databaseManager, clipboardManager, funasrManager, windowManager, hotkeyManager, logger }); // From renderer process - Process text with AI const result = await window.api.processText("这是呃原始文本那个", "optimize"); /* Returns: { success: true, text: "这是原始文本。", usage: { prompt_tokens: 150, completion_tokens: 20, total_tokens: 170 }, model: "gpt-3.5-turbo" } */ // Different processing modes: await window.api.processText(text, "format"); // Format with paragraphs await window.api.processText(text, "correct"); // Correct errors only await window.api.processText(text, "optimize"); // Remove fillers, fix mistakes await window.api.processText(text, "optimize_long"); // Long text with paragraphing await window.api.processText(text, "summarize"); // Summarize content await window.api.processText(text, "enhance"); // Deep optimization // Check AI status with test configuration const aiStatus = await window.api.checkAIStatus({ ai_api_key: "sk-xxx", ai_base_url: "https://api.openai.com/v1", ai_model: "gpt-3.5-turbo" }); /* Returns: { available: true, model: "gpt-3.5-turbo", status: "connected", response: "测试成功", usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }, details: "成功连接到 gpt-3.5-turbo,响应时间正常" } */ // Error handling example: const errorResult = await window.api.checkAIStatus({ ai_api_key: "invalid-key", ai_base_url: "https://api.openai.com/v1" }); /* Returns: { available: false, error: "API密钥无效或已过期", details: "测试失败原因: 401 Unauthorized" } */ ``` -------------------------------- ### Text Processing Hook - AI Integration Source: https://context7.com/yan5xu/ququ/llms.txt A React hook for processing transcribed text using AI models. It allows users to send raw text to the AI for various processing modes like optimization, formatting, correction, summarization, and enhancement. ```APIDOC ## Text Processing Hook - AI Integration React hook for processing transcribed text with AI models. ### Hook Usage ```javascript import { useTextProcessing } from './hooks/useTextProcessing'; function TextProcessor() { const { processedText, isProcessing, error, processText, clearError } = useTextProcessing(); const handleProcess = async (rawText) => { // Process with different modes await processText(rawText, 'optimize'); // or: 'format', 'correct', 'summarize', 'enhance', 'optimize_long' }; return (
{isProcessing &&
Processing...
} {error &&
Error: {error}
} {processedText &&
{processedText}
}
); } ``` ### Available States and Methods - `processedText` (string): The AI-processed text. - `isProcessing` (boolean): Indicates if text processing is currently underway. - `error` (string): An error message if processing fails. - `processText(text: string, mode: string)`: Initiates text processing with the given text and mode. Supported modes include: `'optimize'`, `'format'`, `'correct'`, `'summarize'`, `'enhance'`, `'optimize_long'`. - `clearError()`: Clears any existing error message. ``` -------------------------------- ### Text Processing Hook: AI Integration (JavaScript) Source: https://context7.com/yan5xu/ququ/llms.txt A React hook designed for processing transcribed text using AI models. It allows users to input raw text and select various processing modes like optimization, formatting, correction, summarization, enhancement, and long-form optimization. It manages the processing state and displays results or errors. ```javascript import { useTextProcessing } from './hooks/useTextProcessing'; function TextProcessor() { const { processedText, isProcessing, error, processText, clearError } = useTextProcessing(); const handleProcess = async (rawText) => { // Process with different modes await processText(rawText, 'optimize'); // or: 'format', 'correct', 'summarize', 'enhance', 'optimize_long' }; return (
{isProcessing &&
Processing...
} {error &&
Error: {error}
} {processedText &&
{processedText}
}
); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.