Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
fixed chunking logic
Murtaza Nasir17beb8b81f65
diff --git a/app.py b/app.pyindex 0f241379..4b937e05 100644--- a/app.py+++ b/app.py@@ -1305,7 +1305,7 @@ def transcribe_with_chunking(app_context, recording_id, filepath, filename_for_aapi_key=transcription_api_key,base_url=transcription_base_url,http_client=http_client_with_timeout,- max_retries=2, # Limit retries to avoid excessive delays+ max_retries=3, # Increased retries for better reliabilitytimeout=300.0 # 5 minute timeout for API calls)whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")@@ -3025,43 +3025,61 @@ def upload_file():file.save(filepath)app.logger.info(f"File saved to {filepath}")- # --- Convert non-wav/mp3/flac files to WAV ---+ # --- Convert files only when chunking is needed ---filename_lower = original_filename.lower()- supported_formats = ('.wav', '.mp3', '.flac')- convertible_formats = ('.amr', '.3gp', '.3gpp', '.m4a', '.aac', '.ogg', '.wma', '.webm')- if not filename_lower.endswith(supported_formats):+ # Check if chunking will be needed for this file+ needs_chunking_for_processing = (chunking_service and+ ENABLE_CHUNKING and+ not USE_ASR_ENDPOINT and+ original_file_size > (25 * 1024 * 1024)) # 25MB threshold++ # Define supported formats based on whether chunking is needed+ if needs_chunking_for_processing:+ # For chunking: only support formats that work well with chunking+ supported_formats = ('.wav', '.mp3', '.flac')+ convertible_formats = ('.amr', '.3gp', '.3gpp', '.m4a', '.aac', '.ogg', '.wma', '.webm')+ else:+ # For direct transcription: support WebM and other formats directly+ supported_formats = ('.wav', '.mp3', '.flac', '.webm', '.m4a', '.aac', '.ogg')+ convertible_formats = ('.amr', '.3gp', '.3gpp', '.wma')++ # Only convert if file is not in supported formats AND chunking is needed+ if not filename_lower.endswith(supported_formats) and needs_chunking_for_processing:if filename_lower.endswith(convertible_formats):- app.logger.info(f"Converting {filename_lower} format to WAV for processing.")+ app.logger.info(f"Converting {filename_lower} format to 32kbps MP3 for chunking processing.")else:- app.logger.info(f"Attempting to convert unknown format ({filename_lower}) to WAV.")+ app.logger.info(f"Attempting to convert unknown format ({filename_lower}) to 32kbps MP3 for chunking.")base_filepath, _ = os.path.splitext(filepath)- temp_wav_filepath = f"{base_filepath}_temp.wav"- wav_filepath = f"{base_filepath}.wav"+ temp_mp3_filepath = f"{base_filepath}_temp.mp3"+ mp3_filepath = f"{base_filepath}.mp3"try:- # Using -acodec pcm_s16le for standard WAV format, 16kHz sample rate, mono+ # Convert to 32kbps MP3 for optimal size/quality balancesubprocess.run(- ['ffmpeg', '-i', filepath, '-y', '-acodec', 'pcm_s16le', '-ar', '16000', '-ac', '1', temp_wav_filepath],+ ['ffmpeg', '-i', filepath, '-y', '-acodec', 'mp3', '-ab', '32k', '-ar', '16000', '-ac', '1', temp_mp3_filepath],check=True, capture_output=True, text=True)- app.logger.info(f"Successfully converted {filepath} to {temp_wav_filepath}")+ app.logger.info(f"Successfully converted {filepath} to {temp_mp3_filepath} (32kbps MP3)")- # If the original file is not the same as the final wav file, remove it- if filepath.lower() != wav_filepath.lower():+ # If the original file is not the same as the final mp3 file, remove it+ if filepath.lower() != mp3_filepath.lower():os.remove(filepath)# Rename the temporary file to the final filename- os.rename(temp_wav_filepath, wav_filepath)+ os.rename(temp_mp3_filepath, mp3_filepath)- filepath = wav_filepath+ filepath = mp3_filepathexcept FileNotFoundError:app.logger.error("ffmpeg command not found. Please ensure ffmpeg is installed and in the system's PATH.")return jsonify({'error': 'Audio conversion tool (ffmpeg) not found on server.'}), 500except subprocess.CalledProcessError as e:app.logger.error(f"ffmpeg conversion failed for {filepath}: {e.stderr}")return jsonify({'error': f'Failed to convert audio file: {e.stderr}'}), 500+ elif not filename_lower.endswith(supported_formats):+ # File is not supported and chunking is not needed - log but don't convert+ app.logger.info(f"File format {filename_lower} will be processed directly without conversion (chunking not needed)")# Get final file size (of original or converted file)final_file_size = os.path.getsize(filepath)diff --git a/audio_chunking.py b/audio_chunking.pyindex 3b96c2eb..c3ab0954 100644--- a/audio_chunking.py+++ b/audio_chunking.py@@ -95,17 +95,18 @@ class AudioChunkingService:wav_filename = f"{base_name}_converted.wav"wav_path = os.path.join(temp_dir, wav_filename)- # Convert to WAV using the same settings we use for chunks+ # Convert to 32kbps MP3 using the same settings we use for chunkscmd = ['ffmpeg', '-i', file_path,- '-acodec', 'pcm_s16le',+ '-acodec', 'mp3',+ '-ab', '32k','-ar', '16000','-ac', '1','-y', # Overwrite output filewav_path]- logger.info(f"Converting {file_path} to WAV format for accurate chunking...")+ logger.info(f"Converting {file_path} to 32kbps MP3 format for accurate chunking...")result = subprocess.run(cmd, capture_output=True, text=True)if result.returncode != 0:raise ValueError(f"ffmpeg conversion failed: {result.stderr}")@@ -142,21 +143,23 @@ class AudioChunkingService:# Calculate actual bitrate from the WAV filebitrate_bytes_per_sec = wav_size / wav_duration- # Calculate chunk duration to stay under size limit with safety margin- safety_factor = 0.9 # Use 90% of max size for safety- target_chunk_size = self.max_chunk_size_bytes * safety_factor+ # Use a more aggressive target to create larger chunks+ # Target 22MB chunks (88% of 25MB limit) for better efficiency+ safety_factor = 0.88 # Use 88% of max size for optimal efficiency+ target_chunk_size = 25 * 1024 * 1024 * safety_factor # Target 22MB chunkschunk_duration = (target_chunk_size / bitrate_bytes_per_sec) - self.overlap_seconds- # Ensure reasonable chunk size (minimum 60 seconds, maximum 20 minutes)- chunk_duration = max(60, min(1200, chunk_duration))+ # Ensure reasonable chunk size (minimum 5 minutes, maximum 45 minutes)+ # Larger minimum for better efficiency, larger maximum for fewer chunks+ chunk_duration = max(300, min(2700, chunk_duration))- logger.info(f"Calculated chunk duration: {chunk_duration:.1f}s based on WAV bitrate {bitrate_bytes_per_sec:.0f} bytes/sec")+ logger.info(f"Calculated chunk duration: {chunk_duration:.1f}s (target: {target_chunk_size/1024/1024:.1f}MB) based on bitrate {bitrate_bytes_per_sec:.0f} bytes/sec")return chunk_durationexcept Exception as e:logger.error(f"Error calculating chunk duration from WAV: {e}")- return 300 # Default 5 minutes+ return 600 # Default 10 minutes (increased from 5)def create_chunks(self, file_path: str, temp_dir: str) -> List[Dict[str, Any]]:"""diff --git a/static/js/app.js b/static/js/app.jsindex 1ea5f9fb..2ea0a4f5 100644--- a/static/js/app.js+++ b/static/js/app.js@@ -79,6 +79,14 @@ document.addEventListener('DOMContentLoaded', () => {const animationFrameId = ref(null);const recordingMode = ref('microphone'); // 'microphone', 'system', or 'both'const activeStreams = ref([]); // Track active streams for cleanup++ // --- Recording Size Monitoring ---+ const estimatedFileSize = ref(0);+ const fileSizeWarningShown = ref(false);+ const recordingQuality = ref('optimized'); // 'optimized', 'standard', 'high'+ const actualBitrate = ref(0);+ const maxRecordingMB = ref(200); // Maximum recording size before auto-stop+ const sizeCheckInterval = ref(null);// --- Modal State ---const showEditModal = ref(false);@@ -716,6 +724,53 @@ document.addEventListener('DOMContentLoaded', () => {return parts.join(' ');};+ // --- Recording Size Monitoring Functions ---+ const updateFileSizeEstimate = () => {+ if (!isRecording.value || !actualBitrate.value) return;++ // Calculate estimated size based on recording time and bitrate+ const recordingTimeSeconds = recordingTime.value;+ const estimatedBits = actualBitrate.value * recordingTimeSeconds;+ const estimatedBytes = estimatedBits / 8;+ estimatedFileSize.value = estimatedBytes;++ // Check if we're approaching the size limit+ const sizeMB = estimatedBytes / (1024 * 1024);+ const warningThresholdMB = maxRecordingMB.value * 0.8; // 80% of max size++ if (sizeMB > warningThresholdMB && !fileSizeWarningShown.value) {+ fileSizeWarningShown.value = true;+ showToast(`Recording size is ${formatFileSize(estimatedBytes)}. Consider stopping soon to avoid auto-stop at ${maxRecordingMB.value}MB.`, 'fa-exclamation-triangle', 5000);+ }++ // Auto-stop if we exceed the maximum size+ if (sizeMB > maxRecordingMB.value) {+ console.log(`Auto-stopping recording: size ${formatFileSize(estimatedBytes)} exceeds limit of ${maxRecordingMB.value}MB`);+ stopRecording();+ showToast(`Recording automatically stopped at ${formatFileSize(estimatedBytes)} to prevent excessive file size.`, 'fa-stop-circle', 7000);+ }+ };++ const startSizeMonitoring = () => {+ if (sizeCheckInterval.value) {+ clearInterval(sizeCheckInterval.value);+ }++ // Reset size monitoring state+ estimatedFileSize.value = 0;+ fileSizeWarningShown.value = false;++ // Start monitoring every 5 seconds+ sizeCheckInterval.value = setInterval(updateFileSizeEstimate, 5000);+ };++ const stopSizeMonitoring = () => {+ if (sizeCheckInterval.value) {+ clearInterval(sizeCheckInterval.value);+ sizeCheckInterval.value = null;+ }+ };+// --- Enhanced Date Utility Functions ---const getDateForSorting = (recording) => {const dateStr = sortBy.value === 'meeting_date' ? recording.meeting_date : recording.created_at;@@ -2000,29 +2055,52 @@ document.addEventListener('DOMContentLoaded', () => {// Combine streams if we have bothif (micStream && systemStream) {- audioContext.value = new (window.AudioContext || window.webkitAudioContext)();-- const micSource = audioContext.value.createMediaStreamSource(micStream);- const systemSource = audioContext.value.createMediaStreamSource(systemStream);- const destination = audioContext.value.createMediaStreamDestination();-- micSource.connect(destination);- systemSource.connect(destination);-- // The destination stream contains the mixed audio- combinedStream = destination.stream;-- // We also need to add the video track from the system stream to keep the browser's "sharing this screen" UI active.- // This video track will not be recorded.- const videoTrack = systemStream.getVideoTracks()[0];- if (videoTrack) {- combinedStream.addTrack(videoTrack);+ try {+ audioContext.value = new (window.AudioContext || window.webkitAudioContext)();++ const micSource = audioContext.value.createMediaStreamSource(micStream);+ const systemSource = audioContext.value.createMediaStreamSource(systemStream);+ const destination = audioContext.value.createMediaStreamDestination();++ micSource.connect(destination);+ systemSource.connect(destination);++ // Create a new MediaStream with only the audio track from the destination+ const mixedAudioTrack = destination.stream.getAudioTracks()[0];+ if (!mixedAudioTrack) {+ throw new Error('Failed to create mixed audio track');+ }++ combinedStream = new MediaStream([mixedAudioTrack]);++ // Verify the stream has audio tracks+ if (combinedStream.getAudioTracks().length === 0) {+ throw new Error('Combined stream has no audio tracks');+ }++ console.log('Successfully created combined audio stream with', combinedStream.getAudioTracks().length, 'audio tracks');+ showToast('Recording both microphone and system audio', 'fa-microphone');++ } catch (error) {+ console.error('Failed to combine audio streams:', error);+ // Fallback to system audio only+ if (audioContext.value) {+ audioContext.value.close().catch(e => console.error("Error closing AudioContext:", e));+ audioContext.value = null;+ }+ combinedStream = systemStream;+ showToast('Failed to combine audio, using system audio only', 'fa-exclamation-triangle');}-- showToast('Recording both microphone and system audio', 'fa-microphone');} else if (systemStream) {- combinedStream = systemStream;- showToast('Recording system audio only', 'fa-desktop');+ // For system audio only, create a new stream with just the audio tracks+ const audioTracks = systemStream.getAudioTracks();+ if (audioTracks.length > 0) {+ combinedStream = new MediaStream(audioTracks);+ console.log('Created system audio stream with', audioTracks.length, 'audio tracks');+ showToast('Recording system audio only', 'fa-desktop');+ } else {+ throw new Error('System stream has no audio tracks');+ }} else if (micStream) {combinedStream = micStream;showToast('Recording microphone only', 'fa-microphone');@@ -2037,49 +2115,108 @@ document.addEventListener('DOMContentLoaded', () => {// Best option: Opus codec at 32kbps (excellent compression for speech){mimeType: 'audio/webm;codecs=opus',- audioBitsPerSecond: 32000+ audioBitsPerSecond: 32000,+ description: 'Optimized (32kbps Opus)'},- // Fallback 1: Opus at 64kbps (slightly higher quality)+ // Good option: Opus at 64kbps (slightly higher quality){mimeType: 'audio/webm;codecs=opus',- audioBitsPerSecond: 64000+ audioBitsPerSecond: 64000,+ description: 'Good quality (64kbps Opus)'},- // Fallback 2: WebM with reduced bitrate+ // Fallback 1: WebM with reduced bitrate{mimeType: 'audio/webm',- audioBitsPerSecond: 48000+ audioBitsPerSecond: 64000,+ description: 'Standard WebM (64kbps)'},- // Fallback 3: MP4 with reduced bitrate+ // Fallback 2: MP4 with reduced bitrate{mimeType: 'audio/mp4',- audioBitsPerSecond: 48000+ audioBitsPerSecond: 64000,+ description: 'Standard MP4 (64kbps)'+ },+ // Fallback 3: Just the codec without bitrate+ {+ mimeType: 'audio/webm;codecs=opus',+ description: 'Opus codec (default bitrate)'+ },+ // Fallback 4: Just WebM without bitrate+ {+ mimeType: 'audio/webm',+ description: 'WebM (default bitrate)'}];// Test each option to find the first supported onefor (const options of optionsList) {if (MediaRecorder.isTypeSupported(options.mimeType)) {- console.log(`Using optimized audio recording: ${options.mimeType} at ${options.audioBitsPerSecond}bps`);- showToast('Recording optimized for transcription', 'fa-compress-alt');+ console.log(`Testing audio recording option: ${options.description} - ${options.mimeType}`);return options;}}// Final fallback: no options (browser default)console.log('Using browser default audio recording settings');- showToast('Recording with default quality', 'fa-microphone');- return undefined;+ return null;};- const recorderOptions = getOptimizedRecorderOptions();- mediaRecorder.value = recorderOptions- ? new MediaRecorder(combinedStream, recorderOptions)- : new MediaRecorder(combinedStream);+ // Try to create MediaRecorder with progressive fallbacks+ let mediaRecorderCreated = false;+ let recorderOptions = getOptimizedRecorderOptions();+ let attemptCount = 0;++ while (!mediaRecorderCreated && attemptCount < 5) {+ try {+ attemptCount++;++ if (recorderOptions && attemptCount === 1) {+ // First attempt: try with full options+ console.log(`Attempt ${attemptCount}: Trying ${recorderOptions.description}`);+ mediaRecorder.value = new MediaRecorder(combinedStream, recorderOptions);+ actualBitrate.value = recorderOptions.audioBitsPerSecond || 64000;+ showToast(`Recording: ${recorderOptions.description}`, 'fa-compress-alt', 3000);+ } else if (recorderOptions && attemptCount === 2 && recorderOptions.audioBitsPerSecond) {+ // Second attempt: try same mime type without bitrate constraint+ console.log(`Attempt ${attemptCount}: Trying ${recorderOptions.mimeType} without bitrate`);+ mediaRecorder.value = new MediaRecorder(combinedStream, { mimeType: recorderOptions.mimeType });+ actualBitrate.value = 128000; // Estimate+ showToast(`Recording: ${recorderOptions.mimeType} (default bitrate)`, 'fa-compress-alt', 3000);+ } else {+ // Final attempt: browser default+ console.log(`Attempt ${attemptCount}: Using browser default`);+ mediaRecorder.value = new MediaRecorder(combinedStream);+ actualBitrate.value = 128000; // Estimate browser default+ showToast('Recording with browser default settings', 'fa-microphone', 3000);+ }++ mediaRecorderCreated = true;+ console.log(`MediaRecorder created successfully on attempt ${attemptCount}`);++ } catch (error) {+ console.warn(`MediaRecorder creation attempt ${attemptCount} failed:`, error);+ mediaRecorder.value = null;++ if (attemptCount >= 5) {+ throw new Error(`Failed to create MediaRecorder after ${attemptCount} attempts. Last error: ${error.message}`);+ }+ }+ }++ if (!mediaRecorder.value) {+ throw new Error('Failed to create MediaRecorder with any configuration');+ }++ console.log(`Recording with estimated bitrate: ${actualBitrate.value} bps`);+mediaRecorder.value.ondataavailable = event => audioChunks.value.push(event.data);mediaRecorder.value.onstop = () => {const audioBlob = new Blob(audioChunks.value, { type: 'audio/webm' });audioBlobURL.value = URL.createObjectURL(audioBlob);+ // Stop size monitoring+ stopSizeMonitoring();+// Stop all active streamsactiveStreams.value.forEach(stream => {stream.getTracks().forEach(track => track.stop());@@ -2128,6 +2265,9 @@ document.addEventListener('DOMContentLoaded', () => {recordingTime.value = 0;recordingInterval.value = setInterval(() => recordingTime.value++, 1000);+ // Start size monitoring+ startSizeMonitoring();+// Switch to recording viewcurrentView.value = 'recording';@@ -2152,6 +2292,7 @@ document.addEventListener('DOMContentLoaded', () => {if (mediaRecorder.value && isRecording.value) {mediaRecorder.value.stop();isRecording.value = false;+ stopSizeMonitoring();cancelAnimationFrame(animationFrameId.value);animationFrameId.value = null;}diff --git a/templates/index.html b/templates/index.htmlindex efb1d2ca..c1c44f4a 100644--- a/templates/index.html+++ b/templates/index.html@@ -392,6 +392,22 @@<div><div class="text-2xl font-mono text-[var(--text-accent)]">${formatTime(recordingTime)}</div><p class="text-sm text-[var(--text-muted)]">${ isRecording ? 'Recording in progress...' : 'Recording finished' }</p>+ <!-- Real-time file size display -->+ <div v-if="isRecording && estimatedFileSize > 0" class="mt-2">+ <p class="text-xs text-[var(--text-muted)]">+ Estimated size: <span class="font-mono">${formatFileSize(estimatedFileSize)}</span>+ <span v-if="actualBitrate > 0" class="ml-2">+ (${Math.round(actualBitrate / 1000)}kbps)+ </span>+ </p>+ <!-- Size warning indicator -->+ <div v-if="estimatedFileSize > (maxRecordingMB * 1024 * 1024 * 0.8)" class="mt-1">+ <div class="flex items-center text-xs text-amber-600 dark:text-amber-400">+ <i class="fas fa-exclamation-triangle mr-1"></i>+ <span>Approaching ${maxRecordingMB}MB limit</span>+ </div>+ </div>+ </div></div></div>