Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add job queue for transcription processing with timeout fixes
Murtaza Nasir6ea185195623
diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 9d269290..e7e9e3d8 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -12,6 +12,7 @@ import threadingimport timeimport subprocessfrom datetime import datetime, timedelta+from src.services.job_queue import job_queuefrom flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app, make_responsefrom flask_login import login_required, current_userfrom werkzeug.utils import secure_filename@@ -1018,75 +1019,36 @@ def reprocess_transcription(recording_id):if not recording.audio_path or not os.path.exists(recording.audio_path):return jsonify({'error': 'Audio file not found for reprocessing'}), 404- if recording.status in ['PROCESSING', 'SUMMARIZING']:+ if recording.status in ['QUEUED', 'PROCESSING', 'SUMMARIZING']:return jsonify({'error': 'Recording is already being processed'}), 400- # --- Convert file if necessary before reprocessing ---+ # File path and name for processing (conversion handled in background task if needed)filepath = recording.audio_pathfilename_for_asr = recording.original_filename or os.path.basename(filepath)- filename_lower = filename_for_asr.lower()-- supported_formats = ('.wav', '.mp3', '.flac')- if not filename_lower.endswith(supported_formats):- current_app.logger.info(f"Reprocessing: Converting {filename_lower} format to high-quality MP3.")- base_filepath, file_ext = os.path.splitext(filepath)- temp_mp3_filepath = f"{base_filepath}_temp.mp3"- final_mp3_filepath = f"{base_filepath}.mp3"-- try:- # Convert to high-quality MP3 (128kbps, 44.1kHz)- subprocess.run(- ['ffmpeg', '-i', filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],- check=True, capture_output=True, text=True- )- current_app.logger.info(f"Successfully converted {filepath} to {temp_mp3_filepath} (128kbps MP3)")-- # If the original file is not the same as the final mp3 file, remove it- if filepath.lower() != final_mp3_filepath.lower():- os.remove(filepath)-- # Rename the temporary file to the final filename- os.rename(temp_mp3_filepath, final_mp3_filepath)-- filepath = final_mp3_filepath- filename_for_asr = os.path.basename(filepath)-- # Update database with new path and mime type- recording.audio_path = filepath- recording.mime_type, _ = mimetypes.guess_type(filepath)- db.session.commit()-- except FileNotFoundError:- current_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.'}), 500- except subprocess.CalledProcessError as e:- current_app.logger.error(f"ffmpeg conversion failed for {filepath}: {e.stderr}")- return jsonify({'error': f'Failed to convert audio file: {e.stderr}'}), 500# --- Proceed with reprocessing ---recording.transcription = Nonerecording.summary = None- recording.status = 'PROCESSING'+ recording.status = 'QUEUED' # Will change to PROCESSING when job starts# Clear existing events since they depend on the transcriptionEvent.query.filter_by(recording_id=recording_id).delete()db.session.commit()- # Refresh the recording object to ensure it has the latest committed data- db.session.refresh(recording)+ current_app.logger.info(f"Queueing transcription reprocessing for recording {recording_id}")- current_app.logger.info(f"Starting transcription reprocessing for recording {recording_id}")+ # Prepare job parameters+ data = request.json or {}+ start_time = datetime.utcnow()+ app_context = current_app._get_current_object().app_context()# Decide which transcription method to useif USE_ASR_ENDPOINT:- current_app.logger.info(f"Using ASR endpoint for reprocessing recording {recording_id}")-- data = request.json or {}language = data.get('language') or (recording.owner.transcription_language if recording.owner else None)min_speakers = data.get('min_speakers') or Nonemax_speakers = data.get('max_speakers') or None-+# Convert to int if providedif min_speakers:try:@@ -1098,21 +1060,19 @@ def reprocess_transcription(recording_id):max_speakers = int(max_speakers)except (ValueError, TypeError):max_speakers = None-- # Apply tag defaults if no user input provided (get merged defaults from all tags on this recording)++ # Apply tag defaults if no user input providedif (min_speakers is None or max_speakers is None) and recording.tags:- # Get tag defaults (use first non-None value from ordered tags)for tag_association in sorted(recording.tag_associations, key=lambda x: x.order):tag = tag_association.tagif min_speakers is None and tag.default_min_speakers:min_speakers = tag.default_min_speakersif max_speakers is None and tag.default_max_speakers:max_speakers = tag.default_max_speakers- # Stop once we have both valuesif min_speakers is not None and max_speakers is not None:break-- # Apply environment variable defaults if still no values (reprocess hierarchy: user input > tag defaults > env vars > auto-detect)++ # Apply environment variable defaultsif min_speakers is None and ASR_MIN_SPEAKERS:try:min_speakers = int(ASR_MIN_SPEAKERS)@@ -1123,36 +1083,36 @@ def reprocess_transcription(recording_id):max_speakers = int(ASR_MAX_SPEAKERS)except (ValueError, TypeError):max_speakers = None- if 'ASR_DIARIZE' in os.environ:- diarize_setting = ASR_DIARIZE- elif USE_ASR_ENDPOINT:- # When using ASR endpoint, use the configured ASR_DIARIZE value- diarize_setting = ASR_DIARIZE- else:- diarize_setting = recording.owner.diarize if recording.owner else False- start_time = datetime.utcnow()- thread = threading.Thread(- target=transcribe_audio_asr,- args=(current_app._get_current_object().app_context(), recording.id, filepath, filename_for_asr, start_time, recording.mime_type, language, diarize_setting, min_speakers, max_speakers)+ diarize_setting = ASR_DIARIZE if 'ASR_DIARIZE' in os.environ or USE_ASR_ENDPOINT else (recording.owner.diarize if recording.owner else False)++ # Enqueue the job+ job = job_queue.enqueue(+ func=transcribe_audio_asr,+ args=(app_context, recording.id, filepath, filename_for_asr, start_time, recording.mime_type, language, diarize_setting, min_speakers, max_speakers),+ recording_id=recording.id)else:- current_app.logger.info(f"Using standard transcription API for reprocessing recording {recording_id}")- start_time = datetime.utcnow()- thread = threading.Thread(- target=transcribe_audio_task,- args=(current_app._get_current_object().app_context(), recording.id, filepath, filename_for_asr, start_time)+ # Enqueue the job for standard Whisper API+ job = job_queue.enqueue(+ func=transcribe_audio_task,+ args=(app_context, recording.id, filepath, filename_for_asr, start_time),+ recording_id=recording.id)-- thread.start()- # Return recording with per-user status+ # Get queue position for response+ queue_position = job_queue.get_position_in_queue(recording.id)+ queue_status = job_queue.get_queue_status()++ # Return recording with per-user status and queue inforecording_dict = recording.to_dict(viewer_user=current_user)enrich_recording_dict_with_user_status(recording_dict, recording, current_user)return jsonify({'success': True,- 'message': 'Transcription reprocessing started',- 'recording': recording_dict+ 'message': 'Transcription reprocessing queued',+ 'recording': recording_dict,+ 'queue_position': queue_position,+ 'queue_status': queue_status})except Exception as e:diff --git a/src/config/startup.py b/src/config/startup.pyindex 10e113d8..44164b21 100644--- a/src/config/startup.py+++ b/src/config/startup.py@@ -108,6 +108,16 @@ def initialize_file_exporter(app):app.logger.warning(f"File exporter initialization failed: {e}")+def initialize_job_queue(app):+ """Initialize and start the background job queue."""+ try:+ from src.services.job_queue import job_queue+ job_queue.start()+ app.logger.info("Job queue started with 2 workers")+ except Exception as e:+ app.logger.error(f"Failed to start job queue: {e}")++def run_startup_tasks(app):"""Run all startup tasks that need to happen after app creation."""from src.models import SystemSetting@@ -118,6 +128,9 @@ def run_startup_tasks(app):app.config['MAX_CONTENT_LENGTH'] = max_file_size_mb * 1024 * 1024app.logger.info(f"Set MAX_CONTENT_LENGTH to {max_file_size_mb}MB from database setting")+ # Initialize job queue for background processing+ initialize_job_queue(app)+# Initialize file monitor after app setupinitialize_file_monitor(app)diff --git a/src/services/job_queue.py b/src/services/job_queue.pynew file mode 100644index 00000000..2063fcb1--- /dev/null+++ b/src/services/job_queue.py@@ -0,0 +1,283 @@+"""+Simple job queue for background processing tasks.+Ensures jobs run sequentially or with limited concurrency to prevent+overwhelming external services like ASR endpoints.+"""++import threading+import queue+import logging+from datetime import datetime+from typing import Callable, Any, Dict, Optional+from dataclasses import dataclass, field+from enum import Enum++logger = logging.getLogger(__name__)+++class JobStatus(Enum):+ QUEUED = "queued"+ RUNNING = "running"+ COMPLETED = "completed"+ FAILED = "failed"+++@dataclass+class Job:+ """Represents a background processing job."""+ id: str+ func: Callable+ args: tuple = field(default_factory=tuple)+ kwargs: dict = field(default_factory=dict)+ status: JobStatus = JobStatus.QUEUED+ created_at: datetime = field(default_factory=datetime.utcnow)+ started_at: Optional[datetime] = None+ completed_at: Optional[datetime] = None+ error: Optional[str] = None+ recording_id: Optional[int] = None # For tracking which recording this job is for+++class JobQueue:+ """+ A simple job queue that processes jobs with limited concurrency.++ Features:+ - Configurable max concurrent workers+ - Job status tracking+ - Prevents duplicate jobs for the same recording+ """++ _instance = None+ _lock = threading.Lock()++ def __new__(cls, max_workers: int = 2):+ """Singleton pattern to ensure only one queue exists."""+ if cls._instance is None:+ with cls._lock:+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ cls._instance._initialized = False+ cls._instance._max_workers_init = max_workers+ return cls._instance++ def __init__(self, max_workers: int = 2):+ """Initialize the job queue."""+ if self._initialized:+ return++ self._queue = queue.Queue()+ self._jobs: Dict[str, Job] = {}+ self._recording_jobs: Dict[int, str] = {} # Maps recording_id to job_id+ self._max_workers = getattr(self, '_max_workers_init', max_workers)+ self._workers: list = []+ self._running = False+ self._jobs_lock = threading.Lock()+ self._initialized = True++ logger.info(f"JobQueue initialized with max_workers={self._max_workers}")++ def start(self):+ """Start the worker threads."""+ if self._running:+ return++ self._running = True+ for i in range(self._max_workers):+ worker = threading.Thread(+ target=self._worker_loop,+ name=f"JobQueueWorker-{i}",+ daemon=True+ )+ worker.start()+ self._workers.append(worker)++ logger.info(f"Started {self._max_workers} job queue workers")++ def stop(self):+ """Stop the worker threads."""+ self._running = False+ # Put None items to unblock workers+ for _ in self._workers:+ self._queue.put(None)+ for worker in self._workers:+ worker.join(timeout=5)+ self._workers.clear()+ logger.info("Job queue workers stopped")++ def _worker_loop(self):+ """Main worker loop that processes jobs from the queue."""+ while self._running:+ try:+ job = self._queue.get(timeout=0.1) # Check every 100ms for faster pickup+ if job is None:+ continue++ self._process_job(job)+ self._queue.task_done()++ except queue.Empty:+ continue+ except Exception as e:+ logger.error(f"Worker error: {e}")++ def _process_job(self, job: Job):+ """Process a single job."""+ wait_time = (datetime.utcnow() - job.created_at).total_seconds()+ logger.info(f"Starting job {job.id} for recording {job.recording_id} (waited {wait_time:.2f}s in queue)")++ with self._jobs_lock:+ job.status = JobStatus.RUNNING+ job.started_at = datetime.utcnow()++ try:+ job.func(*job.args, **job.kwargs)++ with self._jobs_lock:+ job.status = JobStatus.COMPLETED+ job.completed_at = datetime.utcnow()++ logger.info(f"Job {job.id} completed successfully")++ except Exception as e:+ logger.error(f"Job {job.id} failed: {e}")++ with self._jobs_lock:+ job.status = JobStatus.FAILED+ job.completed_at = datetime.utcnow()+ job.error = str(e)++ finally:+ # Clean up recording job mapping+ with self._jobs_lock:+ if job.recording_id and job.recording_id in self._recording_jobs:+ del self._recording_jobs[job.recording_id]++ def enqueue(+ self,+ func: Callable,+ args: tuple = (),+ kwargs: dict = None,+ job_id: str = None,+ recording_id: int = None+ ) -> Job:+ """+ Add a job to the queue.++ Args:+ func: The function to call+ args: Positional arguments for the function+ kwargs: Keyword arguments for the function+ job_id: Optional custom job ID+ recording_id: Optional recording ID to prevent duplicate jobs++ Returns:+ The created Job object+ """+ # Auto-start workers if not running+ if not self._running:+ self.start()++ if kwargs is None:+ kwargs = {}++ # Generate job ID if not provided+ if job_id is None:+ job_id = f"job_{datetime.utcnow().strftime('%Y%m%d_%H%M%S_%f')}"++ # Check for existing job for this recording+ with self._jobs_lock:+ if recording_id and recording_id in self._recording_jobs:+ existing_job_id = self._recording_jobs[recording_id]+ existing_job = self._jobs.get(existing_job_id)+ if existing_job and existing_job.status in [JobStatus.QUEUED, JobStatus.RUNNING]:+ logger.warning(f"Job already exists for recording {recording_id}: {existing_job_id}")+ return existing_job++ # Create the job+ job = Job(+ id=job_id,+ func=func,+ args=args,+ kwargs=kwargs,+ recording_id=recording_id+ )++ with self._jobs_lock:+ self._jobs[job_id] = job+ if recording_id:+ self._recording_jobs[recording_id] = job_id++ # Add to queue+ self._queue.put(job)++ logger.info(f"Enqueued job {job_id} for recording {recording_id}, queue size: {self._queue.qsize()}")++ return job++ def get_job(self, job_id: str) -> Optional[Job]:+ """Get a job by ID."""+ with self._jobs_lock:+ return self._jobs.get(job_id)++ def get_job_for_recording(self, recording_id: int) -> Optional[Job]:+ """Get the active job for a recording."""+ with self._jobs_lock:+ job_id = self._recording_jobs.get(recording_id)+ if job_id:+ return self._jobs.get(job_id)+ return None++ def get_queue_status(self) -> Dict[str, Any]:+ """Get the current queue status."""+ with self._jobs_lock:+ queued = sum(1 for j in self._jobs.values() if j.status == JobStatus.QUEUED)+ running = sum(1 for j in self._jobs.values() if j.status == JobStatus.RUNNING)++ return {+ "queue_size": self._queue.qsize(),+ "queued_jobs": queued,+ "running_jobs": running,+ "max_workers": self._max_workers,+ "is_running": self._running+ }++ def get_position_in_queue(self, recording_id: int) -> Optional[int]:+ """Get the position of a recording's job in the queue (1-indexed)."""+ with self._jobs_lock:+ job_id = self._recording_jobs.get(recording_id)+ if not job_id:+ return None++ job = self._jobs.get(job_id)+ if not job or job.status != JobStatus.QUEUED:+ return None++ # Count queued jobs created before this one+ position = 1+ for j in self._jobs.values():+ if j.status == JobStatus.QUEUED and j.created_at < job.created_at:+ position += 1++ return position++ def cleanup_old_jobs(self, max_age_hours: int = 24):+ """Remove completed/failed jobs older than max_age_hours."""+ from datetime import timedelta+ cutoff = datetime.utcnow() - timedelta(hours=max_age_hours)++ with self._jobs_lock:+ to_remove = [+ job_id for job_id, job in self._jobs.items()+ if job.status in [JobStatus.COMPLETED, JobStatus.FAILED]+ and job.completed_at and job.completed_at < cutoff+ ]++ for job_id in to_remove:+ del self._jobs[job_id]++ if to_remove:+ logger.info(f"Cleaned up {len(to_remove)} old jobs")+++# Global job queue instance+job_queue = JobQueue(max_workers=2)diff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 8623ed3c..c96c7533 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -975,7 +975,8 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,with httpx.Client() as client:# Get configurable ASR timeout from database (default 30 minutes)asr_timeout_seconds = SystemSetting.get_setting('asr_timeout_seconds', 1800)- timeout = httpx.Timeout(None, connect=30.0, read=float(asr_timeout_seconds), write=30.0, pool=30.0)+ # Use generous timeouts: write=300s for large file uploads, pool=None to wait indefinitely+ timeout = httpx.Timeout(None, connect=60.0, read=float(asr_timeout_seconds), write=300.0, pool=None)current_app.logger.info(f"Sending ASR request to {url} with params: {params} (timeout: {asr_timeout_seconds}s)")response = client.post(url, params=params, files=files, timeout=timeout)current_app.logger.info(f"ASR request completed with status: {response.status_code}")@@ -1176,13 +1177,14 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,# Handle timeout errors specificallyerror_msg = str(e)- if "timed out" in error_msg.lower() or "timeout" in error_msg.lower():+ error_type = type(e).__name__+ current_app.logger.error(f"ASR processing FAILED for recording {recording_id}: [{error_type}] {error_msg}")++ if "timed out" in error_msg.lower() or "timeout" in error_msg.lower() or "Timeout" in error_type:asr_timeout = SystemSetting.get_setting('asr_timeout_seconds', 1800)- current_app.logger.error(f"ASR processing TIMED OUT for recording {recording_id} after {asr_timeout} seconds. Consider increasing 'asr_timeout_seconds' in Admin Dashboard > System Settings.")- user_error_msg = f"ASR processing timed out after {asr_timeout} seconds. The file may be too long for the current timeout setting."+ current_app.logger.error(f"Timeout details - configured ASR timeout: {asr_timeout}s. Error: {error_msg}")+ user_error_msg = f"ASR processing timed out. Error: {error_msg}"else:- # For non-timeout errors, include more detail- current_app.logger.error(f"ASR processing FAILED for recording {recording_id}: {error_msg}")user_error_msg = f"ASR processing failed: {error_msg}"recording = db.session.get(Recording, recording_id)diff --git a/static/js/modules/composables/reprocess.js b/static/js/modules/composables/reprocess.jsindex 28d34291..85c1b0f1 100644--- a/static/js/modules/composables/reprocess.js+++ b/static/js/modules/composables/reprocess.js@@ -285,7 +285,6 @@ export function useReprocess(state, utils) {// Update status in recordings listconst index = recordings.value.findIndex(r => r.id === recordingId);- console.log(`[REPROCESS] Status update: ${statusData.status} for recording ${recordingId}`);if (index !== -1) {// Create new object to ensure Vue reactivity@@ -297,7 +296,6 @@ export function useReprocess(state, utils) {// Update selectedRecording with new object reference for reactivityif (selectedRecording.value?.id === recordingId) {- console.log(`[REPROCESS] Updating selectedRecording status to: ${statusData.status}`);selectedRecording.value = {...selectedRecording.value,status: statusData.statusdiff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.jsindex 0c05b963..5343f2ca 100644--- a/static/js/modules/composables/ui.js+++ b/static/js/modules/composables/ui.js@@ -219,6 +219,7 @@ export function useUI(state, utils, processedTranscription) {if (!status || status === 'COMPLETED') return '';const statusMap = {'PENDING': t('status.queued'),+ 'QUEUED': t('status.queued'),'PROCESSING': t('status.processing'),'TRANSCRIBING': t('status.transcribing'),'SUMMARIZING': t('status.summarizing'),@@ -232,6 +233,7 @@ export function useUI(state, utils, processedTranscription) {const getStatusClass = (status) => {switch(status) {case 'PENDING': return 'status-pending';+ case 'QUEUED': return 'status-pending';case 'PROCESSING': return 'status-processing';case 'SUMMARIZING': return 'status-summarizing';case 'COMPLETED': return '';diff --git a/static/js/modules/utils/formatters.js b/static/js/modules/utils/formatters.jsindex db19f014..e5e6a859 100644--- a/static/js/modules/utils/formatters.js+++ b/static/js/modules/utils/formatters.js@@ -71,6 +71,7 @@ export const formatStatus = (status, t) => {if (!status || status === 'COMPLETED') return '';const statusMap = {'PENDING': t('status.queued'),+ 'QUEUED': t('status.queued'),'PROCESSING': t('status.processing'),'TRANSCRIBING': t('status.transcribing'),'SUMMARIZING': t('status.summarizing'),@@ -83,6 +84,7 @@ export const formatStatus = (status, t) => {export const getStatusClass = (status) => {switch(status) {case 'PENDING': return 'status-pending';+ case 'QUEUED': return 'status-pending';case 'PROCESSING': return 'status-processing';case 'SUMMARIZING': return 'status-summarizing';case 'COMPLETED': return '';