Skip to content

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

Python

Add admin-managed transcription model list with /v1/models discovery and DB-backed override of TRANSCRIPTION_MODELS_AVAILABLE

Murtaza Nasir085dcba57f0d
diff --git a/src/api/admin.py b/src/api/admin.py
index a5bf692f..bdd51783 100644
--- a/src/api/admin.py
+++ b/src/api/admin.py
@@ -1096,6 +1096,153 @@ def admin_trigger_auto_process():
+@admin_bp.route('/admin/transcription/discover-models', methods=['GET'])
+@login_required
+def admin_discover_transcription_models():
+ """Probe the active transcription connector's /v1/models endpoint.
+
+ Used by the admin UI to populate a "models available on this provider"
+ list when curating which models users can pick from. Returns a list of
+ {id, label, owned_by} dicts. Empty list if the connector does not
+ implement list_models() or the upstream is unreachable.
+ """
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ try:
+ from src.services.transcription import get_registry
+ registry = get_registry()
+ connector = registry.get_active_connector()
+ if not connector:
+ return jsonify({'error': 'No active transcription connector'}), 503
+
+ connector_name = registry.get_active_connector_name()
+ try:
+ models = connector.list_models()
+ except NotImplementedError:
+ return jsonify({
+ 'connector': connector_name,
+ 'supported': False,
+ 'models': [],
+ 'message': f'{connector_name} does not expose a model discovery endpoint.',
+ })
+
+ return jsonify({
+ 'connector': connector_name,
+ 'supported': True,
+ 'models': models or [],
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error discovering transcription models: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@admin_bp.route('/admin/transcription/visible-models', methods=['GET'])
+@login_required
+def admin_get_visible_models():
+ """Return the admin-curated list of models exposed in the user dropdown.
+
+ Falls back to the TRANSCRIPTION_MODELS_AVAILABLE env var when no DB
+ setting has been saved yet. The shape matches what /api/config returns
+ so the admin UI can pre-populate its form.
+ """
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ try:
+ from src.models import SystemSetting
+ from src.config.app_config import TRANSCRIPTION_MODEL_OPTIONS
+ import json as _json
+
+ raw = SystemSetting.get_setting('transcription_models_visible_json', None)
+ if raw:
+ try:
+ parsed = _json.loads(raw)
+ if isinstance(parsed, list):
+ return jsonify({
+ 'source': 'database',
+ 'options': parsed,
+ 'default_model': SystemSetting.get_setting('transcription_default_model', None),
+ })
+ except (ValueError, TypeError):
+ pass
+
+ return jsonify({
+ 'source': 'env' if TRANSCRIPTION_MODEL_OPTIONS else 'unset',
+ 'options': TRANSCRIPTION_MODEL_OPTIONS,
+ 'default_model': None,
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error reading visible transcription models: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@admin_bp.route('/admin/transcription/visible-models', methods=['POST'])
+@login_required
+def admin_save_visible_models():
+ """Save the admin-curated list of user-facing transcription models.
+
+ Body: { "options": [{"value": "...", "label": "..."}, ...],
+ "default_model": "..." | null }
+ """
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ try:
+ from src.models import SystemSetting
+ import json as _json
+
+ data = request.json or {}
+ options = data.get('options', [])
+ if not isinstance(options, list):
+ return jsonify({'error': 'options must be a list'}), 400
+
+ # Normalise each option into {value, label}.
+ normalised = []
+ for opt in options:
+ if isinstance(opt, str):
+ normalised.append({'value': opt, 'label': opt})
+ elif isinstance(opt, dict) and opt.get('value'):
+ normalised.append({
+ 'value': str(opt['value']).strip(),
+ 'label': str(opt.get('label') or opt['value']).strip(),
+ })
+
+ SystemSetting.set_setting(
+ key='transcription_models_visible_json',
+ value=_json.dumps(normalised),
+ description='Admin-curated list of transcription models exposed in user dropdowns. Overrides TRANSCRIPTION_MODELS_AVAILABLE env var when set.',
+ setting_type='string',
+ )
+
+ default_model = (data.get('default_model') or '').strip()
+ if default_model:
+ SystemSetting.set_setting(
+ key='transcription_default_model',
+ value=default_model,
+ description='Admin-selected default transcription model. Used when no per-upload, tag, or folder override is set.',
+ setting_type='string',
+ )
+ else:
+ existing = SystemSetting.query.filter_by(key='transcription_default_model').first()
+ if existing:
+ db.session.delete(existing)
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'options': normalised,
+ 'default_model': default_model or None,
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error saving visible transcription models: {e}")
+ db.session.rollback()
+ return jsonify({'error': str(e)}), 500
+
+
@admin_bp.route('/admin/inquire/process-recordings', methods=['POST'])
@login_required
def admin_process_recordings_for_inquire():
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 0831a51c..ba20acff 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -1828,16 +1828,10 @@ def start_transcription(recording_id):
data = request.get_json() or {}
# Apply the same per-request model override path as the upload/reprocess
- # web endpoints (issue #266). Validate against TRANSCRIPTION_MODELS_AVAILABLE
- # when it is set; drop unknown values silently.
- transcription_model = (data.get('transcription_model') or '').strip() or None
- if transcription_model:
- from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
- if TRANSCRIPTION_MODELS_AVAILABLE and transcription_model not in TRANSCRIPTION_MODELS_AVAILABLE:
- current_app.logger.warning(
- f"Ignoring transcription_model={transcription_model!r} from API v1 transcribe — not in TRANSCRIPTION_MODELS_AVAILABLE"
- )
- transcription_model = None
+ # web endpoints (issue #266). Validates against the admin-curated list +
+ # env allowlist and applies the admin-saved default when nothing was sent.
+ from src.api.recordings import _resolve_transcription_model
+ transcription_model = _resolve_transcription_model(data.get('transcription_model'))
params = {
'language': data.get('language'),
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 90e4197f..88e58914 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -23,6 +23,54 @@ 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, USE_NEW_TRANSCRIPTION_ARCHITECTURE
+
+
+def _resolve_transcription_model(value):
+ """Apply admin-curated allowlist + default to a candidate model name.
+
+ Resolution:
+ 1. If the caller passed a non-empty value:
+ a. If the admin saved a visible-models list in system_setting and the
+ value is in it, accept.
+ b. Else if TRANSCRIPTION_MODELS_AVAILABLE is set and the value is in
+ it, accept.
+ c. Else if neither list is configured, accept (no allowlist enforced).
+ d. Otherwise, drop the value with a warning.
+ 2. If the caller passed nothing, fall back to the admin-saved default
+ model (system_setting key `transcription_default_model`) when set.
+ Returns the validated model id or None.
+ """
+ from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
+ import json as _json
+
+ candidate = (value or '').strip() or None
+ visible = []
+ try:
+ raw = SystemSetting.get_setting('transcription_models_visible_json', None)
+ if raw:
+ parsed = _json.loads(raw)
+ if isinstance(parsed, list):
+ visible = [
+ (item['value'] if isinstance(item, dict) else item)
+ for item in parsed if item
+ ]
+ except Exception:
+ visible = []
+
+ if candidate:
+ in_db_list = bool(visible) and candidate in visible
+ in_env_list = bool(TRANSCRIPTION_MODELS_AVAILABLE) and candidate in TRANSCRIPTION_MODELS_AVAILABLE
+ if visible or TRANSCRIPTION_MODELS_AVAILABLE:
+ if not (in_db_list or in_env_list):
+ current_app.logger.warning(
+ f"Ignoring transcription_model={candidate!r} — not in admin-curated list or TRANSCRIPTION_MODELS_AVAILABLE"
+ )
+ candidate = None
+ return candidate
+
+ # Fall back to admin-saved default when no override flowed through.
+ default = SystemSetting.get_setting('transcription_default_model', None)
+ return default or None
from src.tasks.processing import format_transcription_for_llm
from src.utils.ffmpeg_utils import FFmpegError, FFmpegNotFoundError
from src.services.speaker import update_speaker_usage, identify_unidentified_speakers_from_text
@@ -1044,16 +1092,9 @@ def reprocess_transcription(recording_id):
if not initial_prompt and owner.transcription_initial_prompt:
initial_prompt = owner.transcription_initial_prompt
- # Validate the per-request model against the configured allowlist before
- # passing it to the connector. If the user submitted an unknown model
- # (e.g. via a stale UI cache), drop it rather than crashing the API.
- if transcription_model:
- from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
- if TRANSCRIPTION_MODELS_AVAILABLE and transcription_model not in TRANSCRIPTION_MODELS_AVAILABLE:
- current_app.logger.warning(
- f"Ignoring transcription_model={transcription_model!r} — not in TRANSCRIPTION_MODELS_AVAILABLE"
- )
- transcription_model = None
+ # Validate against admin-curated list and apply admin default when
+ # nothing else in the chain set a model. See _resolve_transcription_model.
+ transcription_model = _resolve_transcription_model(transcription_model)
# Enqueue the job with all parameters
job_params = {
@@ -2318,17 +2359,9 @@ def upload_file():
current_app.logger.info(f"Initial recording record created with ID: {recording.id}")
- # Validate the per-request transcription_model against the configured
- # allowlist before passing it to the connector. If the user submitted
- # an unknown model (e.g. via a stale UI cache), drop it rather than
- # propagating a bad value into the worker.
- if transcription_model:
- from src.config.app_config import TRANSCRIPTION_MODELS_AVAILABLE
- if TRANSCRIPTION_MODELS_AVAILABLE and transcription_model not in TRANSCRIPTION_MODELS_AVAILABLE:
- current_app.logger.warning(
- f"Ignoring transcription_model={transcription_model!r} — not in TRANSCRIPTION_MODELS_AVAILABLE"
- )
- transcription_model = None
+ # Validate against admin-curated list and apply admin default when
+ # nothing else in the chain set a model.
+ transcription_model = _resolve_transcription_model(transcription_model)
# --- Queue transcription job ---
first_tag = selected_tags[0] if selected_tags else None
diff --git a/src/api/system.py b/src/api/system.py
index a8af6f41..a1df68e9 100644
--- a/src/api/system.py
+++ b/src/api/system.py
@@ -182,9 +182,22 @@ def get_system_info():
def _get_transcription_model_options():
"""Return the configured per-upload transcription model dropdown options.
- When TRANSCRIPTION_MODELS_AVAILABLE is unset the list is empty and the
- frontend hides the dropdown. Issue #266.
+ Resolution order:
+ 1. SystemSetting `transcription_models_visible_json` (admin UI overrides)
+ 2. TRANSCRIPTION_MODELS_AVAILABLE env var
+ 3. Empty list (dropdown hidden)
+ Issue #266.
"""
+ try:
+ from src.models import SystemSetting
+ import json as _json
+ raw = SystemSetting.get_setting('transcription_models_visible_json', None)
+ if raw:
+ parsed = _json.loads(raw)
+ if isinstance(parsed, list):
+ return parsed
+ except Exception:
+ pass
return list(TRANSCRIPTION_MODEL_OPTIONS)
diff --git a/src/services/transcription/base.py b/src/services/transcription/base.py
index 20ea75fb..6e6eadfc 100644
--- a/src/services/transcription/base.py
+++ b/src/services/transcription/base.py
@@ -247,6 +247,18 @@ class BaseTranscriptionConnector(ABC):
"""
return {}
+ def list_models(self) -> List[Dict[str, Any]]:
+ """Discover models the upstream provider exposes.
+
+ Connectors that talk to an OpenAI-compatible /v1/models endpoint
+ should override this. Each item is a dict with at minimum 'id' and
+ an optional 'label' or 'owned_by'. The default raises
+ NotImplementedError so callers can detect unsupported providers.
+ """
+ raise NotImplementedError(
+ f"{type(self).__name__} does not implement list_models()"
+ )
+
def health_check(self) -> bool:
"""
Check if the connector is properly configured and reachable.
diff --git a/src/services/transcription/connectors/asr_endpoint.py b/src/services/transcription/connectors/asr_endpoint.py
index d9432453..b9991f30 100644
--- a/src/services/transcription/connectors/asr_endpoint.py
+++ b/src/services/transcription/connectors/asr_endpoint.py
@@ -300,6 +300,31 @@ class ASREndpointConnector(BaseTranscriptionConnector):
raw_response=data
)
+ def list_models(self):
+ """Probe the ASR service's /v1/models endpoint and return the list.
+
+ The whisperx-asr-service fork (and any OpenAI-compatible variant)
+ exposes /v1/models. The upstream onerahmet/whisper-asr-webservice does
+ not, in which case we return an empty list.
+ """
+ try:
+ with httpx.Client(timeout=10.0) as client:
+ resp = client.get(f"{self.base_url}/v1/models")
+ if resp.status_code != 200:
+ return []
+ data = resp.json().get('data', [])
+ return [
+ {
+ 'id': m.get('id'),
+ 'label': m.get('id'),
+ 'owned_by': m.get('owned_by', 'unknown'),
+ }
+ for m in data if m.get('id')
+ ]
+ except Exception as e:
+ logger.warning(f"asr_endpoint /v1/models probe failed: {e}")
+ return []
+
def health_check(self) -> bool:
"""Check if ASR endpoint is reachable."""
try:
diff --git a/src/services/transcription/connectors/mistral.py b/src/services/transcription/connectors/mistral.py
index 050b90b7..0db34c71 100644
--- a/src/services/transcription/connectors/mistral.py
+++ b/src/services/transcription/connectors/mistral.py
@@ -222,6 +222,31 @@ class MistralTranscriptionConnector(BaseTranscriptionConnector):
segments.append(segment)
return segments
+ def list_models(self):
+ """Return Voxtral models from Mistral's /v1/models endpoint.
+
+ Filters to ids containing 'voxtral' so the dropdown only offers
+ audio-capable models.
+ """
+ try:
+ resp = self.client.get('/v1/models')
+ if resp.status_code != 200:
+ return []
+ data = resp.json().get('data', [])
+ audio = []
+ for m in data:
+ mid = m.get('id', '')
+ if mid and 'voxtral' in mid.lower():
+ audio.append({
+ 'id': mid,
+ 'label': mid,
+ 'owned_by': m.get('owned_by', 'mistralai'),
+ })
+ return audio
+ except Exception as e:
+ logger.warning(f"mistral /v1/models probe failed: {e}")
+ return []
+
def health_check(self) -> bool:
"""Check if the connector is properly configured."""
return bool(self.config.get('api_key'))
diff --git a/src/services/transcription/connectors/openai_transcribe.py b/src/services/transcription/connectors/openai_transcribe.py
index 2a4317a9..ad006130 100644
--- a/src/services/transcription/connectors/openai_transcribe.py
+++ b/src/services/transcription/connectors/openai_transcribe.py
@@ -308,6 +308,28 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):
raw_response=response if isinstance(response, dict) else None
)
+ def list_models(self):
+ """Return audio-transcription-relevant models from /v1/models.
+
+ Filters to ids containing 'transcribe' or 'whisper' so the dropdown
+ only offers models that can actually run audio transcription.
+ """
+ try:
+ resp = self.client.models.list()
+ audio = []
+ for m in resp.data:
+ mid = getattr(m, 'id', '')
+ if mid and ('transcribe' in mid.lower() or 'whisper' in mid.lower()):
+ audio.append({
+ 'id': mid,
+ 'label': mid,
+ 'owned_by': getattr(m, 'owned_by', 'openai'),
+ })
+ return audio
+ except Exception as e:
+ logger.warning(f"openai_transcribe /v1/models probe failed: {e}")
+ return []
+
def health_check(self) -> bool:
"""Check if the connector is properly configured."""
return bool(self.config.get('api_key'))
diff --git a/src/services/transcription/connectors/openai_whisper.py b/src/services/transcription/connectors/openai_whisper.py
index 96fb0b92..8692b51d 100644
--- a/src/services/transcription/connectors/openai_whisper.py
+++ b/src/services/transcription/connectors/openai_whisper.py
@@ -126,6 +126,27 @@ class OpenAIWhisperConnector(BaseTranscriptionConnector):
logger.error(f"Whisper transcription failed: {error_msg}")
raise TranscriptionError(f"Whisper transcription failed: {error_msg}") from e
+ def list_models(self):
+ """Return audio-relevant models from OpenAI's /v1/models.
+
+ Filters the full catalog to entries whose id contains 'whisper'.
+ """
+ try:
+ resp = self.client.models.list()
+ audio = []
+ for m in resp.data:
+ mid = getattr(m, 'id', '')
+ if mid and 'whisper' in mid.lower():
+ audio.append({
+ 'id': mid,
+ 'label': mid,
+ 'owned_by': getattr(m, 'owned_by', 'openai'),
+ })
+ return audio
+ except Exception as e:
+ logger.warning(f"openai_whisper /v1/models probe failed: {e}")
+ return []
+
def health_check(self) -> bool:
"""Check if the connector is properly configured."""
return bool(self.config.get('api_key'))
diff --git a/src/services/transcription/connectors/vibevoice.py b/src/services/transcription/connectors/vibevoice.py
index 4eaa4aa3..4a531852 100644
--- a/src/services/transcription/connectors/vibevoice.py
+++ b/src/services/transcription/connectors/vibevoice.py
@@ -317,6 +317,29 @@ class VibeVoiceTranscriptionConnector(BaseTranscriptionConnector):
segments.append(segment)
return segments
+ def list_models(self):
+ """Return models from the vLLM /v1/models endpoint.
+
+ vLLM exposes this in OpenAI-compatible form. Whatever model the
+ VibeVoice server has loaded shows up here.
+ """
+ try:
+ resp = self.client.get('/v1/models')
+ if resp.status_code != 200:
+ return []
+ data = resp.json().get('data', [])
+ return [
+ {
+ 'id': m.get('id'),
+ 'label': m.get('id'),
+ 'owned_by': m.get('owned_by', 'vllm'),
+ }
+ for m in data if m.get('id')
+ ]
+ except Exception as e:
+ logger.warning(f"vibevoice /v1/models probe failed: {e}")
+ return []
+
def health_check(self) -> bool:
"""Check if the vLLM server is reachable."""
try:
diff --git a/templates/admin.html b/templates/admin.html
index 689af2cd..a5502e4b 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -662,7 +662,69 @@
<i class="fas fa-sync-alt mr-2"></i> ${t('buttons.refresh')}
</button>
</div>
-
+
+ <!-- Transcription Models curation -->
+ <div class="mb-6 bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
+ <div class="flex justify-between items-start mb-3">
+ <div>
+ <h4 class="text-md font-semibold text-[var(--text-primary)]"><i class="fas fa-microphone-lines mr-2"></i>Transcription Models</h4>
+ <p class="text-sm text-[var(--text-muted)] mt-1">Discover models on the active transcription provider, then choose which ones users can pick from at upload time. Saved choices override <code>TRANSCRIPTION_MODELS_AVAILABLE</code> in the environment.</p>
+ </div>
+ <button @click="discoverTranscriptionModels" :disabled="discoveringModels"
+ class="px-3 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded-lg shadow hover:bg-[var(--bg-tertiary)] disabled:opacity-50">
+ <i :class="discoveringModels ? 'fas fa-spinner fa-spin' : 'fas fa-search'" class="mr-2"></i>
+ ${ discoveringModels ? 'Discovering...' : 'Discover models' }
+ </button>
+ </div>
+
+ <div v-if="modelDiscoveryError" class="mb-3 text-sm text-[var(--text-danger-strong)]">
+ ${ modelDiscoveryError }
+ </div>
+
+ <div v-if="modelDiscoveryResult" class="mb-3 text-xs text-[var(--text-muted)]">
+ Active connector: <code>${ modelDiscoveryResult.connector }</code>
+ <span v-if="!modelDiscoveryResult.supported"> (no model discovery API; add models manually below)</span>
+ </div>
+
+ <table v-if="visibleTranscriptionModels.length > 0 || (modelDiscoveryResult && modelDiscoveryResult.models && modelDiscoveryResult.models.length > 0)"
+ class="w-full text-sm border-collapse">
+ <thead>
+ <tr class="text-left text-xs uppercase text-[var(--text-muted)] border-b border-[var(--border-primary)]">
+ <th class="py-2">Visible</th>
+ <th class="py-2">Default</th>
+ <th class="py-2">Model id</th>
+ <th class="py-2">Label shown to users</th>
+ <th class="py-2">Source</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="row in transcriptionModelRows" :key="row.value"
+ class="border-b border-[var(--border-primary)]/50">
+ <td class="py-2"><input type="checkbox" v-model="row.visible"></td>
+ <td class="py-2"><input type="radio" :value="row.value" v-model="transcriptionDefaultModel" :disabled="!row.visible"></td>
+ <td class="py-2 font-mono text-xs">${ row.value }</td>
+ <td class="py-2"><input type="text" v-model="row.label" class="w-full px-2 py-1 text-sm bg-[var(--bg-input)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded"></td>
+ <td class="py-2 text-xs text-[var(--text-muted)]">${ row.source }</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <p v-else class="text-sm text-[var(--text-muted)] mb-3">No models discovered yet. Click "Discover models" to probe the active connector, or set <code>TRANSCRIPTION_MODELS_AVAILABLE</code> in your environment.</p>
+
+ <div class="flex items-center gap-3 mt-4">
+ <button @click="addManualTranscriptionModel"
+ class="px-3 py-2 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded-lg hover:bg-[var(--bg-tertiary)]">
+ <i class="fas fa-plus mr-1"></i> Add custom model id
+ </button>
+ <button @click="saveVisibleTranscriptionModels" :disabled="savingModels"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] disabled:opacity-50">
+ <i :class="savingModels ? 'fas fa-spinner fa-spin' : 'fas fa-save'" class="mr-2"></i>
+ ${ savingModels ? 'Saving...' : 'Save selection' }
+ </button>
+ <span v-if="modelSaveMessage" class="text-sm" :class="modelSaveError ? 'text-[var(--text-danger-strong)]' : 'text-[var(--text-success-strong)]'">${ modelSaveMessage }</span>
+ </div>
+ </div>
+
<!-- Settings List -->
<div class="space-y-4">
<div v-for="setting in settings" :key="setting.id" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
@@ -1840,6 +1902,142 @@ Summarization Instructions:
const dailyEmbeddingChart = ref(null);
const monthlyEmbeddingChart = ref(null);
const settings = ref([]);
+ // Transcription model curation state
+ const visibleTranscriptionModels = ref([]); // [{value, label}, ...]
+ const transcriptionDefaultModel = ref(null);
+ const transcriptionDefaultModelSaved = ref(null); // For change tracking
+ const modelDiscoveryResult = ref(null);
+ const modelDiscoveryError = ref('');
+ const discoveringModels = ref(false);
+ const savingModels = ref(false);
+ const modelSaveMessage = ref('');
+ const modelSaveError = ref(false);
+ const manualModelRows = ref([]); // for "Add custom model id" entries
+
+ // Combined view: discovered ∪ saved ∪ manual, deduped by id.
+ const transcriptionModelRows = computed(() => {
+ const map = new Map();
+ // Saved selections come first so order is stable.
+ for (const opt of visibleTranscriptionModels.value) {
+ if (opt && opt.value && !map.has(opt.value)) {
+ map.set(opt.value, {
+ value: opt.value,
+ label: opt.label || opt.value,
+ visible: true,
+ source: 'saved',
+ });
+ }
+ }
+ // Discovery additions
+ const discovered = (modelDiscoveryResult.value && modelDiscoveryResult.value.models) || [];
+ for (const m of discovered) {
+ if (!m.id) continue;
+ if (map.has(m.id)) {
+ const row = map.get(m.id);
+ if (row.source === 'saved') row.source = 'saved + discovered';
+ } else {
+ map.set(m.id, {
+ value: m.id,
+ label: m.label || m.id,
+ visible: false,
+ source: 'discovered (' + (m.owned_by || 'unknown') + ')',
+ });
+ }
+ }
+ // Manual additions
+ for (const m of manualModelRows.value) {
+ if (!m.value) continue;
+ if (!map.has(m.value)) {
+ map.set(m.value, {
+ value: m.value,
+ label: m.label || m.value,
+ visible: true,
+ source: 'manual',
+ });
+ }
+ }
+ return Array.from(map.values());
+ });
+
+ const loadVisibleTranscriptionModels = async () => {
+ try {
+ const r = await fetch('/admin/transcription/visible-models');
+ if (!r.ok) return;
+ const data = await r.json();
+ visibleTranscriptionModels.value = (data.options || []).map(o => ({
+ value: o.value,
+ label: o.label || o.value,
+ }));
+ transcriptionDefaultModel.value = data.default_model || null;
+ transcriptionDefaultModelSaved.value = data.default_model || null;
+ } catch (e) {
+ console.error('Failed to load visible transcription models:', e);
+ }
+ };
+
+ const discoverTranscriptionModels = async () => {
+ discoveringModels.value = true;
+ modelDiscoveryError.value = '';
+ try {
+ const r = await fetch('/admin/transcription/discover-models');
+ const data = await r.json();
+ if (!r.ok) {
+ modelDiscoveryError.value = data.error || 'Discovery failed';
+ modelDiscoveryResult.value = null;
+ } else {
+ modelDiscoveryResult.value = data;
+ if (data.supported && (!data.models || data.models.length === 0)) {
+ modelDiscoveryError.value = 'Connector reports no models. Is the upstream service running?';
+ }
+ }
+ } catch (e) {
+ modelDiscoveryError.value = 'Network error: ' + e.message;
+ } finally {
+ discoveringModels.value = false;
+ }
+ };
+
+ const addManualTranscriptionModel = () => {
+ const id = window.prompt('Enter the model id (e.g. whisper-1, large-v3, voxtral-mini-latest):');
+ if (!id) return;
+ manualModelRows.value.push({ value: id.trim(), label: id.trim() });
+ };
+
+ const saveVisibleTranscriptionModels = async () => {
+ savingModels.value = true;
+ modelSaveMessage.value = '';
+ modelSaveError.value = false;
+ try {
+ const visible = transcriptionModelRows.value
+ .filter(r => r.visible)
+ .map(r => ({ value: r.value, label: r.label || r.value }));
+ // Drop default if it's not in the visible list anymore
+ const defaultModel = visible.some(o => o.value === transcriptionDefaultModel.value)
+ ? transcriptionDefaultModel.value
+ : null;
+ const r = await fetch('/admin/transcription/visible-models', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
+ },
+ body: JSON.stringify({ options: visible, default_model: defaultModel }),
+ });
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error || 'Save failed');
+ visibleTranscriptionModels.value = data.options || [];
+ transcriptionDefaultModel.value = data.default_model || null;
+ transcriptionDefaultModelSaved.value = data.default_model || null;
+ manualModelRows.value = [];
+ modelSaveMessage.value = `Saved ${data.options.length} model${data.options.length === 1 ? '' : 's'}.`;
+ } catch (e) {
+ modelSaveMessage.value = 'Save failed: ' + e.message;
+ modelSaveError.value = true;
+ } finally {
+ savingModels.value = false;
+ }
+ };
+
const isLoadingUsers = ref(true);
const isLoadingSettings = ref(false);
const userSearchQuery = ref('');
@@ -3207,6 +3405,7 @@ Summarization Instructions:
await loadSettings();
}
loadDefaultPrompt();
+ loadVisibleTranscriptionModels();
if (inquireModeEnabled.value) {
loadInquireStatus();
@@ -3424,7 +3623,22 @@ Summarization Instructions:
processAllRecordings,
processBatchRecordings,
reembedAllRecordings,
-
+
+ // Transcription model curation
+ visibleTranscriptionModels,
+ transcriptionDefaultModel,
+ modelDiscoveryResult,
+ modelDiscoveryError,
+ discoveringModels,
+ savingModels,
+ modelSaveMessage,
+ modelSaveError,
+ transcriptionModelRows,
+ discoverTranscriptionModels,
+ addManualTranscriptionModel,
+ saveVisibleTranscriptionModels,
+ loadVisibleTranscriptionModels,
+
// Default Prompts methods
loadDefaultPrompt,
saveDefaultPrompt,