Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Add user-friendly error display and prevent operations on failed transcriptions

Murtaza Nasir16fce4dc115b
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 794d1c6b..17327a6e 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -579,6 +579,10 @@ def generate_summary_endpoint(recording_id):
if not recording.transcription or len(recording.transcription.strip()) < 10:
return jsonify({'error': 'No valid transcription available for summary generation'}), 400
+ # Check if transcription is an error message (not actual content)
+ if is_transcription_error(recording.transcription):
+ return jsonify({'error': 'Cannot generate summary: transcription failed. Please reprocess the transcription first.'}), 400
+
# Check if already processing
if recording.status in ['PROCESSING', 'SUMMARIZING']:
return jsonify({'error': 'Recording is already being processed'}), 400
@@ -1159,6 +1163,10 @@ def reprocess_summary(recording_id):
if not recording.transcription or len(recording.transcription.strip()) < 10:
return jsonify({'error': 'No valid transcription available for summary generation'}), 400
+ # Check if transcription is an error message (not actual content)
+ if is_transcription_error(recording.transcription):
+ return jsonify({'error': 'Cannot generate summary: transcription failed. Please reprocess the transcription first.'}), 400
+
# Check if already processing
if recording.status in ['PROCESSING', 'SUMMARIZING']:
return jsonify({'error': 'Recording is already being processed'}), 400
@@ -2760,6 +2768,14 @@ def chat_with_transcription():
if not has_recording_access(recording, current_user):
return jsonify({'error': 'You do not have permission to chat with this recording'}), 403
+ # Check if transcription exists
+ if not recording.transcription or len(recording.transcription.strip()) < 10:
+ return jsonify({'error': 'No transcription available for this recording'}), 400
+
+ # Check if transcription is an error message (not actual content)
+ if is_transcription_error(recording.transcription):
+ return jsonify({'error': 'Cannot chat: transcription failed. Please reprocess the transcription first.'}), 400
+
# Check if chat client is available
if chat_client is None:
return jsonify({'error': 'Chat service is not available (chat client not configured)'}), 503
diff --git a/src/services/job_queue.py b/src/services/job_queue.py
index 50fbf8ad..7703581f 100644
--- a/src/services/job_queue.py
+++ b/src/services/job_queue.py
@@ -240,6 +240,52 @@ class FairJobQueue:
db.session.rollback()
return None
+ def _is_permanent_error(self, error_str: str) -> bool:
+ """
+ Detect if an error is permanent and should not be retried.
+
+ Permanent errors include:
+ - 413: File too large (user needs to enable chunking or compress file)
+ - 401/403: Authentication/authorization errors (credentials issue)
+ - 402: Payment required (billing issue)
+ - 404: Resource not found (model doesn't exist)
+ - Invalid format errors (file needs to be converted)
+ """
+ error_lower = error_str.lower()
+
+ # HTTP status codes that indicate permanent errors
+ permanent_codes = ['413', '401', '402', '403']
+ for code in permanent_codes:
+ if f'error code: {code}' in error_lower or f'status {code}' in error_lower:
+ return True
+
+ # Specific error patterns that are permanent
+ permanent_patterns = [
+ 'maximum content size limit',
+ 'file too large',
+ 'payload too large',
+ 'invalid api key',
+ 'incorrect api key',
+ 'authentication failed',
+ 'unauthorized',
+ 'permission denied',
+ 'access denied',
+ 'billing',
+ 'payment required',
+ 'quota exceeded',
+ 'insufficient funds',
+ 'model.*not found',
+ 'invalid model',
+ 'unsupported.*format',
+ 'invalid.*file.*format',
+ ]
+
+ for pattern in permanent_patterns:
+ if pattern in error_lower:
+ return True
+
+ return False
+
def _process_job(self, job):
"""Process a single job by dispatching to the appropriate task function."""
job_id = job.id
@@ -289,15 +335,20 @@ class FairJobQueue:
logger.info(f"Job {job_id} completed successfully")
except Exception as e:
+ error_str = str(e)
logger.error(f"Job {job_id} failed: {e}", exc_info=True)
+ # Check if this is a permanent error that shouldn't be retried
+ is_permanent_error = self._is_permanent_error(error_str)
+
# Re-fetch job to update it
job = db.session.get(ProcessingJob, job_id)
if job:
- job.error_message = str(e)
+ job.error_message = error_str
job.retry_count += 1
- if job.retry_count < MAX_RETRIES:
+ # Only retry if: not a permanent error AND under retry limit
+ if not is_permanent_error and job.retry_count < MAX_RETRIES:
# Re-queue for retry
job.status = 'queued'
job.started_at = None
@@ -307,8 +358,15 @@ class FairJobQueue:
job.completed_at = datetime.utcnow()
recording = db.session.get(Recording, recording_id)
- if is_new_upload and recording:
- # For failed new uploads, delete the recording and file
+ if is_permanent_error:
+ logger.info(f"Job {job_id} failed with permanent error (no retry): {error_str[:100]}")
+
+ # For permanent errors (like file too large), keep the recording so user can fix settings
+ # Only delete recordings for transient errors that failed after all retries
+ should_delete = is_new_upload and recording and not is_permanent_error
+
+ if should_delete:
+ # For failed new uploads with transient errors, delete the recording and file
logger.info(f"Deleting failed new upload: recording {recording_id}")
try:
# Delete the audio file
@@ -322,11 +380,16 @@ class FairJobQueue:
except Exception as delete_err:
logger.error(f"Error deleting failed upload recording: {delete_err}")
elif recording:
- # For reprocessing failures, just mark as failed
+ # Keep the recording with FAILED status so user can see the error and fix settings
recording.status = 'FAILED'
- recording.error_message = str(e)
+ # Format the error for nice display
+ from src.utils.error_formatting import format_error_for_storage
+ recording.transcription = format_error_for_storage(error_str)
- logger.error(f"Job {job_id} failed permanently after {MAX_RETRIES} retries")
+ if is_permanent_error:
+ logger.error(f"Job {job_id} failed permanently (non-retryable error)")
+ else:
+ logger.error(f"Job {job_id} failed permanently after {MAX_RETRIES} retries")
db.session.commit()
diff --git a/src/services/transcription/registry.py b/src/services/transcription/registry.py
index 50db5cb0..a314862f 100644
--- a/src/services/transcription/registry.py
+++ b/src/services/transcription/registry.py
@@ -134,17 +134,18 @@ class ConnectorRegistry:
transcription_model = os.environ.get('TRANSCRIPTION_MODEL', '').lower()
whisper_model = os.environ.get('WHISPER_MODEL', '').lower()
- # Priority 2: ASR endpoint - check ASR_BASE_URL directly (smarter than flag)
- if asr_base_url:
- connector_name = 'asr_endpoint'
- logger.info("Auto-detected ASR endpoint from ASR_BASE_URL")
- elif use_asr_flag:
- # Backwards compat: USE_ASR_ENDPOINT flag still works
- connector_name = 'asr_endpoint'
+ # Deprecation warning for legacy USE_ASR_ENDPOINT flag
+ if use_asr_flag:
logger.warning(
"USE_ASR_ENDPOINT=true is deprecated. "
"Set ASR_BASE_URL instead for auto-detection, or use TRANSCRIPTION_CONNECTOR=asr_endpoint"
)
+
+ # Priority 2: ASR endpoint - check ASR_BASE_URL or legacy flag
+ if asr_base_url or use_asr_flag:
+ connector_name = 'asr_endpoint'
+ if asr_base_url:
+ logger.info("Auto-detected ASR endpoint from ASR_BASE_URL")
# Priority 3: Model-based detection
elif transcription_model and 'gpt-4o' in transcription_model:
connector_name = 'openai_transcribe'
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 8871e360..253f0f23 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -27,6 +27,7 @@ from src.services.llm import is_using_openai_api, call_llm_completion, format_ap
from src.utils import extract_json_object, safe_json_loads
from src.utils.ffprobe import get_codec_info, is_video_file, is_lossless_audio, FFProbeError
from src.utils.ffmpeg_utils import convert_to_mp3, extract_audio_from_video as ffmpeg_extract_audio, compress_audio, FFmpegError, FFmpegNotFoundError
+from src.utils.error_formatting import format_error_for_storage
from src.config.app_config import AUDIO_COMPRESS_UPLOADS, AUDIO_CODEC, AUDIO_BITRATE
from src.audio_chunking import AudioChunkingService, ChunkProcessingError, ChunkingNotSupportedError
from src.config.app_config import (
@@ -996,6 +997,118 @@ def compress_lossless_audio(filepath, codec='mp3', bitrate='128k', codec_info=No
raise
+def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, language):
+ """
+ Transcribe a large audio file using chunking with the connector architecture.
+
+ This is used when the connector doesn't handle chunking internally (e.g., OpenAI Whisper)
+ and the file exceeds the configured chunk limit.
+
+ Args:
+ connector: The transcription connector to use
+ filepath: Path to the audio file
+ filename: Original filename for logging
+ mime_type: MIME type of the audio file
+ language: Optional language code
+
+ Returns:
+ Merged transcription text
+ """
+ import tempfile
+ from src.services.transcription import TranscriptionRequest
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ try:
+ # Create chunks
+ current_app.logger.info(f"Creating chunks for large file: {filepath}")
+ chunks = chunking_service.create_chunks(filepath, temp_dir)
+
+ if not chunks:
+ raise ChunkProcessingError("No chunks were created from the audio file")
+
+ current_app.logger.info(f"Created {len(chunks)} chunks, processing each with connector...")
+
+ # Process each chunk
+ chunk_results = []
+
+ for i, chunk in enumerate(chunks):
+ max_retries = 3
+ retry_count = 0
+ success = False
+
+ while retry_count < max_retries and not success:
+ try:
+ retry_suffix = f" (retry {retry_count + 1}/{max_retries})" if retry_count > 0 else ""
+ current_app.logger.info(f"Processing chunk {i+1}/{len(chunks)}: {chunk['filename']} ({chunk['size_mb']:.1f}MB){retry_suffix}")
+
+ # Transcribe chunk using connector
+ with open(chunk['path'], 'rb') as chunk_file:
+ request = TranscriptionRequest(
+ audio_file=chunk_file,
+ filename=chunk['filename'],
+ mime_type='audio/mpeg', # Chunks are always MP3
+ language=language,
+ diarize=False # Chunking doesn't support diarization
+ )
+
+ response = connector.transcribe(request)
+
+ # Store chunk result
+ chunk_result = {
+ 'index': chunk['index'],
+ 'start_time': chunk['start_time'],
+ 'end_time': chunk['end_time'],
+ 'duration': chunk['duration'],
+ 'size_mb': chunk['size_mb'],
+ 'transcription': response.text,
+ 'filename': chunk['filename']
+ }
+ chunk_results.append(chunk_result)
+ current_app.logger.info(f"Chunk {i+1} transcribed successfully: {len(response.text)} characters")
+ success = True
+
+ except Exception as chunk_error:
+ retry_count += 1
+ error_msg = str(chunk_error)
+
+ if retry_count < max_retries:
+ wait_time = 15 if "timeout" not in error_msg.lower() else 30
+ current_app.logger.warning(f"Chunk {i+1} failed (attempt {retry_count}/{max_retries}): {chunk_error}. Retrying in {wait_time}s...")
+ time.sleep(wait_time)
+ else:
+ current_app.logger.error(f"Chunk {i+1} failed after {max_retries} attempts: {chunk_error}")
+ chunk_result = {
+ 'index': chunk['index'],
+ 'start_time': chunk['start_time'],
+ 'end_time': chunk['end_time'],
+ 'transcription': f"[Chunk {i+1} transcription failed: {str(chunk_error)}]",
+ 'filename': chunk['filename']
+ }
+ chunk_results.append(chunk_result)
+
+ # Small delay between chunks
+ if i < len(chunks) - 1:
+ time.sleep(2)
+
+ # Merge transcriptions
+ current_app.logger.info(f"Merging {len(chunk_results)} chunk transcriptions...")
+ merged_transcription = chunking_service.merge_transcriptions(chunk_results)
+
+ if not merged_transcription.strip():
+ raise ChunkProcessingError("Merged transcription is empty")
+
+ # Log statistics
+ chunking_service.log_processing_statistics(chunk_results)
+
+ return merged_transcription
+
+ except Exception as e:
+ current_app.logger.error(f"Chunking transcription failed for {filepath}: {e}")
+ if 'chunks' in locals():
+ chunking_service.cleanup_chunks(chunks)
+ raise ChunkProcessingError(f"Chunked transcription failed: {str(e)}")
+
+
def transcribe_with_connector(app_context, recording_id, filepath, original_filename, start_time, mime_type=None, language=None, diarize=None, min_speakers=None, max_speakers=None, tag_id=None):
"""
Transcribe audio using the new connector-based architecture.
@@ -1078,7 +1191,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
recording.status = 'FAILED'
recording.error_msg = f"Audio extraction failed: {str(e)}"
db.session.commit()
- return
+ raise # Re-raise so job queue marks the job as failed
# Determine if we should diarize
if diarize is None:
@@ -1091,35 +1204,59 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
current_app.logger.warning(f"Diarization requested but connector '{connector_name}' doesn't support it")
should_diarize = False
- # Build the transcription request
- with open(actual_filepath, 'rb') as audio_file:
- request = TranscriptionRequest(
- audio_file=audio_file,
- filename=actual_filename,
- mime_type=actual_content_type,
- language=language,
- diarize=should_diarize,
- min_speakers=min_speakers,
- max_speakers=max_speakers
+ # Check if chunking is needed for large files
+ # The chunking service respects this priority:
+ # 1. Connector handles internally (e.g., ASR endpoint) → no app-level chunking
+ # 2. User's ENABLE_CHUNKING=false → no chunking
+ # 3. User's CHUNK_LIMIT setting → use their settings
+ # 4. Connector defaults (max_file_size, recommended_chunk_seconds)
+ # 5. App default (20MB)
+ connector_specs = connector.specifications
+ should_chunk = (
+ chunking_service and
+ chunking_service.needs_chunking(actual_filepath, False, connector_specs)
+ )
+
+ if should_chunk:
+ # Use chunking for large files
+ file_size_mb = os.path.getsize(actual_filepath) / (1024 * 1024)
+ current_app.logger.info(f"File {actual_filepath} is large ({file_size_mb:.1f}MB), using chunking for transcription")
+ transcription_text = transcribe_chunks_with_connector(
+ connector, actual_filepath, actual_filename, actual_content_type, language
)
+ # Store as plain text (chunked transcription doesn't preserve diarization)
+ recording.transcription = transcription_text
+ current_app.logger.info(f"Chunked transcription completed: {len(transcription_text)} characters")
+ else:
+ # Build the transcription request for single file
+ with open(actual_filepath, 'rb') as audio_file:
+ request = TranscriptionRequest(
+ audio_file=audio_file,
+ filename=actual_filename,
+ mime_type=actual_content_type,
+ language=language,
+ diarize=should_diarize,
+ min_speakers=min_speakers,
+ max_speakers=max_speakers
+ )
- current_app.logger.info(f"Transcribing with connector: diarize={should_diarize}, language={language}")
- response = connector.transcribe(request)
+ current_app.logger.info(f"Transcribing with connector: diarize={should_diarize}, language={language}")
+ response = connector.transcribe(request)
- # Store the result
- if response.segments and response.has_diarization():
- # Store as JSON with segments (diarized format)
- recording.transcription = response.to_storage_format()
- current_app.logger.info(f"Transcription completed with {len(response.segments)} segments and {len(response.speakers or [])} speakers")
- else:
- # Store as plain text
- recording.transcription = response.text
- current_app.logger.info(f"Transcription completed: {len(response.text)} characters")
+ # Store the result
+ if response.segments and response.has_diarization():
+ # Store as JSON with segments (diarized format)
+ recording.transcription = response.to_storage_format()
+ current_app.logger.info(f"Transcription completed with {len(response.segments)} segments and {len(response.speakers or [])} speakers")
+ else:
+ # Store as plain text
+ recording.transcription = response.text
+ current_app.logger.info(f"Transcription completed: {len(response.text)} characters")
- # Store speaker embeddings if available
- if response.speaker_embeddings:
- recording.speaker_embeddings = response.speaker_embeddings
- current_app.logger.info(f"Stored speaker embeddings for speakers: {list(response.speaker_embeddings.keys())}")
+ # Store speaker embeddings if available
+ if response.speaker_embeddings:
+ recording.speaker_embeddings = response.speaker_embeddings
+ current_app.logger.info(f"Stored speaker embeddings for speakers: {list(response.speaker_embeddings.keys())}")
# Calculate and save transcription duration
transcription_end_time = time.time()
@@ -1162,12 +1299,15 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
recording = db.session.get(Recording, recording_id)
if recording:
recording.status = 'FAILED'
- recording.transcription = f"Transcription failed: {error_msg}"
+ recording.transcription = format_error_for_storage(error_msg)
end_time = datetime.utcnow()
recording.processing_time_seconds = (end_time - start_time).total_seconds()
db.session.commit()
+ # Re-raise so job queue marks the job as failed
+ raise
+
def transcribe_audio_asr(app_context, recording_id, filepath, original_filename, start_time, mime_type=None, language=None, diarize=False, min_speakers=None, max_speakers=None, tag_id=None):
"""Transcribes audio using the ASR webservice."""
@@ -1227,7 +1367,7 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,
recording.status = 'FAILED'
recording.error_msg = f"Audio extraction failed: {str(e)}"
db.session.commit()
- return
+ raise # Re-raise so job queue marks the job as failed
# Keep track of converted filepath for retry logic
converted_filepath = None
@@ -1497,9 +1637,11 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,
recording = db.session.get(Recording, recording_id)
if recording:
recording.status = 'FAILED'
- recording.transcription = user_error_msg
+ recording.transcription = format_error_for_storage(user_error_msg)
db.session.commit()
+ # Re-raise so job queue marks the job as failed
+ raise
def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr, start_time, language=None, min_speakers=None, max_speakers=None, tag_id=None):
@@ -1670,7 +1812,7 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,
if recording.status not in ['COMPLETED', 'FAILED']: # Avoid overwriting final state
recording.status = 'FAILED'
if not recording.transcription: # If transcription itself failed
- recording.transcription = f"Processing failed: {str(e)}"
+ recording.transcription = format_error_for_storage(str(e))
# Add error note to summary if appropriate stage was reached
if recording.status == 'SUMMARIZING' and not recording.summary:
recording.summary = f"[Processing failed during summarization: {str(e)}]"
@@ -1679,6 +1821,8 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,
recording.processing_time_seconds = (end_time - start_time).total_seconds()
db.session.commit()
+ # Re-raise so job queue marks the job as failed
+ raise
def transcribe_single_file(filepath, recording):
diff --git a/src/utils/__init__.py b/src/utils/__init__.py
index 69e2cf32..39893bb3 100644
--- a/src/utils/__init__.py
+++ b/src/utils/__init__.py
@@ -41,6 +41,13 @@ from .token_auth import (
is_token_authenticated
)
+from .error_formatting import (
+ is_transcription_error,
+ format_error_for_user,
+ format_error_for_storage,
+ parse_stored_error
+)
+
__all__ = [
# JSON parsing
'auto_close_json',
@@ -63,4 +70,9 @@ __all__ = [
'hash_token',
'load_user_from_token',
'is_token_authenticated',
+ # Error formatting
+ 'is_transcription_error',
+ 'format_error_for_user',
+ 'format_error_for_storage',
+ 'parse_stored_error',
]
diff --git a/src/utils/error_formatting.py b/src/utils/error_formatting.py
new file mode 100644
index 00000000..0bbcab69
--- /dev/null
+++ b/src/utils/error_formatting.py
@@ -0,0 +1,365 @@
+"""
+User-friendly error formatting utility.
+
+Transforms technical error messages into user-friendly explanations with
+actionable guidance. Works for both known error patterns and unknown errors.
+"""
+
+import re
+import json
+from typing import Dict, Optional, Tuple
+
+
+# Known error patterns with user-friendly messages
+ERROR_PATTERNS = [
+ # File size errors
+ {
+ 'patterns': [
+ r'maximum content size limit.*exceeded',
+ r'file.*too large',
+ r'413.*exceeded',
+ r'payload too large',
+ ],
+ 'title': 'File Too Large',
+ 'message': 'The audio file exceeds the maximum size allowed by the transcription service.',
+ 'guidance': 'Try enabling audio chunking in your settings, or compress the audio file before uploading.',
+ 'icon': 'fa-file-audio',
+ 'type': 'size_limit'
+ },
+ # Timeout errors
+ {
+ 'patterns': [
+ r'timed?\s*out',
+ r'timeout',
+ r'deadline exceeded',
+ r'request took too long',
+ ],
+ 'title': 'Processing Timeout',
+ 'message': 'The transcription took too long to complete.',
+ 'guidance': 'This can happen with very long recordings. Try splitting the audio into smaller parts, or increase the timeout setting if available.',
+ 'icon': 'fa-clock',
+ 'type': 'timeout'
+ },
+ # Authentication errors
+ {
+ 'patterns': [
+ r'401.*unauthorized',
+ r'invalid.*api.*key',
+ r'authentication.*failed',
+ r'api key.*invalid',
+ r'incorrect api key',
+ ],
+ 'title': 'Authentication Error',
+ 'message': 'The transcription service rejected the API credentials.',
+ 'guidance': 'Please check that your API key is correct and has not expired. Contact your administrator if the problem persists.',
+ 'icon': 'fa-key',
+ 'type': 'auth'
+ },
+ # Rate limit errors
+ {
+ 'patterns': [
+ r'rate.*limit',
+ r'too many requests',
+ r'429',
+ r'quota.*exceeded',
+ ],
+ 'title': 'Rate Limit Exceeded',
+ 'message': 'Too many requests were sent to the transcription service.',
+ 'guidance': 'Please wait a few minutes before trying again. The system will automatically retry failed jobs.',
+ 'icon': 'fa-hourglass-half',
+ 'type': 'rate_limit'
+ },
+ # Connection errors
+ {
+ 'patterns': [
+ r'connection.*refused',
+ r'connection.*reset',
+ r'could not connect',
+ r'network.*unreachable',
+ r'name.*resolution.*failed',
+ r'dns.*failed',
+ ],
+ 'title': 'Connection Error',
+ 'message': 'Could not connect to the transcription service.',
+ 'guidance': 'Please check your internet connection and ensure the transcription service is available. If using a self-hosted service, verify it is running.',
+ 'icon': 'fa-wifi',
+ 'type': 'connection'
+ },
+ # Service unavailable
+ {
+ 'patterns': [
+ r'503.*service unavailable',
+ r'502.*bad gateway',
+ r'500.*internal server error',
+ r'service.*unavailable',
+ r'server.*error',
+ ],
+ 'title': 'Service Unavailable',
+ 'message': 'The transcription service is temporarily unavailable.',
+ 'guidance': 'This is usually temporary. Please try again in a few minutes.',
+ 'icon': 'fa-server',
+ 'type': 'service_error'
+ },
+ # Invalid audio format
+ {
+ 'patterns': [
+ r'invalid.*file.*format',
+ r'unsupported.*format',
+ r'could not.*decode',
+ r'audio.*corrupt',
+ r'not.*valid.*audio',
+ ],
+ 'title': 'Invalid Audio Format',
+ 'message': 'The audio file format is not supported or the file may be corrupted.',
+ 'guidance': 'Try converting the audio to MP3 or WAV format before uploading. If the file plays correctly on your device, try re-exporting it.',
+ 'icon': 'fa-file-audio',
+ 'type': 'format'
+ },
+ # Insufficient funds/billing
+ {
+ 'patterns': [
+ r'insufficient.*funds',
+ r'billing.*issue',
+ r'payment.*required',
+ r'account.*suspended',
+ ],
+ 'title': 'Billing Issue',
+ 'message': 'There is a billing issue with the transcription service account.',
+ 'guidance': 'Please check your account status and payment information with the transcription service provider.',
+ 'icon': 'fa-credit-card',
+ 'type': 'billing'
+ },
+ # Model not found
+ {
+ 'patterns': [
+ r'model.*not.*found',
+ r'invalid.*model',
+ r'model.*does not exist',
+ ],
+ 'title': 'Model Not Available',
+ 'message': 'The requested transcription model is not available.',
+ 'guidance': 'Please check the model name in your settings. The model may have been deprecated or renamed.',
+ 'icon': 'fa-microchip',
+ 'type': 'model'
+ },
+ # Audio extraction failed
+ {
+ 'patterns': [
+ r'audio.*extraction.*failed',
+ r'could not.*extract.*audio',
+ r'ffmpeg.*failed',
+ r'no audio.*stream',
+ ],
+ 'title': 'Audio Extraction Failed',
+ 'message': 'Could not extract audio from the uploaded file.',
+ 'guidance': 'The file may be corrupted or in an unsupported format. Try converting it to a standard audio format (MP3, WAV) before uploading.',
+ 'icon': 'fa-file-video',
+ 'type': 'extraction'
+ },
+]
+
+
+def extract_error_details(error_text: str) -> Dict:
+ """
+ Extract structured error details from raw error text.
+ Attempts to parse JSON error responses from APIs.
+ """
+ details = {
+ 'raw': error_text,
+ 'code': None,
+ 'message': None,
+ 'type': None,
+ }
+
+ # Try to extract error code
+ code_match = re.search(r'(?:error\s*code|status)[:\s]*(\d{3})', error_text, re.IGNORECASE)
+ if code_match:
+ details['code'] = code_match.group(1)
+
+ # Try to parse JSON error structure
+ json_match = re.search(r'\{[^{}]*["\']error["\'][^{}]*\}', error_text)
+ if json_match:
+ try:
+ # Clean up the JSON-like string
+ json_str = json_match.group(0).replace("'", '"')
+ error_obj = json.loads(json_str)
+ if 'error' in error_obj:
+ err = error_obj['error']
+ if isinstance(err, dict):
+ details['message'] = err.get('message')
+ details['type'] = err.get('type')
+ details['code'] = details['code'] or err.get('code')
+ except (json.JSONDecodeError, KeyError):
+ pass
+
+ # Try to extract message from common patterns
+ if not details['message']:
+ msg_match = re.search(r"['\"]message['\"]\s*:\s*['\"]([^'\"]+)['\"]", error_text)
+ if msg_match:
+ details['message'] = msg_match.group(1)
+
+ return details
+
+
+def format_error_for_user(error_text: str) -> Dict:
+ """
+ Transform a technical error message into a user-friendly format.
+
+ Returns:
+ Dict with keys:
+ - title: Short, user-friendly title
+ - message: Plain language explanation
+ - guidance: Actionable suggestion
+ - icon: FontAwesome icon class
+ - type: Error category
+ - technical: Original error (for advanced users/debugging)
+ - is_known: Whether this matched a known pattern
+ """
+ if not error_text:
+ return {
+ 'title': 'Unknown Error',
+ 'message': 'An unexpected error occurred.',
+ 'guidance': 'Please try again. If the problem persists, contact support.',
+ 'icon': 'fa-exclamation-triangle',
+ 'type': 'unknown',
+ 'technical': '',
+ 'is_known': False
+ }
+
+ error_lower = error_text.lower()
+
+ # Check against known patterns
+ for pattern_info in ERROR_PATTERNS:
+ for pattern in pattern_info['patterns']:
+ if re.search(pattern, error_lower):
+ return {
+ 'title': pattern_info['title'],
+ 'message': pattern_info['message'],
+ 'guidance': pattern_info['guidance'],
+ 'icon': pattern_info['icon'],
+ 'type': pattern_info['type'],
+ 'technical': error_text,
+ 'is_known': True
+ }
+
+ # Unknown error - try to make it more readable
+ details = extract_error_details(error_text)
+
+ # Clean up the error message for display
+ clean_message = details['message'] or error_text
+
+ # Remove common prefixes
+ for prefix in ['Transcription failed:', 'Processing failed:', 'Error:', 'Exception:']:
+ if clean_message.startswith(prefix):
+ clean_message = clean_message[len(prefix):].strip()
+
+ # Truncate very long messages
+ if len(clean_message) > 200:
+ clean_message = clean_message[:200] + '...'
+
+ # Generate a reasonable title based on error code
+ title = 'Processing Error'
+ if details['code']:
+ code = details['code']
+ if code.startswith('4'):
+ title = 'Request Error'
+ elif code.startswith('5'):
+ title = 'Server Error'
+
+ return {
+ 'title': title,
+ 'message': clean_message,
+ 'guidance': 'If this error persists, try reprocessing the recording or contact support for assistance.',
+ 'icon': 'fa-exclamation-circle',
+ 'type': 'unknown',
+ 'technical': error_text,
+ 'is_known': False
+ }
+
+
+def format_error_for_storage(error_text: str) -> str:
+ """
+ Format an error message for storage in the database.
+ Returns a JSON string that can be parsed by the frontend for nice display.
+
+ The format is: ERROR_JSON:{"title": "...", "message": "...", ...}
+
+ This allows the frontend to detect formatted errors and display them nicely,
+ while still being human-readable if viewed raw.
+ """
+ formatted = format_error_for_user(error_text)
+
+ # Create a compact JSON representation
+ error_data = {
+ 't': formatted['title'],
+ 'm': formatted['message'],
+ 'g': formatted['guidance'],
+ 'i': formatted['icon'],
+ 'y': formatted['type'],
+ 'k': formatted['is_known'],
+ }
+
+ # Only include technical details if it adds value
+ if formatted['technical'] and formatted['technical'] != formatted['message']:
+ error_data['d'] = formatted['technical'][:500] # Limit technical detail length
+
+ try:
+ json_str = json.dumps(error_data, ensure_ascii=False)
+ return f"ERROR_JSON:{json_str}"
+ except (TypeError, ValueError):
+ # Fallback to plain text if JSON encoding fails
+ return f"{formatted['title']}: {formatted['message']}"
+
+
+def parse_stored_error(stored_text: str) -> Optional[Dict]:
+ """
+ Parse a stored error message. Returns the formatted error dict if it's
+ a JSON-formatted error, or None if it's plain text.
+ """
+ if not stored_text or not stored_text.startswith('ERROR_JSON:'):
+ return None
+
+ try:
+ json_str = stored_text[11:] # Remove 'ERROR_JSON:' prefix
+ data = json.loads(json_str)
+ return {
+ 'title': data.get('t', 'Error'),
+ 'message': data.get('m', 'An error occurred'),
+ 'guidance': data.get('g', ''),
+ 'icon': data.get('i', 'fa-exclamation-circle'),
+ 'type': data.get('y', 'unknown'),
+ 'is_known': data.get('k', False),
+ 'technical': data.get('d', ''),
+ }
+ except (json.JSONDecodeError, KeyError, TypeError):
+ return None
+
+
+def is_transcription_error(transcription_text: str) -> bool:
+ """
+ Check if the transcription text is actually an error message.
+
+ Returns True if the text is an error message (not valid transcription content).
+ This should be used to prevent operations like summarization or chat on failed recordings.
+ """
+ if not transcription_text:
+ return False
+
+ # Check for JSON-formatted error
+ if transcription_text.startswith('ERROR_JSON:'):
+ return True
+
+ # Check for legacy error prefixes
+ error_prefixes = [
+ 'Transcription failed:',
+ 'Processing failed:',
+ 'ASR processing failed:',
+ 'Audio extraction failed:',
+ 'Upload/Processing failed:',
+ ]
+
+ for prefix in error_prefixes:
+ if transcription_text.startswith(prefix):
+ return True
+
+ return False
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index a9e3b4a5..9e03fa79 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -35,6 +35,159 @@ const getSpeakerColor = (speakerId) => {
return `speaker-color-${(Math.abs(hash) % 8) + 1}`;
};
+// Parse transcription text to detect if it's an error message
+const parseTranscriptionError = (text) => {
+ if (!text) return null;
+
+ // Check for JSON-formatted error from backend
+ if (text.startsWith('ERROR_JSON:')) {
+ try {
+ const jsonStr = text.substring(11);
+ const data = JSON.parse(jsonStr);
+ return {
+ title: data.t || 'Error',
+ message: data.m || 'An error occurred',
+ guidance: data.g || '',
+ icon: data.i || 'fa-exclamation-circle',
+ type: data.y || 'unknown',
+ isKnown: data.k || false,
+ technical: data.d || ''
+ };
+ } catch (e) {
+ console.error('Failed to parse error JSON:', e);
+ }
+ }
+
+ // Check for legacy error format
+ const errorPrefixes = [
+ 'Transcription failed:',
+ 'Processing failed:',
+ 'ASR processing failed:',
+ 'Audio extraction failed:'
+ ];
+
+ for (const prefix of errorPrefixes) {
+ if (text.startsWith(prefix)) {
+ return parseUnformattedError(text);
+ }
+ }
+
+ return null;
+};
+
+// Parse unformatted error messages and make them user-friendly
+const parseUnformattedError = (text) => {
+ const lowerText = text.toLowerCase();
+
+ // Known error patterns
+ const patterns = [
+ {
+ patterns: ['maximum content size limit', 'file too large', '413', 'payload too large', 'exceeded'],
+ title: 'File Too Large',
+ message: 'The audio file exceeds the maximum size allowed by the transcription service.',
+ guidance: 'Try enabling audio chunking in your settings, or compress the audio file before uploading.',
+ icon: 'fa-file-audio',
+ type: 'size_limit'
+ },
+ {
+ patterns: ['timed out', 'timeout', 'deadline exceeded'],
+ title: 'Processing Timeout',
+ message: 'The transcription took too long to complete.',
+ guidance: 'This can happen with very long recordings. Try splitting the audio into smaller parts.',
+ icon: 'fa-clock',
+ type: 'timeout'
+ },
+ {
+ patterns: ['401', 'unauthorized', 'invalid api key', 'authentication failed', 'incorrect api key'],
+ title: 'Authentication Error',
+ message: 'The transcription service rejected the API credentials.',
+ guidance: 'Please check that the API key is correct and has not expired.',
+ icon: 'fa-key',
+ type: 'auth'
+ },
+ {
+ patterns: ['rate limit', 'too many requests', '429', 'quota exceeded'],
+ title: 'Rate Limit Exceeded',
+ message: 'Too many requests were sent to the transcription service.',
+ guidance: 'Please wait a few minutes and try reprocessing.',
+ icon: 'fa-hourglass-half',
+ type: 'rate_limit'
+ },
+ {
+ patterns: ['connection refused', 'connection reset', 'could not connect', 'network unreachable'],
+ title: 'Connection Error',
+ message: 'Could not connect to the transcription service.',
+ guidance: 'Check your internet connection and ensure the service is available.',
+ icon: 'fa-wifi',
+ type: 'connection'
+ },
+ {
+ patterns: ['503', '502', '500', 'service unavailable', 'server error', 'internal server error'],
+ title: 'Service Unavailable',
+ message: 'The transcription service is temporarily unavailable.',
+ guidance: 'This is usually temporary. Please try again in a few minutes.',
+ icon: 'fa-server',
+ type: 'service_error'
+ },
+ {
+ patterns: ['invalid file format', 'unsupported format', 'could not decode', 'corrupt', 'not valid audio'],
+ title: 'Invalid Audio Format',
+ message: 'The audio file format is not supported or the file may be corrupted.',
+ guidance: 'Try converting the audio to MP3 or WAV format before uploading.',
+ icon: 'fa-file-audio',
+ type: 'format'
+ },
+ {
+ patterns: ['audio extraction failed', 'ffmpeg failed', 'no audio stream'],
+ title: 'Audio Extraction Failed',
+ message: 'Could not extract audio from the uploaded file.',
+ guidance: 'Try converting the file to a standard audio format (MP3, WAV) before uploading.',
+ icon: 'fa-file-video',
+ type: 'extraction'
+ }
+ ];
+
+ // Check patterns
+ for (const pattern of patterns) {
+ for (const p of pattern.patterns) {
+ if (lowerText.includes(p)) {
+ return {
+ title: pattern.title,
+ message: pattern.message,
+ guidance: pattern.guidance,
+ icon: pattern.icon,
+ type: pattern.type,
+ isKnown: true,
+ technical: text
+ };
+ }
+ }
+ }
+
+ // Unknown error - clean it up
+ let cleanMessage = text;
+ for (const prefix of ['Transcription failed:', 'Processing failed:', 'Error:', 'ASR processing failed:']) {
+ if (cleanMessage.startsWith(prefix)) {
+ cleanMessage = cleanMessage.substring(prefix.length).trim();
+ }
+ }
+
+ // Truncate if too long
+ if (cleanMessage.length > 200) {
+ cleanMessage = cleanMessage.substring(0, 200) + '...';
+ }
+
+ return {
+ title: 'Processing Error',
+ message: cleanMessage,
+ guidance: 'If this error persists, try reprocessing the recording.',
+ icon: 'fa-exclamation-circle',
+ type: 'unknown',
+ isKnown: false,
+ technical: text
+ };
+};
+
// Wait for the DOM to be fully loaded before mounting the Vue app
document.addEventListener('DOMContentLoaded', async () => {
// Initialize i18n before creating Vue app (if not already initialized)
@@ -826,10 +979,26 @@ document.addEventListener('DOMContentLoaded', async () => {
// =========================================================================
const processedTranscription = computed(() => {
if (!selectedRecording.value?.transcription) {
- return { hasDialogue: false, content: '', speakers: [], simpleSegments: [], bubbleRows: [] };
+ return { hasDialogue: false, content: '', speakers: [], simpleSegments: [], bubbleRows: [], isError: false };
}
const transcription = selectedRecording.value.transcription;
+
+ // Check for error message format
+ const errorInfo = parseTranscriptionError(transcription);
+ if (errorInfo) {
+ return {
+ hasDialogue: false,
+ isJson: false,
+ isError: true,
+ error: errorInfo,
+ content: '',
+ speakers: [],
+ simpleSegments: [],
+ bubbleRows: []
+ };
+ }
+
let transcriptionData;
try {
@@ -1502,6 +1671,7 @@ document.addEventListener('DOMContentLoaded', async () => {
unifiedStatus === 'completed' ? 'Done' : 'Failed',
queuePosition: job.position,
errorMessage: job.error_message,
+ friendlyError: job.error_message ? parseUnformattedError(job.error_message) : null,
completedAt: job.completed_at,
source: 'job'
});
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index dbc09c8a..7c95e4c5 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -5,6 +5,28 @@
import * as FailedUploads from '../db/failed-uploads.js';
+// Parse error message and return friendly error info
+function getFriendlyError(errorMessage) {
+ if (!errorMessage) return { title: 'Processing Error', message: 'An error occurred' };
+ const lowerText = errorMessage.toLowerCase();
+ const patterns = [
+ { patterns: ['maximum content size limit', 'file too large', '413', 'payload too large', 'exceeded'], title: 'File Too Large', guidance: 'Enable chunking in settings or compress the file' },
+ { patterns: ['timed out', 'timeout', 'deadline exceeded'], title: 'Processing Timeout', guidance: 'Try splitting the audio into smaller parts' },
+ { patterns: ['401', 'unauthorized', 'invalid api key', 'authentication failed', 'incorrect api key'], title: 'Authentication Error', guidance: 'Check the API key in settings' },
+ { patterns: ['rate limit', 'too many requests', '429', 'quota exceeded'], title: 'Rate Limit Exceeded', guidance: 'Wait a few minutes and try again' },
+ { patterns: ['connection refused', 'connection reset', 'could not connect', 'network unreachable'], title: 'Connection Error', guidance: 'Check network connection' },
+ { patterns: ['503', '502', '500', 'service unavailable', 'server error', 'internal server error'], title: 'Service Unavailable', guidance: 'Try again in a few minutes' },
+ { patterns: ['invalid file format', 'unsupported format', 'could not decode', 'corrupt'], title: 'Invalid Audio Format', guidance: 'Convert to MP3 or WAV before uploading' },
+ { patterns: ['audio extraction failed', 'ffmpeg failed', 'no audio stream'], title: 'Audio Extraction Failed', guidance: 'Convert to standard audio format' },
+ ];
+ for (const pattern of patterns) {
+ for (const p of pattern.patterns) {
+ if (lowerText.includes(p)) return { title: pattern.title, guidance: pattern.guidance };
+ }
+ }
+ return { title: 'Processing Error', guidance: 'Try reprocessing the recording' };
+}
+
export function useUpload(state, utils) {
const {
uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,
@@ -288,7 +310,9 @@ export function useUpload(state, utils) {
recordings.value[failedRecordIndex].status = 'FAILED';
recordings.value[failedRecordIndex].transcription = `Upload/Processing failed: ${error.message}`;
} else {
- setGlobalError(`Failed to process "${nextFileItem.file.name}": ${error.message}`);
+ // Show friendly error message in toast
+ const friendlyErr = getFriendlyError(error.message);
+ setGlobalError(`${friendlyErr.title}: ${friendlyErr.guidance}`);
}
// Store failed upload in IndexedDB for background sync retry
@@ -508,7 +532,9 @@ export function useUpload(state, utils) {
fileItem.error = 'Processing failed on server.';
}
- setGlobalError(`Processing failed for "${fileItem.displayName || fileItem.file.name}".`);
+ // Show friendly error message in toast
+ const friendlyErr = getFriendlyError(fileItem.error);
+ setGlobalError(`${friendlyErr.title}: ${friendlyErr.guidance}`);
clearInterval(pollInterval.value);
pollInterval.value = null;
resetCurrentFileProcessingState();
diff --git a/static/js/modules/utils/errorDisplay.js b/static/js/modules/utils/errorDisplay.js
new file mode 100644
index 00000000..6671c2d6
--- /dev/null
+++ b/static/js/modules/utils/errorDisplay.js
@@ -0,0 +1,271 @@
+/**
+ * Error Display Utility
+ *
+ * Parses and displays user-friendly error messages from the backend.
+ * Handles both JSON-formatted errors (ERROR_JSON:...) and plain text errors.
+ */
+
+/**
+ * Parse a stored error message from the backend.
+ * @param {string} text - The stored transcription/error text
+ * @returns {Object|null} - Parsed error object or null if not an error
+ */
+export function parseStoredError(text) {
+ if (!text) return null;
+
+ // Check for JSON-formatted error
+ if (text.startsWith('ERROR_JSON:')) {
+ try {
+ const jsonStr = text.substring(11); // Remove 'ERROR_JSON:' prefix
+ const data = JSON.parse(jsonStr);
+ return {
+ title: data.t || 'Error',
+ message: data.m || 'An error occurred',
+ guidance: data.g || '',
+ icon: data.i || 'fa-exclamation-circle',
+ type: data.y || 'unknown',
+ isKnown: data.k || false,
+ technical: data.d || '',
+ isFormattedError: true
+ };
+ } catch (e) {
+ console.error('Failed to parse error JSON:', e);
+ }
+ }
+
+ // Check for legacy error format (starts with common error prefixes)
+ const errorPrefixes = [
+ 'Transcription failed:',
+ 'Processing failed:',
+ 'ASR processing failed:',
+ 'Audio extraction failed:',
+ 'Error:'
+ ];
+
+ for (const prefix of errorPrefixes) {
+ if (text.startsWith(prefix)) {
+ // Parse the error using pattern matching
+ return parseUnformattedError(text);
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Parse an unformatted error message and try to make it user-friendly.
+ * @param {string} text - The raw error text
+ * @returns {Object} - Parsed error object
+ */
+function parseUnformattedError(text) {
+ const lowerText = text.toLowerCase();
+
+ // Known error patterns
+ const patterns = [
+ {
+ patterns: ['maximum content size limit', 'file too large', '413', 'payload too large', 'exceeded'],
+ title: 'File Too Large',
+ message: 'The audio file exceeds the maximum size allowed by the transcription service.',
+ guidance: 'Try enabling audio chunking in your settings, or compress the audio file before uploading.',
+ icon: 'fa-file-audio',
+ type: 'size_limit'
+ },
+ {
+ patterns: ['timed out', 'timeout', 'deadline exceeded'],
+ title: 'Processing Timeout',
+ message: 'The transcription took too long to complete.',
+ guidance: 'This can happen with very long recordings. Try splitting the audio into smaller parts.',
+ icon: 'fa-clock',
+ type: 'timeout'
+ },
+ {
+ patterns: ['401', 'unauthorized', 'invalid api key', 'authentication failed', 'incorrect api key'],
+ title: 'Authentication Error',
+ message: 'The transcription service rejected the API credentials.',
+ guidance: 'Please check that the API key is correct and has not expired.',
+ icon: 'fa-key',
+ type: 'auth'
+ },
+ {
+ patterns: ['rate limit', 'too many requests', '429', 'quota exceeded'],
+ title: 'Rate Limit Exceeded',
+ message: 'Too many requests were sent to the transcription service.',
+ guidance: 'Please wait a few minutes and try reprocessing.',
+ icon: 'fa-hourglass-half',
+ type: 'rate_limit'
+ },
+ {
+ patterns: ['connection refused', 'connection reset', 'could not connect', 'network unreachable'],
+ title: 'Connection Error',
+ message: 'Could not connect to the transcription service.',
+ guidance: 'Check your internet connection and ensure the service is available.',
+ icon: 'fa-wifi',
+ type: 'connection'
+ },
+ {
+ patterns: ['503', '502', '500', 'service unavailable', 'server error', 'internal server error'],
+ title: 'Service Unavailable',
+ message: 'The transcription service is temporarily unavailable.',
+ guidance: 'This is usually temporary. Please try again in a few minutes.',
+ icon: 'fa-server',
+ type: 'service_error'
+ },
+ {
+ patterns: ['invalid file format', 'unsupported format', 'could not decode', 'corrupt', 'not valid audio'],
+ title: 'Invalid Audio Format',
+ message: 'The audio file format is not supported or the file may be corrupted.',
+ guidance: 'Try converting the audio to MP3 or WAV format before uploading.',
+ icon: 'fa-file-audio',
+ type: 'format'
+ },
+ {
+ patterns: ['audio extraction failed', 'ffmpeg failed', 'no audio stream'],
+ title: 'Audio Extraction Failed',
+ message: 'Could not extract audio from the uploaded file.',
+ guidance: 'Try converting the file to a standard audio format (MP3, WAV) before uploading.',
+ icon: 'fa-file-video',
+ type: 'extraction'
+ }
+ ];
+
+ // Check patterns
+ for (const pattern of patterns) {
+ for (const p of pattern.patterns) {
+ if (lowerText.includes(p)) {
+ return {
+ title: pattern.title,
+ message: pattern.message,
+ guidance: pattern.guidance,
+ icon: pattern.icon,
+ type: pattern.type,
+ isKnown: true,
+ technical: text,
+ isFormattedError: true
+ };
+ }
+ }
+ }
+
+ // Unknown error - clean it up as best we can
+ let cleanMessage = text;
+ for (const prefix of ['Transcription failed:', 'Processing failed:', 'Error:', 'ASR processing failed:']) {
+ if (cleanMessage.startsWith(prefix)) {
+ cleanMessage = cleanMessage.substring(prefix.length).trim();
+ }
+ }
+
+ // Truncate if too long
+ if (cleanMessage.length > 200) {
+ cleanMessage = cleanMessage.substring(0, 200) + '...';
+ }
+
+ return {
+ title: 'Processing Error',
+ message: cleanMessage,
+ guidance: 'If this error persists, try reprocessing the recording.',
+ icon: 'fa-exclamation-circle',
+ type: 'unknown',
+ isKnown: false,
+ technical: text,
+ isFormattedError: true
+ };
+}
+
+/**
+ * Check if a transcription text is actually an error message.
+ * @param {string} text - The transcription text
+ * @returns {boolean}
+ */
+export function isErrorMessage(text) {
+ if (!text) return false;
+
+ if (text.startsWith('ERROR_JSON:')) return true;
+
+ const errorPrefixes = [
+ 'Transcription failed:',
+ 'Processing failed:',
+ 'ASR processing failed:',
+ 'Audio extraction failed:'
+ ];
+
+ return errorPrefixes.some(prefix => text.startsWith(prefix));
+}
+
+/**
+ * Generate HTML for displaying an error nicely.
+ * @param {Object} error - Parsed error object from parseStoredError
+ * @param {boolean} showTechnical - Whether to show technical details
+ * @returns {string} - HTML string
+ */
+export function generateErrorHTML(error, showTechnical = false) {
+ if (!error) return '';
+
+ const typeColors = {
+ size_limit: 'amber',
+ timeout: 'orange',
+ auth: 'red',
+ rate_limit: 'yellow',
+ connection: 'blue',
+ service_error: 'purple',
+ format: 'pink',
+ extraction: 'indigo',
+ billing: 'red',
+ model: 'gray',
+ unknown: 'gray'
+ };
+
+ const color = typeColors[error.type] || 'gray';
+
+ let html = `
+ <div class="error-display bg-${color}-500/10 border border-${color}-500/30 rounded-lg p-4">
+ <div class="flex items-start gap-3">
+ <div class="flex-shrink-0 w-10 h-10 rounded-full bg-${color}-500/20 flex items-center justify-center">
+ <i class="fas ${error.icon} text-${color}-500"></i>
+ </div>
+ <div class="flex-1 min-w-0">
+ <h3 class="text-lg font-semibold text-${color}-600 dark:text-${color}-400 mb-1">
+ ${escapeHtml(error.title)}
+ </h3>
+ <p class="text-[var(--text-primary)] mb-2">
+ ${escapeHtml(error.message)}
+ </p>
+ ${error.guidance ? `
+ <div class="flex items-start gap-2 text-sm text-[var(--text-secondary)] bg-[var(--bg-tertiary)]/50 rounded p-2">
+ <i class="fas fa-lightbulb text-yellow-500 mt-0.5"></i>
+ <span>${escapeHtml(error.guidance)}</span>
+ </div>
+ ` : ''}
+ </div>
+ </div>
+ ${showTechnical && error.technical ? `
+ <details class="mt-3 text-xs">
+ <summary class="cursor-pointer text-[var(--text-muted)] hover:text-[var(--text-secondary)]">
+ Technical details
+ </summary>
+ <pre class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded overflow-x-auto text-[var(--text-muted)]">${escapeHtml(error.technical)}</pre>
+ </details>
+ ` : ''}
+ </div>
+ `;
+
+ return html;
+}
+
+/**
+ * Escape HTML special characters.
+ * @param {string} text
+ * @returns {string}
+ */
+function escapeHtml(text) {
+ if (!text) return '';
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
+// Export for use in Vue components
+export default {
+ parseStoredError,
+ isErrorMessage,
+ generateErrorHTML
+};
diff --git a/templates/components/detail/desktop-chat-section.html b/templates/components/detail/desktop-chat-section.html
index 0d629f49..fa4608ab 100644
--- a/templates/components/detail/desktop-chat-section.html
+++ b/templates/components/detail/desktop-chat-section.html
@@ -89,18 +89,23 @@
<div class="flex gap-2">
<textarea v-model="chatInput"
@keydown="handleChatKeydown"
- :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'"
+ :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED' || processedTranscription.isError"
:placeholder="t('chat.placeholderWithHint')"
class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm"
rows="2">
</textarea>
<button @click="sendChatMessage"
- :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'"
+ :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED' || processedTranscription.isError"
class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
<i class="fas fa-paper-plane"></i>
</button>
</div>
- <p v-if="selectedRecording.status !== 'COMPLETED'"
+ <p v-if="processedTranscription.isError"
+ class="text-xs text-amber-500 mt-2">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ Cannot chat: transcription failed. Please reprocess the transcription first.
+ </p>
+ <p v-else-if="selectedRecording.status !== 'COMPLETED'"
class="text-xs text-[var(--text-muted)] mt-2">
${ t('chat.availableAfterTranscription') }
</p>
diff --git a/templates/components/detail/desktop-summary-tab.html b/templates/components/detail/desktop-summary-tab.html
index 641e2cdf..a0684e70 100644
--- a/templates/components/detail/desktop-summary-tab.html
+++ b/templates/components/detail/desktop-summary-tab.html
@@ -8,8 +8,19 @@
<div v-else-if="!selectedRecording.summary" class="text-center py-8">
<i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
<p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
+ <!-- Show message if transcription is an error -->
+ <p v-if="processedTranscription.isError" class="text-sm text-amber-500 mb-2">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ Cannot generate summary: transcription failed
+ </p>
<button @click="generateSummary"
- class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
+ :disabled="processedTranscription.isError"
+ :class="[
+ 'px-6 py-3 font-medium rounded-lg shadow-lg transition-all duration-200',
+ processedTranscription.isError
+ ? 'bg-gray-400 text-gray-200 cursor-not-allowed'
+ : 'bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transform hover:scale-105'
+ ]">
<i class="fas fa-magic mr-2"></i>${ t('summary.generateSummary') }
</button>
</div>
diff --git a/templates/components/detail/desktop-transcription-panel.html b/templates/components/detail/desktop-transcription-panel.html
index 9e4b5047..8f8c6812 100644
--- a/templates/components/detail/desktop-transcription-panel.html
+++ b/templates/components/detail/desktop-transcription-panel.html
@@ -102,8 +102,83 @@
<p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
</div>
+ <!-- Error Display (when transcription is an error message) -->
+ <div v-if="processedTranscription.isError" class="error-display-container">
+ <div :class="[
+ 'rounded-lg p-5 border',
+ processedTranscription.error.type === 'size_limit' ? 'bg-amber-500/10 border-amber-500/30' :
+ processedTranscription.error.type === 'timeout' ? 'bg-orange-500/10 border-orange-500/30' :
+ processedTranscription.error.type === 'auth' ? 'bg-red-500/10 border-red-500/30' :
+ processedTranscription.error.type === 'rate_limit' ? 'bg-yellow-500/10 border-yellow-500/30' :
+ processedTranscription.error.type === 'connection' ? 'bg-blue-500/10 border-blue-500/30' :
+ processedTranscription.error.type === 'service_error' ? 'bg-purple-500/10 border-purple-500/30' :
+ 'bg-gray-500/10 border-gray-500/30'
+ ]">
+ <div class="flex items-start gap-4">
+ <div :class="[
+ 'flex-shrink-0 w-12 h-12 rounded-full flex items-center justify-center',
+ processedTranscription.error.type === 'size_limit' ? 'bg-amber-500/20' :
+ processedTranscription.error.type === 'timeout' ? 'bg-orange-500/20' :
+ processedTranscription.error.type === 'auth' ? 'bg-red-500/20' :
+ processedTranscription.error.type === 'rate_limit' ? 'bg-yellow-500/20' :
+ processedTranscription.error.type === 'connection' ? 'bg-blue-500/20' :
+ processedTranscription.error.type === 'service_error' ? 'bg-purple-500/20' :
+ 'bg-gray-500/20'
+ ]">
+ <i :class="[
+ 'fas text-xl',
+ processedTranscription.error.icon,
+ processedTranscription.error.type === 'size_limit' ? 'text-amber-500' :
+ processedTranscription.error.type === 'timeout' ? 'text-orange-500' :
+ processedTranscription.error.type === 'auth' ? 'text-red-500' :
+ processedTranscription.error.type === 'rate_limit' ? 'text-yellow-500' :
+ processedTranscription.error.type === 'connection' ? 'text-blue-500' :
+ processedTranscription.error.type === 'service_error' ? 'text-purple-500' :
+ 'text-gray-500'
+ ]"></i>
+ </div>
+ <div class="flex-1 min-w-0">
+ <h3 :class="[
+ 'text-lg font-semibold mb-2',
+ processedTranscription.error.type === 'size_limit' ? 'text-amber-600 dark:text-amber-400' :
+ processedTranscription.error.type === 'timeout' ? 'text-orange-600 dark:text-orange-400' :
+ processedTranscription.error.type === 'auth' ? 'text-red-600 dark:text-red-400' :
+ processedTranscription.error.type === 'rate_limit' ? 'text-yellow-600 dark:text-yellow-400' :
+ processedTranscription.error.type === 'connection' ? 'text-blue-600 dark:text-blue-400' :
+ processedTranscription.error.type === 'service_error' ? 'text-purple-600 dark:text-purple-400' :
+ 'text-gray-600 dark:text-gray-400'
+ ]">
+ ${processedTranscription.error.title}
+ </h3>
+ <p class="text-[var(--text-primary)] mb-3">
+ ${processedTranscription.error.message}
+ </p>
+ <div v-if="processedTranscription.error.guidance" class="flex items-start gap-2 text-sm text-[var(--text-secondary)] bg-[var(--bg-tertiary)]/50 rounded-lg p-3">
+ <i class="fas fa-lightbulb text-yellow-500 mt-0.5 flex-shrink-0"></i>
+ <span>${processedTranscription.error.guidance}</span>
+ </div>
+ </div>
+ </div>
+ <!-- Action buttons -->
+ <div class="mt-4 flex items-center gap-3 pt-4 border-t border-[var(--border-secondary)]">
+ <button @click="reprocessTranscription(selectedRecording.id)"
+ v-if="selectedRecording.can_edit !== false"
+ class="px-4 py-2 bg-[var(--bg-accent)] hover:bg-[var(--bg-accent-hover)] text-white rounded-lg transition-colors flex items-center gap-2">
+ <i class="fas fa-redo-alt"></i>
+ <span>Reprocess</span>
+ </button>
+ <details class="text-xs w-full">
+ <summary class="cursor-pointer text-[var(--text-muted)] hover:text-[var(--text-secondary)]">
+ Technical details
+ </summary>
+ <pre v-if="processedTranscription.error.technical" class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-lg text-[var(--text-muted)] text-xs max-h-32 overflow-auto whitespace-pre-wrap break-all w-full">${processedTranscription.error.technical}</pre>
+ </details>
+ </div>
+ </div>
+ </div>
+
<!-- Speaker Legend (for dialogue transcriptions in bubble view only) -->
- <div v-if="processedTranscription.hasDialogue && processedTranscription.speakers.length > 0 && transcriptionViewMode === 'bubble'"
+ <div v-if="!processedTranscription.isError && processedTranscription.hasDialogue && processedTranscription.speakers.length > 0 && transcriptionViewMode === 'bubble'"
:class="['speaker-legend', legendExpanded ? 'expanded' : '']">
<div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">
<div class="speaker-legend-title">
@@ -122,8 +197,8 @@
</div>
</div>
- <!-- Transcription Display -->
- <div v-if="selectedRecording.transcription">
+ <!-- Transcription Display (hide if it's an error) -->
+ <div v-if="selectedRecording.transcription && !processedTranscription.isError">
<!-- Simple View -->
<div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'"
class="transcription-simple-view">
diff --git a/templates/components/detail/mobile-chat-panel.html b/templates/components/detail/mobile-chat-panel.html
index 6041b986..c2c58ca6 100644
--- a/templates/components/detail/mobile-chat-panel.html
+++ b/templates/components/detail/mobile-chat-panel.html
@@ -46,10 +46,14 @@
</div>
<div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">
<div class="flex gap-2">
- <textarea v-model="chatInput" @keydown="handleChatKeydown" :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'" :placeholder="t('chat.placeholder')" class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm" rows="2"></textarea>
- <button @click="sendChatMessage" :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
+ <textarea v-model="chatInput" @keydown="handleChatKeydown" :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED' || processedTranscription.isError" :placeholder="t('chat.placeholder')" class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm" rows="2"></textarea>
+ <button @click="sendChatMessage" :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED' || processedTranscription.isError" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
<i class="fas fa-paper-plane"></i>
</button>
</div>
+ <p v-if="processedTranscription.isError" class="text-xs text-amber-500 mt-2">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ Cannot chat: transcription failed
+ </p>
</div>
</div>
diff --git a/templates/components/detail/mobile-summary-panel.html b/templates/components/detail/mobile-summary-panel.html
index 9dff67ab..0a3f33ed 100644
--- a/templates/components/detail/mobile-summary-panel.html
+++ b/templates/components/detail/mobile-summary-panel.html
@@ -23,8 +23,19 @@
<div v-else-if="!selectedRecording.summary" class="text-center py-8">
<i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
<p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
+ <!-- Show message if transcription is an error -->
+ <p v-if="processedTranscription.isError" class="text-sm text-amber-500 mb-2">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ Cannot generate summary: transcription failed
+ </p>
<button @click="generateSummary"
- class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
+ :disabled="processedTranscription.isError"
+ :class="[
+ 'px-6 py-3 font-medium rounded-lg shadow-lg transition-all duration-200',
+ processedTranscription.isError
+ ? 'bg-gray-400 text-gray-200 cursor-not-allowed'
+ : 'bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transform hover:scale-105'
+ ]">
<i class="fas fa-magic mr-2"></i>Generate Summary
</button>
</div>
diff --git a/templates/components/detail/mobile-transcript-panel.html b/templates/components/detail/mobile-transcript-panel.html
index b1b49b03..4e7214c6 100644
--- a/templates/components/detail/mobile-transcript-panel.html
+++ b/templates/components/detail/mobile-transcript-panel.html
@@ -50,8 +50,58 @@
<i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>
<p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
</div>
+
+ <!-- Error Display (when transcription is an error message) -->
+ <div v-if="processedTranscription.isError" class="error-display-container p-2">
+ <div :class="[
+ 'rounded-lg p-4 border',
+ processedTranscription.error.type === 'size_limit' ? 'bg-amber-500/10 border-amber-500/30' :
+ processedTranscription.error.type === 'timeout' ? 'bg-orange-500/10 border-orange-500/30' :
+ processedTranscription.error.type === 'auth' ? 'bg-red-500/10 border-red-500/30' :
+ 'bg-gray-500/10 border-gray-500/30'
+ ]">
+ <div class="flex items-start gap-3">
+ <div :class="[
+ 'flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center',
+ processedTranscription.error.type === 'size_limit' ? 'bg-amber-500/20' :
+ processedTranscription.error.type === 'timeout' ? 'bg-orange-500/20' :
+ processedTranscription.error.type === 'auth' ? 'bg-red-500/20' :
+ 'bg-gray-500/20'
+ ]">
+ <i :class="[
+ 'fas',
+ processedTranscription.error.icon,
+ processedTranscription.error.type === 'size_limit' ? 'text-amber-500' :
+ processedTranscription.error.type === 'timeout' ? 'text-orange-500' :
+ processedTranscription.error.type === 'auth' ? 'text-red-500' :
+ 'text-gray-500'
+ ]"></i>
+ </div>
+ <div class="flex-1 min-w-0">
+ <h3 class="font-semibold text-[var(--text-primary)] mb-1">
+ ${processedTranscription.error.title}
+ </h3>
+ <p class="text-sm text-[var(--text-secondary)] mb-2">
+ ${processedTranscription.error.message}
+ </p>
+ <div v-if="processedTranscription.error.guidance" class="text-xs text-[var(--text-muted)] bg-[var(--bg-tertiary)]/50 rounded p-2">
+ <i class="fas fa-lightbulb text-yellow-500 mr-1"></i>
+ ${processedTranscription.error.guidance}
+ </div>
+ </div>
+ </div>
+ <div class="mt-3 pt-3 border-t border-[var(--border-secondary)]">
+ <button @click="reprocessTranscription(selectedRecording.id)"
+ v-if="selectedRecording.can_edit !== false"
+ class="w-full px-3 py-2 bg-[var(--bg-accent)] hover:bg-[var(--bg-accent-hover)] text-white rounded-lg transition-colors text-sm">
+ <i class="fas fa-redo-alt mr-2"></i>Reprocess
+ </button>
+ </div>
+ </div>
+ </div>
+
<!-- Transcription content (show regardless of processing state if transcription exists) -->
- <div v-if="selectedRecording.transcription">
+ <div v-if="selectedRecording.transcription && !processedTranscription.isError">
<div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'" class="transcription-simple-view">
<div v-if="processedTranscription.hasDialogue">
<div v-for="(segment, index) in processedTranscription.simpleSegments" :key="`seg-${index}-${segment.startTime}`" :class="['speaker-segment', { 'active-playing-segment': currentPlayingSegmentIndex === index }]" @click="seekAudioFromEvent" :data-start-time="segment.startTime" :data-segment-index="index">
diff --git a/templates/components/progress-popup.html b/templates/components/progress-popup.html
index 89358b5d..e38c9c9e 100644
--- a/templates/components/progress-popup.html
+++ b/templates/components/progress-popup.html
@@ -106,9 +106,28 @@
</div>
<div v-for="item in failedProgressItems"
:key="item.id"
- class="px-2 py-1.5 bg-red-500/10 border-l-2 border-red-500 rounded-md mb-1">
+ :class="[
+ 'px-2 py-1.5 rounded-md mb-1 border-l-2',
+ item.friendlyError?.type === 'size_limit' ? 'bg-amber-500/10 border-amber-500' :
+ item.friendlyError?.type === 'timeout' ? 'bg-orange-500/10 border-orange-500' :
+ item.friendlyError?.type === 'auth' ? 'bg-red-500/10 border-red-500' :
+ item.friendlyError?.type === 'rate_limit' ? 'bg-yellow-500/10 border-yellow-500' :
+ item.friendlyError?.type === 'connection' ? 'bg-blue-500/10 border-blue-500' :
+ item.friendlyError?.type === 'service_error' ? 'bg-purple-500/10 border-purple-500' :
+ 'bg-red-500/10 border-red-500'
+ ]">
<div class="flex items-center gap-2">
- <i class="fas fa-exclamation-circle text-xs text-red-500"></i>
+ <i :class="[
+ 'fas text-xs',
+ item.friendlyError?.icon || 'fa-exclamation-circle',
+ item.friendlyError?.type === 'size_limit' ? 'text-amber-500' :
+ item.friendlyError?.type === 'timeout' ? 'text-orange-500' :
+ item.friendlyError?.type === 'auth' ? 'text-red-500' :
+ item.friendlyError?.type === 'rate_limit' ? 'text-yellow-500' :
+ item.friendlyError?.type === 'connection' ? 'text-blue-500' :
+ item.friendlyError?.type === 'service_error' ? 'text-purple-500' :
+ 'text-red-500'
+ ]"></i>
<span class="text-xs truncate flex-1 text-[var(--text-primary)]">${item.title}</span>
<div class="flex items-center gap-1">
<button v-if="item.jobId" @click.stop="retryProgressItem(item)"
@@ -123,7 +142,22 @@
</button>
</div>
</div>
- <span v-if="item.errorMessage" class="text-[10px] text-red-400 block truncate mt-0.5">${item.errorMessage}</span>
+ <!-- Friendly error title and message -->
+ <div v-if="item.friendlyError" class="mt-0.5">
+ <span :class="[
+ 'text-[10px] font-medium',
+ item.friendlyError.type === 'size_limit' ? 'text-amber-500' :
+ item.friendlyError.type === 'timeout' ? 'text-orange-500' :
+ item.friendlyError.type === 'auth' ? 'text-red-500' :
+ item.friendlyError.type === 'rate_limit' ? 'text-yellow-500' :
+ item.friendlyError.type === 'connection' ? 'text-blue-500' :
+ item.friendlyError.type === 'service_error' ? 'text-purple-500' :
+ 'text-red-400'
+ ]">${item.friendlyError.title}</span>
+ <span v-if="item.friendlyError.guidance" class="text-[10px] text-[var(--text-muted)] block truncate">${item.friendlyError.guidance}</span>
+ </div>
+ <!-- Fallback to raw error message if no friendly error -->
+ <span v-else-if="item.errorMessage" class="text-[10px] text-red-400 block truncate mt-0.5">${item.errorMessage}</span>
</div>
</div>