Skip to content

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

Python

Add STT connector architecture phase 2: data-driven UI, specifications, and simplified config

Murtaza Nasir2c2437758d14
diff --git a/.gitignore b/.gitignore
index c90146a0..00ca1a2d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,7 +7,7 @@ uploads/
__pycache__/
*.pyc
*.log
-.env
+*.env
.migrate/
project_files.md
*.md
diff --git a/config/env.transcription.example b/config/env.transcription.example
new file mode 100644
index 00000000..7cff0713
--- /dev/null
+++ b/config/env.transcription.example
@@ -0,0 +1,129 @@
+# =============================================================================
+# Transcription Connector Configuration
+# =============================================================================
+#
+# Speakr supports multiple transcription providers through a connector-based
+# architecture. This file documents all available configuration options.
+#
+# Quick Start (Simplified):
+# 1. For OpenAI with diarization: Set TRANSCRIPTION_MODEL=gpt-4o-transcribe-diarize
+# 2. For self-hosted ASR: Set ASR_BASE_URL=http://your-asr:9000
+# 3. For legacy Whisper: Set TRANSCRIPTION_API_KEY and optionally TRANSCRIPTION_MODEL
+#
+# Auto-Detection Priority:
+# 1. TRANSCRIPTION_CONNECTOR - explicit connector name (if you need full control)
+# 2. ASR_BASE_URL - if set, uses ASR endpoint connector
+# 3. TRANSCRIPTION_MODEL contains 'gpt-4o' - uses OpenAI Transcribe connector
+# 4. Default - uses OpenAI Whisper connector with TRANSCRIPTION_MODEL or whisper-1
+
+# =============================================================================
+# CONNECTOR SELECTION (Auto-detected if not set)
+# =============================================================================
+# Options: openai_whisper, openai_transcribe, asr_endpoint
+# Leave empty to auto-detect based on other settings
+# TRANSCRIPTION_CONNECTOR=
+
+# Feature flag to enable/disable new connector architecture (default: true)
+# Set to false to use legacy code path for troubleshooting
+# USE_NEW_TRANSCRIPTION_ARCHITECTURE=true
+
+# =============================================================================
+# OPENAI CONFIGURATION (Required for openai_whisper and openai_transcribe)
+# =============================================================================
+TRANSCRIPTION_API_KEY=your_openai_api_key
+TRANSCRIPTION_BASE_URL=https://api.openai.com/v1
+
+# Model Selection - determines which connector is used:
+#
+# whisper-1 - Legacy Whisper model, no diarization, $0.006/min
+# Supports: srt, vtt, json, verbose_json output formats
+#
+# gpt-4o-transcribe - High quality transcription, no diarization, $0.006/min
+# Better accuracy than whisper-1, accepts prompts
+#
+# gpt-4o-mini-transcribe - Cost-effective option, no diarization, $0.003/min
+# Good for high-volume, budget-conscious use
+#
+# gpt-4o-transcribe-diarize - Speaker diarization!, $0.006/min
+# Identifies speakers as A, B, C, D...
+# Requires chunking_strategy for audio >30s
+#
+TRANSCRIPTION_MODEL=gpt-4o-transcribe-diarize
+
+# Legacy Whisper model name (used when TRANSCRIPTION_MODEL is not set)
+# WHISPER_MODEL=whisper-1
+
+# =============================================================================
+# ASR ENDPOINT CONFIGURATION (For self-hosted whisper services)
+# =============================================================================
+# Note: USE_ASR_ENDPOINT is deprecated. Just set ASR_BASE_URL instead.
+# The connector will auto-detect ASR mode when ASR_BASE_URL is set.
+# USE_ASR_ENDPOINT=true # Deprecated - kept for backwards compatibility
+
+# Base URL of your ASR service (required if USE_ASR_ENDPOINT=true)
+# Supports: whisper-asr-webservice, WhisperX, and compatible services
+# ASR_BASE_URL=http://whisper-asr:9000
+
+# Request timeout in seconds (default: 1800 = 30 minutes)
+# Increase for very long audio files
+# ASR_TIMEOUT=1800
+
+# Enable speaker diarization (default: true)
+# ASR_DIARIZE=true
+
+# Speaker count hints (optional, helps with diarization accuracy)
+# ASR_MIN_SPEAKERS=1
+# ASR_MAX_SPEAKERS=5
+
+# Return speaker embeddings for speaker identification (WhisperX only)
+# Enables automatic speaker matching across recordings
+# ASR_RETURN_SPEAKER_EMBEDDINGS=false
+
+# =============================================================================
+# CHUNKING CONFIGURATION (For large files)
+# =============================================================================
+# Enable automatic file chunking for large audio files
+ENABLE_CHUNKING=true
+
+# Maximum chunk size in MB (files larger than this will be split)
+CHUNK_SIZE_MB=20
+
+# Overlap between chunks in seconds (helps with transcription accuracy at boundaries)
+CHUNK_OVERLAP_SECONDS=3
+
+# =============================================================================
+# EXAMPLE CONFIGURATIONS (Simplified)
+# =============================================================================
+#
+# --- OpenAI with Speaker Diarization (Recommended) ---
+# Just two environment variables needed:
+# TRANSCRIPTION_API_KEY=sk-xxx
+# TRANSCRIPTION_MODEL=gpt-4o-transcribe-diarize
+#
+# --- Self-hosted WhisperX (Best for privacy) ---
+# Just one environment variable needed (auto-detects ASR mode):
+# ASR_BASE_URL=http://whisper-asr:9000
+# Optional:
+# ASR_DIARIZE=true
+# ASR_RETURN_SPEAKER_EMBEDDINGS=true
+#
+# --- OpenAI Whisper (Legacy, no diarization) ---
+# TRANSCRIPTION_API_KEY=sk-xxx
+# TRANSCRIPTION_MODEL=whisper-1
+#
+# --- Custom Whisper model (local or compatible endpoint) ---
+# TRANSCRIPTION_API_KEY=not-needed
+# TRANSCRIPTION_BASE_URL=http://localhost:8080/v1
+# TRANSCRIPTION_MODEL=Systran/faster-distil-whisper-large-v3
+
+# =============================================================================
+# FUTURE: Additional Provider Notes
+# =============================================================================
+# The connector architecture is designed to support additional providers.
+# Future connectors may include:
+#
+# - Deepgram: Known for excellent diarization and real-time transcription
+# - AssemblyAI: Strong diarization with speaker labels
+# - Google Cloud Speech-to-Text: Enterprise-grade with speaker diarization
+#
+# To request a new connector, please open an issue on GitHub.
diff --git a/src/api/auth.py b/src/api/auth.py
index 0250ab23..08b0aa09 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -369,9 +369,22 @@ def account():
asr_diarize_locked = 'ASR_DIARIZE' in os.environ
ASR_DIARIZE = os.environ.get('ASR_DIARIZE', 'false').lower() == 'true'
USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ USE_NEW_TRANSCRIPTION_ARCHITECTURE = os.environ.get('USE_NEW_TRANSCRIPTION_ARCHITECTURE', 'true').lower() == 'true'
ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+ # Get connector diarization support (new architecture)
+ connector_supports_diarization = USE_ASR_ENDPOINT # Default to USE_ASR_ENDPOINT for backwards compat
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.get_active_connector()
+ if connector:
+ connector_supports_diarization = connector.supports_diarization
+ except Exception as e:
+ current_app.logger.warning(f"Could not get connector diarization support: {e}")
+
# Check if user is a team admin and get their admin groups
admin_memberships = GroupMembership.query.filter_by(
user_id=current_user.id,
@@ -401,6 +414,7 @@ def account():
title='Account',
default_summary_prompt_text=default_summary_prompt_text,
use_asr_endpoint=USE_ASR_ENDPOINT,
+ connector_supports_diarization=connector_supports_diarization,
enable_auto_deletion=ENABLE_AUTO_DELETION,
enable_internal_sharing=ENABLE_INTERNAL_SHARING,
user_admin_groups=user_admin_groups,
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 9923bdc4..794d1c6b 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -22,7 +22,7 @@ from email.utils import encode_rfc2231
from src.database import db
from src.models import *
from src.utils import *
-from src.config.app_config import ASR_MIN_SPEAKERS, ASR_MAX_SPEAKERS, ASR_DIARIZE
+from src.config.app_config import ASR_MIN_SPEAKERS, ASR_MAX_SPEAKERS, ASR_DIARIZE, USE_NEW_TRANSCRIPTION_ARCHITECTURE
from src.tasks.processing import format_transcription_for_llm, transcribe_with_chunking
from src.utils.ffmpeg_utils import FFmpegError, FFmpegNotFoundError
from src.services.speaker import update_speaker_usage, identify_unidentified_speakers_from_text
@@ -1268,8 +1268,25 @@ def index():
# Calculate if archive toggle should be shown (only when audio-only deletion mode is active)
enable_archive_toggle = ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only'
+ # Get connector capabilities (new architecture)
+ # Defaults to USE_ASR_ENDPOINT for backwards compatibility
+ connector_supports_diarization = USE_ASR_ENDPOINT
+ connector_supports_speaker_count = USE_ASR_ENDPOINT # ASR endpoint supports min/max speakers
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.get_active_connector()
+ if connector:
+ connector_supports_diarization = connector.supports_diarization
+ connector_supports_speaker_count = connector.supports_speaker_count_control
+ except Exception as e:
+ current_app.logger.warning(f"Could not get connector capabilities: {e}")
+
return render_template('index.html',
- use_asr_endpoint=USE_ASR_ENDPOINT,
+ use_asr_endpoint=USE_ASR_ENDPOINT, # Backwards compat
+ connector_supports_diarization=connector_supports_diarization,
+ connector_supports_speaker_count=connector_supports_speaker_count,
inquire_mode_enabled=ENABLE_INQUIRE_MODE,
enable_archive_toggle=enable_archive_toggle,
enable_internal_sharing=ENABLE_INTERNAL_SHARING,
@@ -1959,19 +1976,34 @@ def upload_file():
original_file_size = file.tell()
file.seek(0)
- # Check size limit before saving - only enforce if chunking is disabled or using ASR endpoint
+ # Check size limit before saving - only enforce if chunking is disabled or connector handles it
max_content_length = current_app.config.get('MAX_CONTENT_LENGTH')
- # Skip size check if chunking is enabled and using OpenAI Whisper API
+ # Get connector specifications for chunking decisions
+ connector_specs = None
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.get_active_connector()
+ if connector:
+ connector_specs = connector.specifications
+ except Exception as e:
+ current_app.logger.warning(f"Could not get connector specs for upload: {e}")
+
+ # Skip size check if chunking is enabled (app-level or connector handles internally)
should_enforce_size_limit = True
- if ENABLE_CHUNKING and chunking_service and not USE_ASR_ENDPOINT:
- should_enforce_size_limit = False
- # Get chunking mode for better logging
- mode, limit_value = chunking_service.parse_chunk_limit()
- if mode == 'size':
- current_app.logger.info(f"Size-based chunking enabled ({limit_value}MB limit) - skipping {original_file_size/1024/1024:.1f}MB size limit check")
- else:
- current_app.logger.info(f"Duration-based chunking enabled ({limit_value}s limit) - skipping {original_file_size/1024/1024:.1f}MB size limit check")
+ if chunking_service:
+ from src.audio_chunking import get_effective_chunking_config
+ chunking_config = get_effective_chunking_config(connector_specs)
+ if chunking_config.enabled or chunking_config.source == 'connector_internal':
+ should_enforce_size_limit = False
+ if chunking_config.source == 'connector_internal':
+ current_app.logger.info(f"Connector handles chunking internally - skipping {original_file_size/1024/1024:.1f}MB size limit check")
+ elif chunking_config.mode == 'size':
+ current_app.logger.info(f"Size-based chunking enabled ({chunking_config.limit_value}MB, source={chunking_config.source}) - skipping {original_file_size/1024/1024:.1f}MB size limit check")
+ else:
+ current_app.logger.info(f"Duration-based chunking enabled ({chunking_config.limit_value}s, source={chunking_config.source}) - skipping {original_file_size/1024/1024:.1f}MB size limit check")
if should_enforce_size_limit and max_content_length and original_file_size > max_content_length:
raise RequestEntityTooLarge()
@@ -1982,12 +2014,10 @@ def upload_file():
# --- Convert files only when chunking is needed ---
filename_lower = original_filename.lower()
- # Check if chunking will be needed for this file
+ # Check if chunking will be needed for this file (uses connector-aware logic)
needs_chunking_for_processing = bool(
chunking_service and
- ENABLE_CHUNKING and
- not USE_ASR_ENDPOINT and
- chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT)
+ chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT, connector_specs)
)
# Probe once and use shared conversion utility
diff --git a/src/api/system.py b/src/api/system.py
index 9bd537d6..94bb8cb7 100644
--- a/src/api/system.py
+++ b/src/api/system.py
@@ -16,8 +16,9 @@ from src.models import *
from src.utils import *
from src.config.version import get_version
from src.services.llm import TEXT_MODEL_BASE_URL, TEXT_MODEL_NAME
-from src.config.app_config import ASR_BASE_URL
+from src.config.app_config import ASR_BASE_URL, USE_NEW_TRANSCRIPTION_ARCHITECTURE
from src.services.token_tracking import token_tracker
+from src.services.transcription import TranscriptionCapability
# Create blueprint
system_bp = Blueprint('system', __name__)
@@ -121,14 +122,36 @@ def get_system_info():
try:
# Use the same version detection logic as startup
version = get_version()
-
+
+ # Get transcription connector info
+ transcription_info = {
+ 'connector': 'unknown',
+ 'supports_diarization': USE_ASR_ENDPOINT, # Backwards compatible default
+ 'supports_speaker_embeddings': False,
+ }
+
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.get_active_connector()
+ if connector:
+ transcription_info = {
+ 'connector': registry.get_active_connector_name(),
+ 'supports_diarization': connector.supports_diarization,
+ 'supports_speaker_embeddings': connector.supports(TranscriptionCapability.SPEAKER_EMBEDDINGS),
+ }
+ except Exception as e:
+ current_app.logger.warning(f"Could not get connector info: {e}")
+
return jsonify({
'version': version,
'llm_endpoint': TEXT_MODEL_BASE_URL,
'llm_model': TEXT_MODEL_NAME,
'whisper_endpoint': os.environ.get('TRANSCRIPTION_BASE_URL', 'https://api.openai.com/v1'),
- 'asr_enabled': USE_ASR_ENDPOINT,
- 'asr_endpoint': ASR_BASE_URL if USE_ASR_ENDPOINT else None
+ 'asr_enabled': USE_ASR_ENDPOINT, # Backwards compat
+ 'asr_endpoint': ASR_BASE_URL if USE_ASR_ENDPOINT else None,
+ 'transcription': transcription_info,
})
except Exception as e:
current_app.logger.error(f"Error getting system info: {e}")
@@ -143,7 +166,7 @@ def get_config():
try:
# Get configurable file size limit
max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
-
+
# Get chunking configuration (supports both legacy and new formats)
chunking_info = {}
if ENABLE_CHUNKING and chunking_service:
@@ -174,10 +197,27 @@ def get_config():
# Calculate if archive toggle should be shown (only when audio-only deletion mode is active)
enable_archive_toggle = ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only'
+ # Get connector capabilities (new architecture)
+ # Defaults to USE_ASR_ENDPOINT for backwards compatibility
+ connector_supports_diarization = USE_ASR_ENDPOINT
+ connector_supports_speaker_count = USE_ASR_ENDPOINT # ASR endpoint supports min/max speakers
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.get_active_connector()
+ if connector:
+ connector_supports_diarization = connector.supports_diarization
+ connector_supports_speaker_count = connector.supports_speaker_count_control
+ except Exception as e:
+ current_app.logger.warning(f"Could not get connector capabilities: {e}")
+
return jsonify({
'max_file_size_mb': max_file_size_mb,
'recording_disclaimer': SystemSetting.get_setting('recording_disclaimer', ''),
- 'use_asr_endpoint': USE_ASR_ENDPOINT,
+ 'use_asr_endpoint': USE_ASR_ENDPOINT, # Backwards compat
+ 'connector_supports_diarization': connector_supports_diarization, # Connector capability
+ 'connector_supports_speaker_count': connector_supports_speaker_count, # Min/max speakers
'enable_internal_sharing': ENABLE_INTERNAL_SHARING,
'enable_archive_toggle': enable_archive_toggle,
'show_usernames_in_ui': SHOW_USERNAMES_IN_UI,
diff --git a/src/audio_chunking.py b/src/audio_chunking.py
index 9e498434..f025b2f3 100644
--- a/src/audio_chunking.py
+++ b/src/audio_chunking.py
@@ -13,15 +13,187 @@ import tempfile
import logging
import math
import re
-from typing import List, Dict, Any, Optional, Tuple
+from dataclasses import dataclass
+from typing import List, Dict, Any, Optional, Tuple, TYPE_CHECKING
from datetime import datetime
import mimetypes
from src.utils.ffmpeg_utils import convert_to_mp3, FFmpegError, FFmpegNotFoundError
+if TYPE_CHECKING:
+ from src.services.transcription.base import ConnectorSpecifications
+
# Configure logging
logger = logging.getLogger(__name__)
+
+@dataclass
+class EffectiveChunkingConfig:
+ """Effective chunking configuration after resolving connector specs and ENV settings."""
+ enabled: bool
+ mode: str # 'size' or 'duration'
+ limit_value: float # MB for size, seconds for duration
+ overlap_seconds: int
+ source: str # 'disabled', 'connector_internal', 'env', 'connector_default', 'app_default'
+
+
+def get_effective_chunking_config(
+ connector_specs: Optional['ConnectorSpecifications'] = None
+) -> EffectiveChunkingConfig:
+ """
+ Determine effective chunking configuration based on connector specs and ENV settings.
+
+ Priority order:
+ 1. If connector handles_chunking_internally=True → no app-level chunking
+ 2. If ENABLE_CHUNKING=false → no chunking
+ 3. If CHUNK_LIMIT or CHUNK_SIZE_MB is explicitly set → use ENV settings
+ 4. If connector has specs → use connector defaults (max_file_size or recommended_chunk_seconds)
+ 5. Fallback: 20MB size-based chunking
+
+ Args:
+ connector_specs: Optional ConnectorSpecifications from the active connector
+
+ Returns:
+ EffectiveChunkingConfig with resolved settings
+ """
+ overlap_seconds = int(os.environ.get('CHUNK_OVERLAP_SECONDS', '3'))
+
+ # Priority 1: Connector handles chunking internally
+ if connector_specs and connector_specs.handles_chunking_internally:
+ logger.debug("Chunking: Connector handles chunking internally, no app-level chunking needed")
+ return EffectiveChunkingConfig(
+ enabled=False,
+ mode='none',
+ limit_value=0,
+ overlap_seconds=overlap_seconds,
+ source='connector_internal'
+ )
+
+ # Priority 2: User explicitly disabled chunking
+ enable_chunking_env = os.environ.get('ENABLE_CHUNKING', '').lower()
+ if enable_chunking_env == 'false':
+ logger.debug("Chunking: Disabled via ENABLE_CHUNKING=false")
+ return EffectiveChunkingConfig(
+ enabled=False,
+ mode='none',
+ limit_value=0,
+ overlap_seconds=overlap_seconds,
+ source='disabled'
+ )
+
+ # Priority 3: User has set CHUNK_LIMIT or CHUNK_SIZE_MB explicitly
+ chunk_limit = os.environ.get('CHUNK_LIMIT', '').strip()
+ chunk_size_mb_env = os.environ.get('CHUNK_SIZE_MB', '').strip()
+
+ if chunk_limit:
+ # Parse CHUNK_LIMIT (20MB, 600s, 10m)
+ chunk_limit_upper = chunk_limit.upper()
+
+ if chunk_limit_upper.endswith('MB'):
+ try:
+ size_mb = float(re.sub(r'[^0-9.]', '', chunk_limit_upper))
+ logger.debug(f"Chunking: Using ENV CHUNK_LIMIT={size_mb}MB")
+ return EffectiveChunkingConfig(
+ enabled=True,
+ mode='size',
+ limit_value=size_mb,
+ overlap_seconds=overlap_seconds,
+ source='env'
+ )
+ except ValueError:
+ logger.warning(f"Invalid CHUNK_LIMIT format: {chunk_limit}")
+
+ elif chunk_limit_upper.endswith('S'):
+ try:
+ seconds = float(re.sub(r'[^0-9.]', '', chunk_limit_upper))
+ logger.debug(f"Chunking: Using ENV CHUNK_LIMIT={seconds}s")
+ return EffectiveChunkingConfig(
+ enabled=True,
+ mode='duration',
+ limit_value=seconds,
+ overlap_seconds=overlap_seconds,
+ source='env'
+ )
+ except ValueError:
+ logger.warning(f"Invalid CHUNK_LIMIT format: {chunk_limit}")
+
+ elif chunk_limit_upper.endswith('M') and not chunk_limit_upper.endswith('MB'):
+ try:
+ minutes = float(re.sub(r'[^0-9.]', '', chunk_limit_upper))
+ logger.debug(f"Chunking: Using ENV CHUNK_LIMIT={minutes}m ({minutes * 60}s)")
+ return EffectiveChunkingConfig(
+ enabled=True,
+ mode='duration',
+ limit_value=minutes * 60,
+ overlap_seconds=overlap_seconds,
+ source='env'
+ )
+ except ValueError:
+ logger.warning(f"Invalid CHUNK_LIMIT format: {chunk_limit}")
+
+ elif chunk_size_mb_env:
+ # Legacy CHUNK_SIZE_MB
+ try:
+ size_mb = float(chunk_size_mb_env)
+ logger.debug(f"Chunking: Using legacy ENV CHUNK_SIZE_MB={size_mb}MB")
+ return EffectiveChunkingConfig(
+ enabled=True,
+ mode='size',
+ limit_value=size_mb,
+ overlap_seconds=overlap_seconds,
+ source='env'
+ )
+ except ValueError:
+ logger.warning(f"Invalid CHUNK_SIZE_MB format: {chunk_size_mb_env}")
+
+ # Priority 4: Use connector specifications
+ if connector_specs:
+ # Prefer max_file_size_bytes if set
+ if connector_specs.max_file_size_bytes:
+ size_mb = connector_specs.max_file_size_bytes / (1024 * 1024)
+ # Use 80% of max to leave safety margin
+ safe_size_mb = size_mb * 0.8
+ logger.debug(f"Chunking: Using connector max_file_size ({size_mb}MB, safe: {safe_size_mb}MB)")
+ return EffectiveChunkingConfig(
+ enabled=True,
+ mode='size',
+ limit_value=safe_size_mb,
+ overlap_seconds=overlap_seconds,
+ source='connector_default'
+ )
+
+ # Fall back to recommended_chunk_seconds
+ if connector_specs.recommended_chunk_seconds:
+ logger.debug(f"Chunking: Using connector recommended_chunk_seconds={connector_specs.recommended_chunk_seconds}s")
+ return EffectiveChunkingConfig(
+ enabled=True,
+ mode='duration',
+ limit_value=connector_specs.recommended_chunk_seconds,
+ overlap_seconds=overlap_seconds,
+ source='connector_default'
+ )
+
+ # Priority 5: App defaults (only if ENABLE_CHUNKING wasn't explicitly 'false')
+ # If ENABLE_CHUNKING is not set or is 'true', use defaults
+ if enable_chunking_env != 'false':
+ logger.debug("Chunking: Using app defaults (20MB size-based)")
+ return EffectiveChunkingConfig(
+ enabled=True,
+ mode='size',
+ limit_value=20.0,
+ overlap_seconds=overlap_seconds,
+ source='app_default'
+ )
+
+ # Final fallback: disabled
+ return EffectiveChunkingConfig(
+ enabled=False,
+ mode='none',
+ limit_value=0,
+ overlap_seconds=overlap_seconds,
+ source='disabled'
+ )
+
class AudioChunkingService:
"""Service for chunking large audio files and processing them with OpenAI Whisper API."""
@@ -40,49 +212,99 @@ class AudioChunkingService:
self.max_chunk_duration_seconds = max_chunk_duration_seconds
self.chunk_stats = [] # Track processing statistics
- def needs_chunking(self, file_path: str, use_asr_endpoint: bool = False) -> bool:
+ def needs_chunking(
+ self,
+ file_path: str,
+ use_asr_endpoint: bool = False,
+ connector_specs: Optional['ConnectorSpecifications'] = None
+ ) -> bool:
"""
- Check if a file needs to be chunked based on size and endpoint being used.
-
+ Check if a file needs to be chunked based on connector specs, ENV settings, and file size.
+
+ Priority order for chunking configuration:
+ 1. If connector handles_chunking_internally=True → no app-level chunking
+ 2. If ENABLE_CHUNKING=false → no chunking
+ 3. If CHUNK_LIMIT or CHUNK_SIZE_MB is explicitly set → use ENV settings
+ 4. If connector has specs → use connector defaults
+ 5. Fallback: 20MB size-based chunking
+
NOTE: For duration-based limits, this may return True even if chunking isn't needed,
because we need to convert the file first to check duration. The actual chunking
decision is made after conversion in calculate_optimal_chunking().
-
+
Args:
file_path: Path to the audio file
- use_asr_endpoint: Whether ASR endpoint is being used (no chunking needed)
-
+ use_asr_endpoint: DEPRECATED - use connector_specs instead
+ connector_specs: Optional ConnectorSpecifications from the active connector
+
Returns:
True if file might need chunking, False otherwise
"""
- if use_asr_endpoint:
+ # Get effective chunking configuration
+ chunking_config = get_effective_chunking_config(connector_specs)
+
+ # If chunking is disabled (by connector or user), return False
+ if not chunking_config.enabled:
+ logger.info(f"Chunking disabled (source: {chunking_config.source})")
return False
-
+
+ # Legacy fallback: if no connector_specs provided, check use_asr_endpoint
+ if connector_specs is None and use_asr_endpoint:
+ logger.info("Chunking: ASR endpoint detected (legacy), no chunking needed")
+ return False
+
try:
file_size = os.path.getsize(file_path)
- mode, limit_value = self.parse_chunk_limit()
-
- if mode == 'size':
+
+ if chunking_config.mode == 'size':
# For size-based limits, we can determine immediately
- chunk_size_bytes = limit_value * 1024 * 1024
+ chunk_size_bytes = chunking_config.limit_value * 1024 * 1024
needs_it = file_size > chunk_size_bytes
- logger.info(f"Size check: {file_size/1024/1024:.1f}MB vs limit {limit_value}MB - needs chunking: {needs_it}")
+ logger.info(f"Chunking check (size, source={chunking_config.source}): "
+ f"{file_size/1024/1024:.1f}MB vs limit {chunking_config.limit_value}MB - needs chunking: {needs_it}")
return needs_it
- else:
+ elif chunking_config.mode == 'duration':
# For duration-based limits, we need to check the actual duration
# Try to get duration without conversion first (fast check)
duration = self.get_audio_duration(file_path)
if duration:
- needs_it = duration > limit_value
- logger.info(f"Duration check: {duration:.1f}s vs limit {limit_value}s - needs chunking: {needs_it}")
+ needs_it = duration > chunking_config.limit_value
+ logger.info(f"Chunking check (duration, source={chunking_config.source}): "
+ f"{duration:.1f}s vs limit {chunking_config.limit_value}s - needs chunking: {needs_it}")
return needs_it
else:
# Can't determine duration without conversion, assume might need chunking
- logger.info(f"Duration-based limit set ({limit_value}s) but can't check duration yet - will check after conversion")
+ logger.info(f"Duration-based limit set ({chunking_config.limit_value}s) but can't check duration yet - will check after conversion")
return True # Proceed to conversion and check
+ else:
+ # Mode is 'none', shouldn't reach here but handle gracefully
+ return False
+
except OSError:
logger.error(f"Could not get file size for {file_path}")
return False
+
+ def needs_chunking_with_config(
+ self,
+ file_path: str,
+ connector_specs: Optional['ConnectorSpecifications'] = None
+ ) -> Tuple[bool, EffectiveChunkingConfig]:
+ """
+ Check if a file needs chunking and return the effective configuration.
+
+ This is useful when you need both the decision and the configuration
+ for subsequent processing.
+
+ Args:
+ file_path: Path to the audio file
+ connector_specs: Optional ConnectorSpecifications from the active connector
+
+ Returns:
+ Tuple of (needs_chunking, EffectiveChunkingConfig)
+ """
+ chunking_config = get_effective_chunking_config(connector_specs)
+ needs_it = self.needs_chunking(file_path, connector_specs=connector_specs)
+ return needs_it, chunking_config
def get_audio_duration(self, file_path: str) -> Optional[float]:
"""
diff --git a/src/config/app_config.py b/src/config/app_config.py
index e6e65520..1016edcb 100644
--- a/src/config/app_config.py
+++ b/src/config/app_config.py
@@ -22,6 +22,19 @@ transcription_base_url = os.environ.get("TRANSCRIPTION_BASE_URL", "")
if transcription_base_url:
transcription_base_url = transcription_base_url.split('#')[0].strip()
+# New transcription connector configuration
+# TRANSCRIPTION_CONNECTOR: explicit connector name (openai_whisper, openai_transcribe, asr_endpoint)
+# TRANSCRIPTION_MODEL: model to use (e.g., gpt-4o-transcribe-diarize for diarization)
+TRANSCRIPTION_CONNECTOR = os.environ.get('TRANSCRIPTION_CONNECTOR', '').lower().strip()
+TRANSCRIPTION_MODEL = os.environ.get('TRANSCRIPTION_MODEL', '')
+if TRANSCRIPTION_MODEL:
+ TRANSCRIPTION_MODEL = TRANSCRIPTION_MODEL.split('#')[0].strip()
+
+# Feature flag for new transcription architecture (default: enabled)
+USE_NEW_TRANSCRIPTION_ARCHITECTURE = os.environ.get(
+ 'USE_NEW_TRANSCRIPTION_ARCHITECTURE', 'true'
+).lower() == 'true'
+
USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
ASR_BASE_URL = os.environ.get('ASR_BASE_URL')
if ASR_BASE_URL:
@@ -81,6 +94,37 @@ def initialize_config(app):
app.logger.info(f"=== Speakr {version} Starting Up ===")
+ # Initialize transcription connector
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.initialize_from_env()
+ connector_name = registry.get_active_connector_name()
+ capabilities = [c.name for c in connector.get_capabilities()]
+ app.logger.info(f"Transcription connector initialized: {connector_name}")
+ app.logger.info(f"Connector capabilities: {capabilities}")
+
+ # Log diarization support prominently
+ if connector.supports_diarization:
+ app.logger.info("Speaker diarization: ENABLED")
+ else:
+ app.logger.info("Speaker diarization: NOT AVAILABLE (connector does not support it)")
+
+ except Exception as e:
+ app.logger.error(f"Failed to initialize transcription connector: {e}")
+ app.logger.error("Falling back to legacy transcription configuration validation")
+ # Fall through to legacy validation
+ _validate_legacy_transcription_config(app)
+ else:
+ # Legacy configuration validation
+ _validate_legacy_transcription_config(app)
+
+ return client, chunking_service, version
+
+
+def _validate_legacy_transcription_config(app):
+ """Validate legacy transcription configuration (backwards compatibility)."""
if USE_ASR_ENDPOINT:
if not ASR_BASE_URL:
app.logger.error("ERROR: ASR enabled but ASR_BASE_URL not configured!")
@@ -91,5 +135,3 @@ def initialize_config(app):
app.logger.error("ERROR: No transcription service configured!")
sys.exit(1)
app.logger.info(f"Using Whisper API: {transcription_base_url}")
-
- return client, chunking_service, version
diff --git a/src/services/transcription/__init__.py b/src/services/transcription/__init__.py
new file mode 100644
index 00000000..4b409f4d
--- /dev/null
+++ b/src/services/transcription/__init__.py
@@ -0,0 +1,98 @@
+"""
+Transcription service package.
+
+Provides a connector-based architecture for speech-to-text transcription
+with support for multiple providers:
+
+- OpenAI Whisper (whisper-1)
+- OpenAI GPT-4o Transcribe (gpt-4o-transcribe, gpt-4o-mini-transcribe, gpt-4o-transcribe-diarize)
+- Custom ASR endpoints (whisper-asr-webservice, WhisperX, etc.)
+
+Usage:
+ from src.services.transcription import (
+ transcribe,
+ get_connector,
+ supports_diarization,
+ TranscriptionRequest,
+ TranscriptionResponse,
+ )
+
+ # Simple transcription using active connector
+ with open('audio.mp3', 'rb') as f:
+ request = TranscriptionRequest(
+ audio_file=f,
+ filename='audio.mp3',
+ diarize=True
+ )
+ response = transcribe(request)
+ print(response.text)
+ if response.segments:
+ for seg in response.segments:
+ print(f"[{seg.speaker}]: {seg.text}")
+"""
+
+from .base import (
+ TranscriptionCapability,
+ TranscriptionRequest,
+ TranscriptionResponse,
+ TranscriptionSegment,
+ BaseTranscriptionConnector,
+ ConnectorSpecifications,
+ DEFAULT_SPECIFICATIONS,
+)
+
+from .exceptions import (
+ TranscriptionError,
+ ConfigurationError,
+ ProviderError,
+ AudioFormatError,
+ ChunkingError,
+)
+
+from .registry import (
+ ConnectorRegistry,
+ get_registry,
+ connector_registry,
+ transcribe,
+ get_connector,
+ supports_diarization,
+)
+
+from .connectors import (
+ OpenAIWhisperConnector,
+ OpenAITranscribeConnector,
+ ASREndpointConnector,
+)
+
+__all__ = [
+ # Base types
+ 'TranscriptionCapability',
+ 'TranscriptionRequest',
+ 'TranscriptionResponse',
+ 'TranscriptionSegment',
+ 'BaseTranscriptionConnector',
+ 'ConnectorSpecifications',
+ 'DEFAULT_SPECIFICATIONS',
+
+ # Exceptions
+ 'TranscriptionError',
+ 'ConfigurationError',
+ 'ProviderError',
+ 'AudioFormatError',
+ 'ChunkingError',
+
+ # Registry
+ 'ConnectorRegistry',
+ 'get_registry',
+ 'connector_registry',
+
+ # Convenience functions
+ 'transcribe',
+ 'get_connector',
+ 'supports_diarization',
+
+ # Connectors
+ 'OpenAIWhisperConnector',
+ 'OpenAITranscribeConnector',
+ 'ASREndpointConnector',
+]
diff --git a/src/services/transcription/base.py b/src/services/transcription/base.py
new file mode 100644
index 00000000..a515c293
--- /dev/null
+++ b/src/services/transcription/base.py
@@ -0,0 +1,241 @@
+"""
+Base classes and data types for transcription connectors.
+"""
+
+import json
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from enum import Enum, auto
+from typing import Optional, List, Dict, Any, BinaryIO, Set, Type, FrozenSet
+
+
+class TranscriptionCapability(Enum):
+ """Capabilities that connectors can declare support for."""
+ DIARIZATION = auto() # Speaker diarization
+ CHUNKING = auto() # Automatic file chunking for large files
+ TIMESTAMPS = auto() # Word/segment timestamps
+ LANGUAGE_DETECTION = auto() # Auto language detection
+ KNOWN_SPEAKERS = auto() # Support for known speaker references (future)
+ SPEAKER_EMBEDDINGS = auto() # Return speaker embeddings
+ SPEAKER_COUNT_CONTROL = auto() # Support for min/max speaker count parameters
+ STREAMING = auto() # Real-time streaming transcription
+
+
+@dataclass
+class ConnectorSpecifications:
+ """
+ Provider-specific constraints and requirements.
+
+ Each connector declares its constraints so the application can automatically
+ handle chunking, format conversion, and other preprocessing as needed.
+ """
+ # Size constraints
+ max_file_size_bytes: Optional[int] = None # None = unlimited
+
+ # Duration constraints
+ max_duration_seconds: Optional[int] = None # None = unlimited
+ min_duration_for_chunking: Optional[int] = None # Provider's internal chunking threshold
+
+ # Chunking behavior
+ handles_chunking_internally: bool = False # Provider handles large files
+ requires_chunking_param: bool = False # Must send chunking_strategy param
+ recommended_chunk_seconds: int = 600 # 10 minutes default
+
+ # Audio format support - connector-specific codec restrictions
+ # None = use system defaults from get_supported_codecs()
+ # Set = only allow these codecs (overrides defaults)
+ supported_codecs: Optional[FrozenSet[str]] = None
+ # Codecs this connector doesn't support (removed from defaults)
+ # Merged with AUDIO_UNSUPPORTED_CODECS env var
+ unsupported_codecs: Optional[FrozenSet[str]] = None
+
+
+# Default specifications for connectors that don't define their own
+DEFAULT_SPECIFICATIONS = ConnectorSpecifications()
+
+
+@dataclass
+class TranscriptionRequest:
+ """Standardized transcription request."""
+ audio_file: BinaryIO
+ filename: str
+ mime_type: Optional[str] = None
+ language: Optional[str] = None
+
+ # Diarization options
+ diarize: bool = False
+ min_speakers: Optional[int] = None
+ max_speakers: Optional[int] = None
+ known_speaker_names: Optional[List[str]] = None
+ known_speaker_references: Optional[Dict[str, BinaryIO]] = None
+
+ # Advanced options
+ prompt: Optional[str] = None
+ temperature: Optional[float] = None
+
+ # Provider-specific options (passthrough)
+ extra_options: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class TranscriptionSegment:
+ """Single segment of transcription with optional metadata."""
+ text: str
+ speaker: Optional[str] = None
+ start_time: Optional[float] = None
+ end_time: Optional[float] = None
+ confidence: Optional[float] = None
+ words: Optional[List[Dict[str, Any]]] = None
+
+
+@dataclass
+class TranscriptionResponse:
+ """Standardized transcription response."""
+ # Core content
+ text: str # Plain text transcription
+ segments: Optional[List[TranscriptionSegment]] = None # Detailed segments
+
+ # Metadata
+ language: Optional[str] = None # Detected language
+ duration: Optional[float] = None # Audio duration in seconds
+
+ # Speaker information
+ speakers: Optional[List[str]] = None # List of speakers found
+ speaker_embeddings: Optional[Dict[str, List[float]]] = None
+
+ # Provider info
+ provider: str = ""
+ model: str = ""
+
+ # Raw response for debugging
+ raw_response: Optional[Dict[str, Any]] = None
+
+ def to_storage_format(self) -> str:
+ """
+ Convert to the JSON format used for storage in database.
+
+ Returns a JSON string in the format expected by the existing codebase:
+ [
+ {
+ "speaker": "SPEAKER_00",
+ "sentence": "Text here",
+ "start_time": 0.0,
+ "end_time": 5.5
+ },
+ ...
+ ]
+ """
+ if self.segments:
+ return json.dumps([
+ {
+ 'speaker': seg.speaker or 'Unknown Speaker',
+ 'sentence': seg.text,
+ 'start_time': seg.start_time,
+ 'end_time': seg.end_time
+ }
+ for seg in self.segments
+ ])
+ # If no segments, return plain text (for non-diarized transcriptions)
+ return self.text
+
+ def has_diarization(self) -> bool:
+ """Check if this response contains diarization data."""
+ if not self.segments:
+ return False
+ return any(seg.speaker for seg in self.segments)
+
+
+class BaseTranscriptionConnector(ABC):
+ """Abstract base class for transcription connectors."""
+
+ # Class-level capability declarations - subclasses should override
+ CAPABILITIES: Set[TranscriptionCapability] = set()
+ PROVIDER_NAME: str = "unknown"
+
+ # Provider-specific constraints - subclasses should override
+ SPECIFICATIONS: ConnectorSpecifications = DEFAULT_SPECIFICATIONS
+
+ def __init__(self, config: Dict[str, Any]):
+ """
+ Initialize connector with configuration.
+
+ Args:
+ config: Provider-specific configuration dict
+ """
+ self.config = config
+ self._validate_config()
+
+ @abstractmethod
+ def _validate_config(self) -> None:
+ """
+ Validate required configuration is present.
+
+ Raises:
+ ConfigurationError: If required config is missing or invalid
+ """
+ pass
+
+ @abstractmethod
+ def transcribe(self, request: TranscriptionRequest) -> TranscriptionResponse:
+ """
+ Perform transcription.
+
+ Args:
+ request: Standardized transcription request
+
+ Returns:
+ Standardized transcription response
+
+ Raises:
+ TranscriptionError: On transcription failure
+ ConfigurationError: On configuration issues
+ """
+ pass
+
+ def supports(self, capability: TranscriptionCapability) -> bool:
+ """Check if connector supports a capability."""
+ return capability in self.CAPABILITIES
+
+ def get_capabilities(self) -> Set[TranscriptionCapability]:
+ """Get all supported capabilities."""
+ return self.CAPABILITIES.copy()
+
+ @property
+ def supports_diarization(self) -> bool:
+ """Check if connector supports speaker diarization."""
+ return TranscriptionCapability.DIARIZATION in self.CAPABILITIES
+
+ @property
+ def supports_chunking(self) -> bool:
+ """Check if connector supports automatic file chunking."""
+ return TranscriptionCapability.CHUNKING in self.CAPABILITIES
+
+ @property
+ def supports_speaker_count_control(self) -> bool:
+ """Check if connector supports min/max speaker count parameters."""
+ return TranscriptionCapability.SPEAKER_COUNT_CONTROL in self.CAPABILITIES
+
+ @property
+ def specifications(self) -> ConnectorSpecifications:
+ """Get connector specifications."""
+ return self.SPECIFICATIONS
+
+ @classmethod
+ def get_config_schema(cls) -> Dict[str, Any]:
+ """
+ Return JSON schema for this connector's configuration.
+ Useful for admin UI and validation.
+
+ Returns:
+ JSON schema dict describing required and optional config
+ """
+ return {}
+
+ def health_check(self) -> bool:
+ """
+ Check if the connector is properly configured and reachable.
+
+ Returns:
+ True if the connector is healthy, False otherwise
+ """
+ return True
diff --git a/src/services/transcription/connectors/__init__.py b/src/services/transcription/connectors/__init__.py
new file mode 100644
index 00000000..fff8bb45
--- /dev/null
+++ b/src/services/transcription/connectors/__init__.py
@@ -0,0 +1,13 @@
+"""
+Transcription connector implementations.
+"""
+
+from .openai_whisper import OpenAIWhisperConnector
+from .openai_transcribe import OpenAITranscribeConnector
+from .asr_endpoint import ASREndpointConnector
+
+__all__ = [
+ 'OpenAIWhisperConnector',
+ 'OpenAITranscribeConnector',
+ 'ASREndpointConnector',
+]
diff --git a/src/services/transcription/connectors/asr_endpoint.py b/src/services/transcription/connectors/asr_endpoint.py
new file mode 100644
index 00000000..d5736bd9
--- /dev/null
+++ b/src/services/transcription/connectors/asr_endpoint.py
@@ -0,0 +1,283 @@
+"""
+ASR Endpoint connector for custom self-hosted ASR services.
+
+Supports whisper-asr-webservice, WhisperX, and other compatible ASR services
+that expose a /asr endpoint.
+"""
+
+import json
+import logging
+import httpx
+from typing import Dict, Any, Set, Optional
+
+from ..base import (
+ BaseTranscriptionConnector,
+ TranscriptionCapability,
+ TranscriptionRequest,
+ TranscriptionResponse,
+ TranscriptionSegment,
+ ConnectorSpecifications,
+)
+from ..exceptions import TranscriptionError, ConfigurationError, ProviderError
+
+logger = logging.getLogger(__name__)
+
+
+class ASREndpointConnector(BaseTranscriptionConnector):
+ """Connector for custom ASR webservice (whisper-asr-webservice, WhisperX, etc.)."""
+
+ CAPABILITIES: Set[TranscriptionCapability] = {
+ TranscriptionCapability.DIARIZATION,
+ TranscriptionCapability.TIMESTAMPS,
+ TranscriptionCapability.LANGUAGE_DETECTION,
+ TranscriptionCapability.SPEAKER_COUNT_CONTROL, # Supports min/max speakers
+ }
+ PROVIDER_NAME = "asr_endpoint"
+
+ # Self-hosted ASR endpoints typically handle files of any size internally
+ SPECIFICATIONS = ConnectorSpecifications(
+ max_file_size_bytes=None, # Unlimited
+ max_duration_seconds=None, # Unlimited
+ handles_chunking_internally=True, # ASR service handles it
+ )
+
+ def __init__(self, config: Dict[str, Any]):
+ """
+ Initialize the ASR Endpoint connector.
+
+ Args:
+ config: Configuration dict with keys:
+ - base_url: ASR service base URL (required)
+ - timeout: Request timeout in seconds (default: 1800)
+ - return_speaker_embeddings: Whether to request embeddings (default: False)
+ - diarize: Whether to enable diarization by default (default: True)
+ """
+ super().__init__(config)
+
+ self.base_url = config['base_url'].rstrip('/')
+ self.timeout = config.get('timeout', 1800) # 30 minutes default
+ self.return_embeddings = config.get('return_speaker_embeddings', False)
+ self.default_diarize = config.get('diarize', True)
+
+ # Add speaker embeddings capability if enabled
+ if self.return_embeddings:
+ self.CAPABILITIES = self.CAPABILITIES | {TranscriptionCapability.SPEAKER_EMBEDDINGS}
+
+ def _validate_config(self) -> None:
+ """Validate required configuration."""
+ if not self.config.get('base_url'):
+ raise ConfigurationError("base_url is required for ASR endpoint connector")
+
+ def transcribe(self, request: TranscriptionRequest) -> TranscriptionResponse:
+ """
+ Transcribe audio using ASR webservice.
+
+ Args:
+ request: Standardized transcription request
+
+ Returns:
+ TranscriptionResponse with segments and speaker information
+ """
+ try:
+ url = f"{self.base_url}/asr"
+
+ params = {
+ 'encode': True,
+ 'task': 'transcribe',
+ 'output': 'json'
+ }
+
+ if request.language:
+ params['language'] = request.language
+ logger.info(f"Using transcription language: {request.language}")
+
+ # Determine if we should diarize
+ should_diarize = request.diarize if request.diarize is not None else self.default_diarize
+
+ if should_diarize:
+ # Send both parameter names for compatibility:
+ # - 'diarize' is used by whisper-asr-webservice
+ # - 'enable_diarization' is used by WhisperX
+ params['diarize'] = True
+ params['enable_diarization'] = True
+
+ if self.return_embeddings:
+ params['return_speaker_embeddings'] = True
+
+ if request.min_speakers:
+ params['min_speakers'] = request.min_speakers
+ if request.max_speakers:
+ params['max_speakers'] = request.max_speakers
+
+ content_type = request.mime_type or 'application/octet-stream'
+ files = {
+ 'audio_file': (request.filename, request.audio_file, content_type)
+ }
+
+ # Configure timeout: generous values for large file uploads
+ timeout = httpx.Timeout(
+ None,
+ connect=60.0,
+ read=float(self.timeout),
+ write=300.0,
+ pool=None
+ )
+
+ logger.info(f"Sending ASR request to {url} with params: {params} (timeout: {self.timeout}s)")
+
+ with httpx.Client() as client:
+ response = client.post(url, params=params, files=files, timeout=timeout)
+ logger.info(f"ASR request completed with status: {response.status_code}")
+ response.raise_for_status()
+
+ # Parse the JSON response
+ response_text = response.text
+ try:
+ data = response.json()
+ except Exception as json_err:
+ if response_text.strip().startswith('<'):
+ logger.error(f"ASR returned HTML error page (status {response.status_code})")
+ raise ProviderError(
+ f"ASR service returned HTML error page",
+ provider=self.PROVIDER_NAME,
+ status_code=response.status_code
+ )
+ else:
+ raise ProviderError(
+ f"ASR service returned invalid response: {json_err}",
+ provider=self.PROVIDER_NAME,
+ status_code=response.status_code
+ )
+
+ return self._parse_response(data)
+
+ except httpx.HTTPStatusError as e:
+ logger.error(f"ASR request failed with status {e.response.status_code}")
+ raise ProviderError(
+ f"ASR request failed with status {e.response.status_code}",
+ provider=self.PROVIDER_NAME,
+ status_code=e.response.status_code
+ ) from e
+
+ except httpx.TimeoutException as e:
+ logger.error(f"ASR request timed out after {self.timeout}s")
+ raise TranscriptionError(f"ASR request timed out after {self.timeout}s") from e
+
+ except Exception as e:
+ error_msg = str(e)
+ logger.error(f"ASR transcription failed: {error_msg}")
+ raise TranscriptionError(f"ASR transcription failed: {error_msg}") from e
+
+ def _parse_response(self, data: Dict[str, Any]) -> TranscriptionResponse:
+ """
+ Parse ASR webservice response into standardized format.
+
+ The ASR response contains:
+ - text: Full transcription text
+ - language: Detected language
+ - segments: Array of segments with speaker, text, start, end
+ - speaker_embeddings: Optional speaker embeddings (WhisperX only)
+ """
+ segments = []
+ speakers = set()
+ full_text_parts = []
+ last_speaker = None
+
+ logger.info(f"ASR response keys: {list(data.keys())}")
+
+ if 'segments' in data and isinstance(data['segments'], list):
+ logger.info(f"Number of segments: {len(data['segments'])}")
+
+ for seg in data['segments']:
+ speaker = seg.get('speaker')
+
+ # Handle missing speakers by carrying forward from previous segment
+ if speaker is None:
+ if last_speaker is not None:
+ speaker = last_speaker
+ else:
+ speaker = 'UNKNOWN_SPEAKER'
+ else:
+ last_speaker = speaker
+
+ text = seg.get('text', '').strip()
+ speakers.add(speaker)
+ full_text_parts.append(f"[{speaker}]: {text}")
+
+ segments.append(TranscriptionSegment(
+ text=text,
+ speaker=speaker,
+ start_time=seg.get('start'),
+ end_time=seg.get('end')
+ ))
+
+ # Get the full text
+ if 'text' in data:
+ full_text = data['text']
+ elif full_text_parts:
+ full_text = '\n'.join(full_text_parts)
+ else:
+ full_text = ''
+
+ # Extract speaker embeddings if present
+ speaker_embeddings = data.get('speaker_embeddings')
+ if speaker_embeddings:
+ logger.info(f"Received speaker embeddings for speakers: {list(speaker_embeddings.keys())}")
+
+ logger.info(f"Parsed {len(segments)} segments with {len(speakers)} unique speakers: {sorted(speakers)}")
+
+ return TranscriptionResponse(
+ text=full_text,
+ segments=segments,
+ speakers=sorted(list(speakers)),
+ speaker_embeddings=speaker_embeddings,
+ language=data.get('language'),
+ provider=self.PROVIDER_NAME,
+ model="asr-endpoint",
+ raw_response=data
+ )
+
+ def health_check(self) -> bool:
+ """Check if ASR endpoint is reachable."""
+ try:
+ with httpx.Client(timeout=10.0) as client:
+ # Try common health check endpoints
+ for endpoint in ['/health', '/']:
+ try:
+ response = client.get(f"{self.base_url}{endpoint}")
+ if response.status_code < 500:
+ return True
+ except Exception:
+ continue
+ return False
+ except Exception:
+ return False
+
+ @classmethod
+ def get_config_schema(cls) -> Dict[str, Any]:
+ """Return JSON schema for configuration."""
+ return {
+ "type": "object",
+ "required": ["base_url"],
+ "properties": {
+ "base_url": {
+ "type": "string",
+ "description": "ASR service base URL (e.g., http://whisper-asr:9000)"
+ },
+ "timeout": {
+ "type": "integer",
+ "default": 1800,
+ "description": "Request timeout in seconds"
+ },
+ "diarize": {
+ "type": "boolean",
+ "default": True,
+ "description": "Enable speaker diarization by default"
+ },
+ "return_speaker_embeddings": {
+ "type": "boolean",
+ "default": False,
+ "description": "Request speaker embeddings (WhisperX only)"
+ }
+ }
+ }
diff --git a/src/services/transcription/connectors/openai_transcribe.py b/src/services/transcription/connectors/openai_transcribe.py
new file mode 100644
index 00000000..9feb65d2
--- /dev/null
+++ b/src/services/transcription/connectors/openai_transcribe.py
@@ -0,0 +1,278 @@
+"""
+OpenAI GPT-4o Transcribe connector.
+
+Supports the newer GPT-4o based transcription models:
+- gpt-4o-transcribe: High quality transcription
+- gpt-4o-mini-transcribe: Cost-effective transcription
+- gpt-4o-transcribe-diarize: Speaker diarization with labels A, B, C, D
+"""
+
+import logging
+import httpx
+from openai import OpenAI
+from typing import Dict, Any, Set, Optional
+
+from ..base import (
+ BaseTranscriptionConnector,
+ TranscriptionCapability,
+ TranscriptionRequest,
+ TranscriptionResponse,
+ TranscriptionSegment,
+ ConnectorSpecifications,
+)
+from ..exceptions import TranscriptionError, ConfigurationError
+
+logger = logging.getLogger(__name__)
+
+
+class OpenAITranscribeConnector(BaseTranscriptionConnector):
+ """Connector for GPT-4o Transcribe models with optional diarization support."""
+
+ # Base capabilities - diarization added dynamically based on model
+ CAPABILITIES: Set[TranscriptionCapability] = {
+ TranscriptionCapability.TIMESTAMPS,
+ TranscriptionCapability.LANGUAGE_DETECTION,
+ }
+ PROVIDER_NAME = "openai_transcribe"
+
+ # GPT-4o Transcribe models have specific constraints
+ # - 25MB file size limit
+ # - 1400 second max duration for diarize model
+ # - chunking_strategy="auto" handles files >30s internally
+ SPECIFICATIONS = ConnectorSpecifications(
+ max_file_size_bytes=25 * 1024 * 1024, # 25MB
+ max_duration_seconds=1400, # ~23.3 minutes max for diarize model
+ min_duration_for_chunking=30, # >30s needs chunking_strategy param
+ handles_chunking_internally=True, # Uses chunking_strategy="auto"
+ requires_chunking_param=True, # Must send chunking_strategy for >30s
+ )
+
+ # Models and their capabilities
+ MODELS = {
+ 'gpt-4o-transcribe': {
+ 'supports_diarization': False,
+ 'description': 'High quality transcription'
+ },
+ 'gpt-4o-mini-transcribe': {
+ 'supports_diarization': False,
+ 'description': 'Cost-effective transcription'
+ },
+ 'gpt-4o-mini-transcribe-2025-12-15': {
+ 'supports_diarization': False,
+ 'description': 'Cost-effective transcription (dated version)'
+ },
+ 'gpt-4o-transcribe-diarize': {
+ 'supports_diarization': True,
+ 'description': 'Speaker diarization with labels A, B, C, D'
+ }
+ }
+
+ def __init__(self, config: Dict[str, Any]):
+ """
+ Initialize the GPT-4o Transcribe connector.
+
+ Args:
+ config: Configuration dict with keys:
+ - api_key: OpenAI API key (required)
+ - base_url: API base URL (default: https://api.openai.com/v1)
+ - model: Model name (required, one of MODELS)
+ - http_client: Optional httpx.Client instance
+ """
+ # Store model before calling super().__init__ since _validate_config needs it
+ self.model = config.get('model', 'gpt-4o-transcribe')
+
+ super().__init__(config)
+
+ # Set up HTTP client with custom headers
+ http_client = config.get('http_client')
+ if not http_client:
+ app_headers = {
+ "HTTP-Referer": "https://github.com/murtaza-nasir/speakr",
+ "X-Title": "Speakr - AI Audio Transcription",
+ "User-Agent": "Speakr/1.0 (https://github.com/murtaza-nasir/speakr)"
+ }
+ http_client = httpx.Client(verify=True, headers=app_headers)
+
+ self.client = OpenAI(
+ api_key=config['api_key'],
+ base_url=config.get('base_url', 'https://api.openai.com/v1'),
+ http_client=http_client
+ )
+
+ # Dynamically update capabilities based on model
+ if self._model_supports_diarization():
+ self.CAPABILITIES = self.CAPABILITIES | {
+ TranscriptionCapability.DIARIZATION,
+ TranscriptionCapability.KNOWN_SPEAKERS
+ }
+
+ def _validate_config(self) -> None:
+ """Validate required configuration."""
+ if not self.config.get('api_key'):
+ raise ConfigurationError("api_key is required for OpenAI Transcribe connector")
+
+ model = self.config.get('model', 'gpt-4o-transcribe')
+ if model not in self.MODELS:
+ raise ConfigurationError(
+ f"Unknown model: {model}. Valid models: {list(self.MODELS.keys())}"
+ )
+
+ def _model_supports_diarization(self) -> bool:
+ """Check if the current model supports diarization."""
+ model_info = self.MODELS.get(self.model, {})
+ return model_info.get('supports_diarization', False)
+
+ def transcribe(self, request: TranscriptionRequest) -> TranscriptionResponse:
+ """
+ Transcribe audio using GPT-4o Transcribe API.
+
+ Args:
+ request: Standardized transcription request
+
+ Returns:
+ TranscriptionResponse, with segments if using diarization model
+ """
+ try:
+ params = {
+ "model": self.model,
+ "file": request.audio_file,
+ }
+
+ if request.language:
+ params["language"] = request.language
+ logger.info(f"Using transcription language: {request.language}")
+
+ # Handle diarization model specifics
+ if self.model == 'gpt-4o-transcribe-diarize':
+ # Required: chunking_strategy for audio > 30 seconds
+ params["chunking_strategy"] = "auto"
+
+ if request.diarize:
+ params["response_format"] = "diarized_json"
+ logger.info("Using diarized_json response format for speaker diarization")
+
+ # Optional: known speaker support (for future implementation)
+ # if request.known_speaker_names:
+ # params["known_speaker_names"] = request.known_speaker_names
+ else:
+ # Non-diarization models
+ if request.prompt:
+ params["prompt"] = request.prompt
+
+ logger.info(f"Sending request to GPT-4o Transcribe API with model: {self.model}")
+ response = self.client.audio.transcriptions.create(**params)
+
+ # Parse response based on format
+ if self.model == 'gpt-4o-transcribe-diarize' and request.diarize:
+ return self._parse_diarized_response(response)
+ else:
+ return self._parse_text_response(response)
+
+ except Exception as e:
+ error_msg = str(e)
+ logger.error(f"GPT-4o transcription failed: {error_msg}")
+ raise TranscriptionError(f"GPT-4o transcription failed: {error_msg}") from e
+
+ def _parse_text_response(self, response) -> TranscriptionResponse:
+ """Parse a plain text response."""
+ text = response.text if hasattr(response, 'text') else str(response)
+ return TranscriptionResponse(
+ text=text,
+ provider=self.PROVIDER_NAME,
+ model=self.model
+ )
+
+ def _parse_diarized_response(self, response) -> TranscriptionResponse:
+ """
+ Parse diarized JSON response into standardized format.
+
+ The diarized_json response contains segments with:
+ - speaker: "A", "B", "C", "D" etc.
+ - text: The transcribed text
+ - start: Segment start time
+ - end: Segment end time
+ """
+ segments = []
+ speakers = set()
+ full_text_parts = []
+
+ # Handle response object - could be dict or object with attributes
+ if hasattr(response, 'segments'):
+ raw_segments = response.segments
+ elif isinstance(response, dict) and 'segments' in response:
+ raw_segments = response['segments']
+ else:
+ # Fallback to text-only response
+ logger.warning("No segments found in diarized response, falling back to text")
+ return self._parse_text_response(response)
+
+ for seg in raw_segments:
+ # Handle both dict and object segments
+ if isinstance(seg, dict):
+ speaker = seg.get('speaker', 'Unknown')
+ text = seg.get('text', '')
+ start = seg.get('start')
+ end = seg.get('end')
+ else:
+ speaker = getattr(seg, 'speaker', 'Unknown')
+ text = getattr(seg, 'text', '')
+ start = getattr(seg, 'start', None)
+ end = getattr(seg, 'end', None)
+
+ speakers.add(speaker)
+ full_text_parts.append(f"[{speaker}]: {text}")
+
+ segments.append(TranscriptionSegment(
+ text=text,
+ speaker=speaker,
+ start_time=start,
+ end_time=end
+ ))
+
+ # Get the full text if available
+ if hasattr(response, 'text'):
+ full_text = response.text
+ elif isinstance(response, dict) and 'text' in response:
+ full_text = response['text']
+ else:
+ full_text = '\n'.join(full_text_parts)
+
+ logger.info(f"Parsed {len(segments)} segments with {len(speakers)} unique speakers: {sorted(speakers)}")
+
+ return TranscriptionResponse(
+ text=full_text,
+ segments=segments,
+ speakers=sorted(list(speakers)),
+ provider=self.PROVIDER_NAME,
+ model=self.model,
+ raw_response=response if isinstance(response, dict) else None
+ )
+
+ def health_check(self) -> bool:
+ """Check if the connector is properly configured."""
+ return bool(self.config.get('api_key'))
+
+ @classmethod
+ def get_config_schema(cls) -> Dict[str, Any]:
+ """Return JSON schema for configuration."""
+ return {
+ "type": "object",
+ "required": ["api_key"],
+ "properties": {
+ "api_key": {
+ "type": "string",
+ "description": "OpenAI API key"
+ },
+ "base_url": {
+ "type": "string",
+ "default": "https://api.openai.com/v1",
+ "description": "API base URL"
+ },
+ "model": {
+ "type": "string",
+ "enum": list(cls.MODELS.keys()),
+ "default": "gpt-4o-transcribe",
+ "description": "GPT-4o transcription model to use"
+ }
+ }
+ }
diff --git a/src/services/transcription/connectors/openai_whisper.py b/src/services/transcription/connectors/openai_whisper.py
new file mode 100644
index 00000000..870f1c9d
--- /dev/null
+++ b/src/services/transcription/connectors/openai_whisper.py
@@ -0,0 +1,143 @@
+"""
+OpenAI Whisper API connector (whisper-1 model).
+
+This is the legacy Whisper API connector that supports the whisper-1 model.
+It returns plain text transcriptions without speaker diarization.
+"""
+
+import logging
+import os
+import httpx
+from openai import OpenAI
+from typing import Dict, Any, Set
+
+from ..base import (
+ BaseTranscriptionConnector,
+ TranscriptionCapability,
+ TranscriptionRequest,
+ TranscriptionResponse,
+ ConnectorSpecifications,
+)
+from ..exceptions import TranscriptionError, ConfigurationError
+
+logger = logging.getLogger(__name__)
+
+
+class OpenAIWhisperConnector(BaseTranscriptionConnector):
+ """Connector for OpenAI Whisper API (whisper-1 model)."""
+
+ CAPABILITIES: Set[TranscriptionCapability] = {
+ TranscriptionCapability.CHUNKING,
+ TranscriptionCapability.TIMESTAMPS,
+ TranscriptionCapability.LANGUAGE_DETECTION,
+ }
+ PROVIDER_NAME = "openai_whisper"
+
+ # OpenAI Whisper has a 25MB file limit and doesn't handle chunking internally
+ SPECIFICATIONS = ConnectorSpecifications(
+ max_file_size_bytes=25 * 1024 * 1024, # 25MB
+ handles_chunking_internally=False,
+ recommended_chunk_seconds=600, # 10 minutes
+ )
+
+ def __init__(self, config: Dict[str, Any]):
+ """
+ Initialize the Whisper connector.
+
+ Args:
+ config: Configuration dict with keys:
+ - api_key: OpenAI API key (required)
+ - base_url: API base URL (optional)
+ - model: Model name (default: whisper-1)
+ - http_client: Optional httpx.Client instance
+ """
+ super().__init__(config)
+
+ # Set up HTTP client with custom headers
+ http_client = config.get('http_client')
+ if not http_client:
+ app_headers = {
+ "HTTP-Referer": "https://github.com/murtaza-nasir/speakr",
+ "X-Title": "Speakr - AI Audio Transcription",
+ "User-Agent": "Speakr/1.0 (https://github.com/murtaza-nasir/speakr)"
+ }
+ http_client = httpx.Client(verify=True, headers=app_headers)
+
+ self.client = OpenAI(
+ api_key=config['api_key'],
+ base_url=config.get('base_url') or None,
+ http_client=http_client
+ )
+ self.model = config.get('model', 'whisper-1')
+
+ def _validate_config(self) -> None:
+ """Validate required configuration."""
+ if not self.config.get('api_key'):
+ raise ConfigurationError("api_key is required for OpenAI Whisper connector")
+
+ def transcribe(self, request: TranscriptionRequest) -> TranscriptionResponse:
+ """
+ Transcribe audio using OpenAI Whisper API.
+
+ Args:
+ request: Standardized transcription request
+
+ Returns:
+ TranscriptionResponse with plain text (no diarization)
+ """
+ try:
+ params = {
+ "model": self.model,
+ "file": request.audio_file,
+ }
+
+ if request.language:
+ params["language"] = request.language
+ logger.info(f"Using transcription language: {request.language}")
+
+ if request.prompt:
+ params["prompt"] = request.prompt
+
+ if request.temperature is not None:
+ params["temperature"] = request.temperature
+
+ logger.info(f"Sending request to Whisper API with model: {self.model}")
+ transcript = self.client.audio.transcriptions.create(**params)
+
+ return TranscriptionResponse(
+ text=transcript.text,
+ provider=self.PROVIDER_NAME,
+ model=self.model
+ )
+
+ except Exception as e:
+ error_msg = str(e)
+ logger.error(f"Whisper transcription failed: {error_msg}")
+ raise TranscriptionError(f"Whisper transcription failed: {error_msg}") from e
+
+ def health_check(self) -> bool:
+ """Check if the connector is properly configured."""
+ return bool(self.config.get('api_key'))
+
+ @classmethod
+ def get_config_schema(cls) -> Dict[str, Any]:
+ """Return JSON schema for configuration."""
+ return {
+ "type": "object",
+ "required": ["api_key"],
+ "properties": {
+ "api_key": {
+ "type": "string",
+ "description": "OpenAI API key"
+ },
+ "base_url": {
+ "type": "string",
+ "description": "API base URL (optional, for OpenAI-compatible endpoints)"
+ },
+ "model": {
+ "type": "string",
+ "default": "whisper-1",
+ "description": "Whisper model to use"
+ }
+ }
+ }
diff --git a/src/services/transcription/exceptions.py b/src/services/transcription/exceptions.py
new file mode 100644
index 00000000..d9de52d6
--- /dev/null
+++ b/src/services/transcription/exceptions.py
@@ -0,0 +1,32 @@
+"""
+Custom exceptions for transcription services.
+"""
+
+
+class TranscriptionError(Exception):
+ """Base exception for transcription errors."""
+ pass
+
+
+class ConfigurationError(TranscriptionError):
+ """Configuration-related errors (missing or invalid config)."""
+ pass
+
+
+class ProviderError(TranscriptionError):
+ """Provider/API errors."""
+
+ def __init__(self, message: str, provider: str = None, status_code: int = None):
+ super().__init__(message)
+ self.provider = provider
+ self.status_code = status_code
+
+
+class AudioFormatError(TranscriptionError):
+ """Unsupported audio format errors."""
+ pass
+
+
+class ChunkingError(TranscriptionError):
+ """Errors during file chunking."""
+ pass
diff --git a/src/services/transcription/registry.py b/src/services/transcription/registry.py
new file mode 100644
index 00000000..50db5cb0
--- /dev/null
+++ b/src/services/transcription/registry.py
@@ -0,0 +1,293 @@
+"""
+Connector registry for managing transcription connectors.
+
+Provides factory pattern for creating and managing transcription connectors,
+with auto-detection from environment variables for backwards compatibility.
+"""
+
+import os
+import logging
+from typing import Dict, Any, Optional, Type, List
+
+from .base import BaseTranscriptionConnector, TranscriptionCapability, TranscriptionRequest, TranscriptionResponse
+from .exceptions import ConfigurationError
+
+logger = logging.getLogger(__name__)
+
+
+class ConnectorRegistry:
+ """
+ Registry for managing transcription connectors.
+
+ Singleton pattern - use get_registry() to get the shared instance.
+ """
+
+ _instance = None
+ _connectors: Dict[str, Type[BaseTranscriptionConnector]] = {}
+ _active_connector: Optional[BaseTranscriptionConnector] = None
+ _connector_name: str = ""
+ _initialized: bool = False
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
+ def __init__(self):
+ if self._initialized:
+ return
+ self._register_builtin_connectors()
+ self._initialized = True
+
+ def _register_builtin_connectors(self):
+ """Register all built-in connectors."""
+ from .connectors.openai_whisper import OpenAIWhisperConnector
+ from .connectors.openai_transcribe import OpenAITranscribeConnector
+ from .connectors.asr_endpoint import ASREndpointConnector
+
+ self.register('openai_whisper', OpenAIWhisperConnector)
+ self.register('openai_transcribe', OpenAITranscribeConnector)
+ self.register('asr_endpoint', ASREndpointConnector)
+
+ def register(self, name: str, connector_class: Type[BaseTranscriptionConnector]):
+ """
+ Register a connector class.
+
+ Args:
+ name: Unique name for the connector
+ connector_class: The connector class to register
+ """
+ self._connectors[name] = connector_class
+ logger.debug(f"Registered transcription connector: {name}")
+
+ def get_connector_class(self, name: str) -> Type[BaseTranscriptionConnector]:
+ """
+ Get a connector class by name.
+
+ Args:
+ name: The connector name
+
+ Returns:
+ The connector class
+
+ Raises:
+ ConfigurationError: If connector not found
+ """
+ if name not in self._connectors:
+ raise ConfigurationError(
+ f"Unknown connector: {name}. Available: {list(self._connectors.keys())}"
+ )
+ return self._connectors[name]
+
+ def create_connector(self, name: str, config: Dict[str, Any]) -> BaseTranscriptionConnector:
+ """
+ Create a connector instance.
+
+ Args:
+ name: The connector name
+ config: Configuration dict for the connector
+
+ Returns:
+ Configured connector instance
+ """
+ connector_class = self.get_connector_class(name)
+ return connector_class(config)
+
+ def list_connectors(self) -> List[Dict[str, Any]]:
+ """
+ List all registered connectors with their capabilities.
+
+ Returns:
+ List of connector info dicts
+ """
+ result = []
+ for name, cls in self._connectors.items():
+ result.append({
+ 'name': name,
+ 'provider_name': cls.PROVIDER_NAME,
+ 'capabilities': [c.name for c in cls.CAPABILITIES],
+ 'config_schema': cls.get_config_schema()
+ })
+ return result
+
+ def initialize_from_env(self) -> BaseTranscriptionConnector:
+ """
+ Initialize the active connector from environment variables.
+
+ Auto-detection priority:
+ 1. TRANSCRIPTION_CONNECTOR - explicit connector name
+ 2. ASR_BASE_URL is set - use ASR endpoint (smarter detection)
+ - USE_ASR_ENDPOINT=true also works (backwards compat, with deprecation warning)
+ 3. TRANSCRIPTION_MODEL contains 'gpt-4o' - use OpenAI Transcribe
+ 4. TRANSCRIPTION_MODEL is set - use OpenAI Whisper with that model
+ 5. Default to OpenAI Whisper (whisper-1)
+
+ Returns:
+ The initialized connector
+ """
+ connector_name = os.environ.get('TRANSCRIPTION_CONNECTOR', '').lower().strip()
+
+ if not connector_name:
+ # Auto-detect based on existing config for backwards compatibility
+ asr_base_url = os.environ.get('ASR_BASE_URL', '').strip()
+ use_asr_flag = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ 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'
+ logger.warning(
+ "USE_ASR_ENDPOINT=true is deprecated. "
+ "Set ASR_BASE_URL instead for auto-detection, or use TRANSCRIPTION_CONNECTOR=asr_endpoint"
+ )
+ # Priority 3: Model-based detection
+ elif transcription_model and 'gpt-4o' in transcription_model:
+ connector_name = 'openai_transcribe'
+ logger.info(f"Auto-detected OpenAI Transcribe from TRANSCRIPTION_MODEL={transcription_model}")
+ # Priority 4 & 5: OpenAI Whisper (with custom or default model)
+ else:
+ connector_name = 'openai_whisper'
+ model = transcription_model or whisper_model or 'whisper-1'
+ logger.info(f"Using OpenAI Whisper connector with model: {model}")
+
+ config = self._build_config_from_env(connector_name)
+
+ try:
+ self._active_connector = self.create_connector(connector_name, config)
+ self._connector_name = connector_name
+
+ logger.info(f"Initialized transcription connector: {connector_name}")
+ logger.info(f"Capabilities: {[c.name for c in self._active_connector.get_capabilities()]}")
+
+ return self._active_connector
+
+ except Exception as e:
+ logger.error(f"Failed to initialize connector '{connector_name}': {e}")
+ raise ConfigurationError(f"Failed to initialize connector '{connector_name}': {e}") from e
+
+ def _build_config_from_env(self, connector_name: str) -> Dict[str, Any]:
+ """
+ Build connector config from environment variables.
+
+ Args:
+ connector_name: The connector to build config for
+
+ Returns:
+ Configuration dict
+ """
+ if connector_name == 'asr_endpoint':
+ base_url = os.environ.get('ASR_BASE_URL', '')
+ if base_url:
+ base_url = base_url.split('#')[0].strip()
+
+ return {
+ 'base_url': base_url,
+ 'timeout': int(os.environ.get('ASR_TIMEOUT', os.environ.get('asr_timeout_seconds', '1800'))),
+ 'diarize': os.environ.get('ASR_DIARIZE', 'true').lower() == 'true',
+ 'return_speaker_embeddings': os.environ.get('ASR_RETURN_SPEAKER_EMBEDDINGS', 'false').lower() == 'true'
+ }
+
+ elif connector_name == 'openai_transcribe':
+ base_url = os.environ.get('TRANSCRIPTION_BASE_URL', 'https://api.openai.com/v1')
+ if base_url:
+ base_url = base_url.split('#')[0].strip()
+
+ return {
+ 'api_key': os.environ.get('TRANSCRIPTION_API_KEY', ''),
+ 'base_url': base_url,
+ 'model': os.environ.get('TRANSCRIPTION_MODEL', 'gpt-4o-transcribe')
+ }
+
+ else: # openai_whisper (default)
+ base_url = os.environ.get('TRANSCRIPTION_BASE_URL', '')
+ if base_url:
+ base_url = base_url.split('#')[0].strip()
+
+ # Support both TRANSCRIPTION_MODEL and legacy WHISPER_MODEL
+ # TRANSCRIPTION_MODEL takes priority for custom Whisper variants
+ model = os.environ.get('TRANSCRIPTION_MODEL', '') or os.environ.get('WHISPER_MODEL', 'whisper-1')
+
+ return {
+ 'api_key': os.environ.get('TRANSCRIPTION_API_KEY', ''),
+ 'base_url': base_url or None,
+ 'model': model
+ }
+
+ def get_active_connector(self) -> BaseTranscriptionConnector:
+ """
+ Get the currently active connector.
+
+ Initializes from environment if not already initialized.
+
+ Returns:
+ The active connector
+ """
+ if not self._active_connector:
+ self.initialize_from_env()
+ return self._active_connector
+
+ def get_active_connector_name(self) -> str:
+ """Get the name of the currently active connector."""
+ if not self._active_connector:
+ self.initialize_from_env()
+ return self._connector_name
+
+ def reinitialize(self) -> BaseTranscriptionConnector:
+ """
+ Force re-initialization of the connector.
+
+ Useful when environment variables have changed.
+
+ Returns:
+ The newly initialized connector
+ """
+ self._active_connector = None
+ self._connector_name = ""
+ return self.initialize_from_env()
+
+
+# Global registry instance
+_registry: Optional[ConnectorRegistry] = None
+
+
+def get_registry() -> ConnectorRegistry:
+ """Get the global connector registry."""
+ global _registry
+ if _registry is None:
+ _registry = ConnectorRegistry()
+ return _registry
+
+
+# Convenience aliases
+connector_registry = get_registry()
+
+
+def transcribe(request: TranscriptionRequest) -> TranscriptionResponse:
+ """
+ Transcribe audio using the active connector.
+
+ This is a convenience function that uses the global registry.
+
+ Args:
+ request: The transcription request
+
+ Returns:
+ Transcription response
+ """
+ connector = get_registry().get_active_connector()
+ return connector.transcribe(request)
+
+
+def get_connector() -> BaseTranscriptionConnector:
+ """Get the active transcription connector."""
+ return get_registry().get_active_connector()
+
+
+def supports_diarization() -> bool:
+ """Check if the active connector supports diarization."""
+ return get_registry().get_active_connector().supports_diarization
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 83ba1803..8871e360 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -29,7 +29,11 @@ from src.utils.ffprobe import get_codec_info, is_video_file, is_lossless_audio,
from src.utils.ffmpeg_utils import convert_to_mp3, extract_audio_from_video as ffmpeg_extract_audio, compress_audio, FFmpegError, FFmpegNotFoundError
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 ASR_DIARIZE, ASR_BASE_URL, ASR_RETURN_SPEAKER_EMBEDDINGS, transcription_api_key, transcription_base_url, chunking_service, ENABLE_CHUNKING
+from src.config.app_config import (
+ ASR_DIARIZE, ASR_BASE_URL, ASR_RETURN_SPEAKER_EMBEDDINGS,
+ transcription_api_key, transcription_base_url, chunking_service, ENABLE_CHUNKING,
+ USE_NEW_TRANSCRIPTION_ARCHITECTURE
+)
from src.file_exporter import export_recording, ENABLE_AUTO_EXPORT
# Configuration for internal sharing
@@ -176,8 +180,8 @@ def clean_llm_response(text):
# Configuration from environment
USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
-ASR_ENDPOINT = os.environ.get('ASR_ENDPOINT', '')
-ASR_API_KEY = os.environ.get('ASR_API_KEY', '')
+# Note: ASR_ENDPOINT and ASR_API_KEY were removed - they were dead code
+# ASR configuration is now handled via the connector architecture
ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
# chunking_service, ENABLE_CHUNKING, transcription_api_key, and transcription_base_url
@@ -992,6 +996,179 @@ def compress_lossless_audio(filepath, codec='mp3', bitrate='128k', codec_info=No
raise
+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.
+
+ This function uses the transcription connector system which supports:
+ - OpenAI Whisper (whisper-1)
+ - OpenAI GPT-4o Transcribe (gpt-4o-transcribe, gpt-4o-mini-transcribe)
+ - OpenAI GPT-4o Transcribe Diarize (gpt-4o-transcribe-diarize) - with speaker labels
+ - Custom ASR endpoints (whisper-asr-webservice, WhisperX, etc.)
+
+ Args:
+ app_context: Flask app context
+ recording_id: ID of the recording to process
+ filepath: Path to the audio file
+ original_filename: Original filename for logging
+ start_time: Processing start time
+ mime_type: MIME type of the audio file
+ language: Optional language code override
+ diarize: Whether to enable diarization (None = use connector default)
+ min_speakers: Optional minimum speakers
+ max_speakers: Optional maximum speakers
+ tag_id: Optional tag ID to apply custom prompt from
+ """
+ from src.services.transcription import (
+ get_connector, TranscriptionRequest, TranscriptionCapability
+ )
+
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ current_app.logger.error(f"Error: Recording {recording_id} not found for transcription.")
+ return
+
+ try:
+ current_app.logger.info(f"Starting connector-based transcription for recording {recording_id}...")
+ recording.status = 'PROCESSING'
+ transcription_start_time = time.time()
+ db.session.commit()
+
+ # Get the active transcription connector
+ connector = get_connector()
+ connector_name = connector.PROVIDER_NAME
+ current_app.logger.info(f"Using transcription connector: {connector_name}")
+
+ # Handle video extraction (keep existing logic)
+ actual_filepath = filepath
+ actual_content_type = mime_type or mimetypes.guess_type(original_filename)[0] or 'application/octet-stream'
+ actual_filename = original_filename
+
+ # Use codec detection to check if file is a video
+ try:
+ is_video = is_video_file(filepath, timeout=10)
+ if is_video:
+ current_app.logger.info(f"Video detected for {original_filename}")
+ except FFProbeError as e:
+ current_app.logger.warning(f"Failed to probe {original_filename}: {e}. Falling back to MIME type detection.")
+ video_mime_types = [
+ 'video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/webm',
+ 'video/avi', 'video/x-ms-wmv', 'video/3gpp'
+ ]
+ is_video = (
+ actual_content_type.startswith('video/') or
+ actual_content_type in video_mime_types
+ )
+
+ if is_video:
+ current_app.logger.info(f"Video container detected, extracting audio...")
+ try:
+ audio_filepath, audio_mime_type = extract_audio_from_video(filepath)
+ actual_filepath = audio_filepath
+ actual_content_type = audio_mime_type
+ actual_filename = os.path.basename(audio_filepath)
+
+ recording.audio_path = audio_filepath
+ recording.mime_type = audio_mime_type
+ db.session.commit()
+ current_app.logger.info(f"Audio extracted: {audio_filepath}")
+ except Exception as e:
+ current_app.logger.error(f"Failed to extract audio from video: {str(e)}")
+ recording.status = 'FAILED'
+ recording.error_msg = f"Audio extraction failed: {str(e)}"
+ db.session.commit()
+ return
+
+ # Determine if we should diarize
+ if diarize is None:
+ # Use connector's default diarization setting
+ should_diarize = connector.supports_diarization
+ else:
+ should_diarize = diarize and connector.supports_diarization
+
+ if should_diarize and not connector.supports_diarization:
+ 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
+ )
+
+ 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 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()
+ recording.transcription_duration_seconds = int(transcription_end_time - transcription_start_time)
+ db.session.commit()
+ current_app.logger.info(f"Transcription completed in {recording.transcription_duration_seconds}s")
+
+ # Check if auto-summarization is disabled
+ disable_auto_summarization = SystemSetting.get_setting('disable_auto_summarization', False)
+ will_auto_summarize = not disable_auto_summarization
+
+ # Generate title immediately
+ generate_title_task(app_context, recording_id, will_auto_summarize=will_auto_summarize)
+
+ if disable_auto_summarization:
+ current_app.logger.info(f"Auto-summarization disabled, skipping summary for recording {recording_id}")
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ db.session.commit()
+
+ # Apply auto-shares for group tags after processing completes
+ apply_team_tag_auto_shares(recording_id)
+
+ # Export transcription-only if auto-export is enabled
+ if ENABLE_AUTO_EXPORT:
+ export_recording(recording_id)
+ else:
+ # Auto-generate summary for all recordings
+ current_app.logger.info(f"Auto-generating summary for recording {recording_id}")
+ generate_summary_only_task(app_context, recording_id)
+
+ except Exception as e:
+ db.session.rollback()
+ error_msg = str(e)
+ error_type = type(e).__name__
+ current_app.logger.error(f"Connector transcription FAILED for recording {recording_id}: [{error_type}] {error_msg}", exc_info=True)
+
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ recording.status = 'FAILED'
+ recording.transcription = f"Transcription failed: {error_msg}"
+
+ end_time = datetime.utcnow()
+ recording.processing_time_seconds = (end_time - start_time).total_seconds()
+ db.session.commit()
+
+
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."""
with app_context:
@@ -1339,6 +1516,42 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,
max_speakers: Optional maximum speakers override (from upload form)
tag_id: Optional tag ID to apply custom prompt from
"""
+ # Use new connector-based architecture if enabled
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ # Determine diarization setting based on connector capabilities
+ # The connector will handle this, but we pass the user's preference
+ diarize_setting = None # Let connector decide based on its capabilities
+
+ # Use language from upload form if provided, otherwise use user's default
+ if language:
+ user_transcription_language = language
+ else:
+ user_transcription_language = recording.owner.transcription_language if recording and recording.owner else None
+
+ mime_type = recording.mime_type if recording else None
+
+ transcribe_with_connector(
+ app_context, recording_id, filepath, filename_for_asr, start_time,
+ mime_type=mime_type,
+ language=user_transcription_language,
+ diarize=diarize_setting,
+ min_speakers=min_speakers,
+ max_speakers=max_speakers,
+ tag_id=tag_id
+ )
+
+ # After transcription completes, calculate processing time
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if recording and recording.status in ['COMPLETED', 'FAILED']:
+ end_time = datetime.utcnow()
+ recording.processing_time_seconds = (end_time - start_time).total_seconds()
+ db.session.commit()
+ return
+
+ # Legacy path: use old implementation for backwards compatibility
if USE_ASR_ENDPOINT:
with app_context:
recording = db.session.get(Recording, recording_id)
@@ -1391,11 +1604,24 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,
db.session.commit()
# Check if chunking is needed for large files
- needs_chunking = (chunking_service and
- ENABLE_CHUNKING and
- chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT))
+ # Get connector specifications for smart chunking decisions
+ connector_specs = None
+ if USE_NEW_TRANSCRIPTION_ARCHITECTURE:
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.get_active_connector()
+ if connector:
+ connector_specs = connector.specifications
+ except Exception as e:
+ current_app.logger.warning(f"Could not get connector specs for chunking: {e}")
+
+ # Use connector-aware chunking (respects connector.handles_chunking_internally,
+ # user ENV settings, and connector defaults in that priority order)
+ should_chunk = (chunking_service and
+ chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT, connector_specs))
- if needs_chunking:
+ if should_chunk:
current_app.logger.info(f"File {filepath} is large ({os.path.getsize(filepath)/1024/1024:.1f}MB), using chunking for transcription")
transcription_text = transcribe_with_chunking(app_context, recording_id, filepath, filename_for_asr)
else:
diff --git a/src/utils/audio_conversion.py b/src/utils/audio_conversion.py
index c96efcfe..daf3bcb6 100644
--- a/src/utils/audio_conversion.py
+++ b/src/utils/audio_conversion.py
@@ -63,24 +63,35 @@ class ConversionResult:
return self.final_size / (1024 * 1024)
-def get_supported_codecs(needs_chunking: bool = False) -> Set[str]:
+def get_supported_codecs(needs_chunking: bool = False, connector_specs: Optional[Any] = None) -> Set[str]:
"""
Get the set of supported audio codecs.
Args:
needs_chunking: If True, return only codecs that work well with chunking
+ connector_specs: Optional ConnectorSpecifications with provider-specific codec restrictions
Returns:
- Set of supported codec names (minus any excluded via AUDIO_UNSUPPORTED_CODECS)
+ Set of supported codec names (minus any excluded via env var or connector specs)
"""
- if needs_chunking:
+ # If connector defines explicit supported codecs, use those
+ if connector_specs and connector_specs.supported_codecs:
+ base_codecs = set(connector_specs.supported_codecs)
+ elif needs_chunking:
# For chunking: only support codecs that work well with chunking
base_codecs = {'pcm_s16le', 'pcm_s24le', 'pcm_f32le', 'mp3', 'flac'}
else:
# For direct transcription: support more codecs including WebM/Opus
base_codecs = {'pcm_s16le', 'pcm_s24le', 'pcm_f32le', 'mp3', 'flac', 'opus', 'vorbis', 'aac'}
- # Remove any user-specified unsupported codecs
+ # Remove connector-specific unsupported codecs
+ if connector_specs and connector_specs.unsupported_codecs:
+ excluded = base_codecs & set(connector_specs.unsupported_codecs)
+ if excluded:
+ logger.info(f"Excluding codecs from supported list (via connector specs): {excluded}")
+ base_codecs = base_codecs - set(connector_specs.unsupported_codecs)
+
+ # Remove any global user-specified unsupported codecs (env var still applies)
if AUDIO_UNSUPPORTED_CODECS:
excluded = base_codecs & AUDIO_UNSUPPORTED_CODECS
if excluded:
@@ -96,7 +107,8 @@ def convert_if_needed(
codec_info: Optional[Dict[str, Any]] = None,
needs_chunking: bool = False,
is_asr_endpoint: bool = False,
- delete_original: bool = True
+ delete_original: bool = True,
+ connector_specs: Optional[Any] = None
) -> ConversionResult:
"""
Handle ALL audio conversion needs in one place.
@@ -116,6 +128,7 @@ def convert_if_needed(
needs_chunking: Whether chunking will be used (affects supported codecs)
is_asr_endpoint: Whether using ASR endpoint (affects AAC handling)
delete_original: Whether to delete original file after successful conversion
+ connector_specs: Optional ConnectorSpecifications with provider-specific codec restrictions
Returns:
ConversionResult with output path, mime type, and conversion stats
@@ -147,8 +160,8 @@ def convert_if_needed(
audio_codec = original_codec
has_video = codec_info.get('has_video', False) if codec_info else False
- # Get supported codecs based on processing mode
- supported_codecs = get_supported_codecs(needs_chunking)
+ # Get supported codecs based on processing mode and connector specs
+ supported_codecs = get_supported_codecs(needs_chunking, connector_specs)
# Handle video files - extract audio
if has_video:
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index 67d9a3cd..a9e3b4a5 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -385,6 +385,8 @@ document.addEventListener('DOMContentLoaded', async () => {
// --- App Configuration ---
const useAsrEndpoint = ref(false);
+ const connectorSupportsDiarization = ref(false); // Connector capability for diarization UI
+ const connectorSupportsSpeakerCount = ref(false); // Connector capability for min/max speakers
const currentUserName = ref('');
const canDeleteRecordings = ref(true);
const enableInternalSharing = ref(false);
@@ -542,7 +544,7 @@ document.addEventListener('DOMContentLoaded', async () => {
openAsrDropdownIndex,
// App Config
- useAsrEndpoint, currentUserName, canDeleteRecordings, enableInternalSharing, enableArchiveToggle, showUsernamesInUI,
+ useAsrEndpoint, connectorSupportsDiarization, connectorSupportsSpeakerCount, currentUserName, canDeleteRecordings, enableInternalSharing, enableArchiveToggle, showUsernamesInUI,
// Internal Sharing
showUnifiedShareModal, internalShareUserSearch, internalShareSearchResults,
@@ -1861,6 +1863,8 @@ document.addEventListener('DOMContentLoaded', async () => {
const appElement = document.getElementById('app');
if (appElement) {
useAsrEndpoint.value = appElement.dataset.useAsrEndpoint === 'True';
+ connectorSupportsDiarization.value = appElement.dataset.connectorSupportsDiarization === 'True';
+ connectorSupportsSpeakerCount.value = appElement.dataset.connectorSupportsSpeakerCount === 'True';
currentUserName.value = appElement.dataset.currentUserName || '';
}
diff --git a/static/js/modules/composables/recordings.js b/static/js/modules/composables/recordings.js
index c6c63a79..bb6a7543 100644
--- a/static/js/modules/composables/recordings.js
+++ b/static/js/modules/composables/recordings.js
@@ -11,7 +11,7 @@ export function useRecordings(state, utils, reprocessComposable) {
filterTags, filterSpeakers, filterDatePreset, filterDateRange, filterTextQuery,
filterStarred, filterInbox, sortBy,
availableTags, availableSpeakers, selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,
- useAsrEndpoint, globalError, uploadQueue, isProcessingActive, currentView,
+ useAsrEndpoint, connectorSupportsDiarization, globalError, uploadQueue, isProcessingActive, currentView,
isMobileScreen, isSidebarCollapsed, isRecording, audioBlobURL
} = state;
@@ -370,7 +370,7 @@ export function useRecordings(state, utils, reprocessComposable) {
).filter(Boolean);
const firstTag = selectedTags[0];
- if (firstTag && useAsrEndpoint.value) {
+ if (firstTag && connectorSupportsDiarization.value) {
if (firstTag.default_language) {
uploadLanguage.value = firstTag.default_language;
}
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index 069210b8..dbc09c8a 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -12,7 +12,7 @@ export function useUpload(state, utils) {
maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit,
recordings, selectedRecording, totalRecordings, globalError,
selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,
- useAsrEndpoint, asrLanguage, asrMinSpeakers, asrMaxSpeakers,
+ useAsrEndpoint, connectorSupportsDiarization, asrLanguage, asrMinSpeakers, asrMaxSpeakers,
dragover, availableTags, uploadTagSearchFilter
} = state;
@@ -223,8 +223,8 @@ export function useUpload(state, utils) {
formData.append(`tag_ids[${index}]`, tagId);
});
- // Add ASR advanced options if ASR endpoint is enabled
- if (useAsrEndpoint.value) {
+ // Add diarization options if connector supports it
+ if (connectorSupportsDiarization.value) {
const asrOpts = nextFileItem.asrOptions || {};
const language = asrOpts.language || uploadLanguage.value;
const minSpeakers = asrOpts.min_speakers || uploadMinSpeakers.value;
@@ -592,7 +592,7 @@ export function useUpload(state, utils) {
).filter(Boolean);
const firstTag = selectedTagsObjects[0];
- if (firstTag && useAsrEndpoint.value) {
+ if (firstTag && connectorSupportsDiarization.value) {
if (firstTag.default_language) {
uploadLanguage.value = firstTag.default_language;
}
diff --git a/static/js/modules/state/core.js b/static/js/modules/state/core.js
index f7f4468f..a7946b7c 100644
--- a/static/js/modules/state/core.js
+++ b/static/js/modules/state/core.js
@@ -39,6 +39,8 @@ export function createCoreState(ref, computed) {
// --- App Configuration ---
const useAsrEndpoint = ref(false);
+ const connectorSupportsDiarization = ref(false); // Connector capability for diarization UI
+ const connectorSupportsSpeakerCount = ref(false); // Connector capability for min/max speakers
const currentUserName = ref('');
const canDeleteRecordings = ref(true);
const enableInternalSharing = ref(false);
@@ -116,6 +118,8 @@ export function createCoreState(ref, computed) {
// App Configuration
useAsrEndpoint,
+ connectorSupportsDiarization,
+ connectorSupportsSpeakerCount,
currentUserName,
canDeleteRecordings,
enableInternalSharing,
diff --git a/templates/account.html b/templates/account.html
index 537d7cbe..c09727c2 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -1744,10 +1744,10 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
</div>
</div>
- {% if use_asr_endpoint %}
+ {% if connector_supports_diarization %}
<div class="border-t border-[var(--border-primary)] pt-4">
- <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3" data-i18n="editTagModal.asrDefaultSettings">ASR Default Settings</h4>
- <p class="text-xs text-[var(--text-light)] mb-3" data-i18n="editTagModal.asrSettingsDescription">These settings will be applied by default when using this tag with ASR transcription</p>
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3" data-i18n="editTagModal.asrDefaultSettings">Diarization Default Settings</h4>
+ <p class="text-xs text-[var(--text-light)] mb-3" data-i18n="editTagModal.asrSettingsDescription">These settings will be applied by default when using this tag with diarization-enabled transcription</p>
<div class="space-y-3">
<div>
diff --git a/templates/components/detail/desktop-header.html b/templates/components/detail/desktop-header.html
index 7685578c..10ce3d96 100644
--- a/templates/components/detail/desktop-header.html
+++ b/templates/components/detail/desktop-header.html
@@ -73,7 +73,7 @@
:title="t('buttons.resetStuckProcessing')">
<i class="fas fa-undo"></i>
</button>
- <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint"
+ <button @click="openSpeakerModal" v-if="processedTranscription.hasDialogue"
class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
:title="t('buttons.identifySpeakers')">
<i class="fas fa-user-tag"></i>
diff --git a/templates/components/detail/mobile-header.html b/templates/components/detail/mobile-header.html
index b5cdd477..73e04c17 100644
--- a/templates/components/detail/mobile-header.html
+++ b/templates/components/detail/mobile-header.html
@@ -99,7 +99,7 @@
<button @click="confirmReprocess('transcription', selectedRecording)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-redo-alt"></i></button>
<button @click="confirmReprocess('summary', selectedRecording)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-sync-alt"></i></button>
<button @click="confirmReset(selectedRecording)" v-if="['PENDING', 'PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500"><i class="fas fa-undo"></i></button>
- <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-user-tag"></i></button>
+ <button @click="openSpeakerModal" v-if="processedTranscription.hasDialogue" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-user-tag"></i></button>
<button v-if="!selectedRecording.is_shared || (selectedRecording.share_info && selectedRecording.share_info.can_reshare)" @click="openUnifiedShareModal(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-share-alt"></i></button>
<button v-if="canDeleteRecordings && selectedRecording.can_delete !== false" @click="confirmDelete(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors"><i class="fas fa-trash"></i></button>
</div>
diff --git a/templates/components/recording-view.html b/templates/components/recording-view.html
index 33b96b57..ac223c8d 100644
--- a/templates/components/recording-view.html
+++ b/templates/components/recording-view.html
@@ -189,15 +189,15 @@
<i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
Selected tags include custom summary prompts
</p>
- <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
+ <p v-if="selectedTags.length > 0 && connectorSupportsDiarization && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
class="text-xs text-[var(--text-muted)] mt-1">
<i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
First tag's ASR settings will be applied: ${selectedTags[0].name}
</p>
</div>
- <!-- Advanced Options for ASR (collapsible) -->
- <div v-if="useAsrEndpoint">
+ <!-- Advanced Options for diarization-enabled connectors (collapsible) -->
+ <div v-if="connectorSupportsDiarization">
<button @click="showAdvancedOptions = !showAdvancedOptions"
class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
<span class="flex items-center gap-2 text-[var(--text-secondary)]">
@@ -218,7 +218,8 @@
</select>
</div>
- <div class="grid grid-cols-2 gap-3">
+ <!-- Speaker Settings - only show for connectors that support min/max speakers -->
+ <div v-if="connectorSupportsSpeakerCount" class="grid grid-cols-2 gap-3">
<div>
<label for="recordingAsrMinSpeakers" class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
</label>
diff --git a/templates/components/upload-view.html b/templates/components/upload-view.html
index 0a524f63..b4f6a9a4 100644
--- a/templates/components/upload-view.html
+++ b/templates/components/upload-view.html
@@ -212,15 +212,15 @@
<i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
Selected tags include custom summary prompts
</p>
- <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
+ <p v-if="selectedTags.length > 0 && connectorSupportsDiarization && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
class="text-xs text-[var(--text-muted)] mt-1">
<i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
First tag's ASR settings will be applied: ${selectedTags[0].name}
</p>
</div>
- <!-- Advanced Options for ASR (collapsible) -->
- <div v-if="useAsrEndpoint" class="mt-4">
+ <!-- Advanced Options for diarization-enabled connectors (collapsible) -->
+ <div v-if="connectorSupportsDiarization" class="mt-4">
<button @click="showAdvancedOptions = !showAdvancedOptions"
class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
<span class="flex items-center gap-2 text-[var(--text-secondary)]">
@@ -242,8 +242,8 @@
</select>
</div>
- <!-- Speaker Settings -->
- <div class="grid grid-cols-2 gap-3">
+ <!-- Speaker Settings - only show for connectors that support min/max speakers -->
+ <div v-if="connectorSupportsSpeakerCount" class="grid grid-cols-2 gap-3">
<div>
<label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
</label>
diff --git a/templates/index.html b/templates/index.html
index 06c62276..86899296 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -46,6 +46,8 @@
</div>
<div id="app" v-cloak
data-use-asr-endpoint="{{ use_asr_endpoint }}"
+ data-connector-supports-diarization="{{ connector_supports_diarization }}"
+ data-connector-supports-speaker-count="{{ connector_supports_speaker_count }}"
data-enable-archive-toggle="{{ enable_archive_toggle }}"
data-enable-internal-sharing="{{ enable_internal_sharing }}"
data-current-user-name="{{ (current_user.name or current_user.username) if current_user.is_authenticated else '' }}"
diff --git a/templates/modals/reprocess-modal.html b/templates/modals/reprocess-modal.html
index 1b2291d3..49903967 100644
--- a/templates/modals/reprocess-modal.html
+++ b/templates/modals/reprocess-modal.html
@@ -44,10 +44,10 @@
</div>
<div>
<p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.whatWillHappen')"></p>
- <p class="text-sm text-[var(--text-muted)]" v-if="reprocessType === 'transcription' && !useAsrEndpoint">
+ <p class="text-sm text-[var(--text-muted)]" v-if="reprocessType === 'transcription' && !connectorSupportsDiarization">
<span v-text="t('reprocessModal.audioReTranscribedFromScratch')"></span>
</p>
- <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'transcription' && useAsrEndpoint">
+ <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'transcription' && connectorSupportsDiarization">
<span v-text="t('reprocessModal.audioReTranscribedWithAsr')"></span>
</p>
<p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'summary'">
@@ -56,21 +56,24 @@
</div>
</div>
- <!-- ASR Options -->
- <div v-if="reprocessType === 'transcription' && useAsrEndpoint" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
+ <!-- Diarization Options (for connectors that support it) -->
+ <div v-if="reprocessType === 'transcription' && connectorSupportsDiarization" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
<h4 class="text-md font-semibold text-[var(--text-secondary)]" v-text="t('help.advancedAsrOptions')"></h4>
<div>
<label for="asr-language-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.language')"></label>
<input type="text" id="asr-language-reprocess" v-model="asrReprocessOptions.language" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., en, es, zh (optional)">
</div>
- <div>
- <label for="asr-min-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.minSpeakers')"></label>
- <input type="number" id="asr-min-speakers-reprocess" v-model.number="asrReprocessOptions.min_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
- </div>
- <div>
- <label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.maxSpeakers')"></label>
- <input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
- </div>
+ <!-- Min/Max Speakers - only show for connectors that support it (ASR endpoint, not OpenAI) -->
+ <template v-if="connectorSupportsSpeakerCount">
+ <div>
+ <label for="asr-min-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.minSpeakers')"></label>
+ <input type="number" id="asr-min-speakers-reprocess" v-model.number="asrReprocessOptions.min_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
+ </div>
+ <div>
+ <label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.maxSpeakers')"></label>
+ <input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
+ </div>
+ </template>
</div>
<!-- Custom Prompt Options for Summary Reprocessing -->