Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
"""
System info and configuration.
This blueprint was auto-generated from app.py route extraction.
"""
import os
import json
from datetime import datetime, timedelta
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
from src.database import db
from src.models import *
from src.utils import *
from src.config.version import get_version
from src.utils.localization import format_file_size, api_error, translate
from src.services.llm import TEXT_MODEL_BASE_URL, TEXT_MODEL_NAME
from src.config.app_config import ASR_BASE_URL, USE_NEW_TRANSCRIPTION_ARCHITECTURE, TRANSCRIPTION_MODEL_OPTIONS
from src.services.token_tracking import token_tracker
from src.services.transcription import TranscriptionCapability
# Create blueprint
system_bp = Blueprint('system', __name__)
# Configuration from environment
ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
DELETION_MODE = os.environ.get('DELETION_MODE', 'full_recording') # 'audio_only' or 'full_recording'
USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'
SHOW_USERNAMES_IN_UI = os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() == 'true'
ENABLE_AUTO_EXPORT = os.environ.get('ENABLE_AUTO_EXPORT', 'false').lower() == 'true'
ENABLE_INCOGNITO_MODE = os.environ.get('ENABLE_INCOGNITO_MODE', 'false').lower() == 'true'
INCOGNITO_MODE_DEFAULT = os.environ.get('INCOGNITO_MODE_DEFAULT', 'false').lower() == 'true'
VIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'
MAX_CONCURRENT_UPLOADS = int(os.environ.get('MAX_CONCURRENT_UPLOADS', '3'))
# Import chunking service (will be set from app)
chunking_service = None
# Global helpers (will be injected from app)
has_recording_access = None
bcrypt = None
csrf = None
limiter = None
def init_system_helpers(**kwargs):
"""Initialize helper functions and extensions from app."""
global has_recording_access, bcrypt, csrf, limiter, chunking_service
has_recording_access = kwargs.get('has_recording_access')
bcrypt = kwargs.get('bcrypt')
csrf = kwargs.get('csrf')
limiter = kwargs.get('limiter')
chunking_service = kwargs.get('chunking_service')
# Color scheme ids, as in colorSchemes in static/js/app.modular.js.
THEME_COLOR_SCHEMES = ('blue', 'emerald', 'purple', 'rose', 'amber', 'teal')
# --- Routes ---
@system_bp.route('/api/user/preferences', methods=['POST'])
@login_required
def save_user_preferences():
"""Save user preferences including UI language"""
data = request.json
if 'language' in data:
current_user.ui_language = data['language']
# Speaker-count entry mode for the transcription UIs (#362):
# 'range' (min/max fields) or 'single' (one count stored as min == max).
if 'speaker_count_mode' in data:
mode = data['speaker_count_mode']
if mode not in ('range', 'single'):
return jsonify(api_error('invalid_speaker_count_mode')), 400
current_user.speaker_count_mode = mode
# Theme, saved when the user changes it so other devices follow (D#419).
if 'dark_mode' in data:
if not isinstance(data['dark_mode'], bool):
return jsonify(api_error('invalid_dark_mode')), 400
current_user.theme_dark_mode = data['dark_mode']
if 'color_scheme' in data:
if data['color_scheme'] not in THEME_COLOR_SCHEMES:
return jsonify(api_error('invalid_color_scheme')), 400
current_user.theme_color_scheme = data['color_scheme']
db.session.commit()
return jsonify({
'success': True,
'message': translate('server.apiMessage.preferencesSaved'),
'ui_language': current_user.ui_language
})
def _storage_meter(user):
"""Storage against the quota; has_quota is False without one. The labels
are in the interface language's number format (#481)."""
try:
from src.services.storage_quota import usage
u = usage(user)
except Exception as e:
current_app.logger.warning(f"Could not read storage usage for user {user.id}: {e}")
return {'has_quota': False}
if not u['quota_bytes']:
return {'has_quota': False, 'used_bytes': u['used_bytes']}
return {'has_quota': True, 'used_bytes': u['used_bytes'], 'quota_bytes': u['quota_bytes'],
'percentage': u['percentage'], 'used_label': format_file_size(u['used_bytes']),
'quota_label': format_file_size(u['quota_bytes'])}
@system_bp.route('/api/user/token-budget', methods=['GET'])
@login_required
def get_user_token_budget():
"""Get current user's token budget status, and storage against the
quota for the header meters (#413)."""
try:
user = current_user
storage = _storage_meter(user)
# If user has no budget, return null to indicate unlimited
if not user.monthly_token_budget:
return jsonify({
'has_budget': False,
'budget': None,
'usage': 0,
'percentage': 0,
'storage': storage,
})
# Get current usage
current_usage = token_tracker.get_monthly_usage(user.id)
percentage = (current_usage / user.monthly_token_budget) * 100
return jsonify({
'has_budget': True,
'budget': user.monthly_token_budget,
'usage': current_usage,
'percentage': round(percentage, 1),
'storage': storage,
})
except Exception as e:
current_app.logger.error(f"Error getting token budget for user {current_user.id}: {e}")
return jsonify({'error': str(e)}), 500
# --- System Info API Endpoint ---
@system_bp.route('/api/system/info', methods=['GET'])
def get_system_info():
"""Get system information including version and model details."""
try:
# Use the same version detection logic as startup
version = get_version()
# Get transcription connector info
transcription_info = {
'connector': 'unknown',
'model': None,
'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(),
'model': getattr(connector, 'model', None), # Model name if available
'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}")
# Determine ASR status from connector (new arch) or env var (legacy)
is_asr_connector = transcription_info.get('connector') == 'asr_endpoint'
asr_enabled = is_asr_connector or USE_ASR_ENDPOINT
# Determine the active transcription endpoint based on which connector is in use
if asr_enabled:
active_endpoint = ASR_BASE_URL
else:
active_endpoint = os.environ.get('TRANSCRIPTION_BASE_URL', 'https://api.openai.com/v1')
return jsonify({
'version': version,
'llm_endpoint': TEXT_MODEL_BASE_URL,
'llm_model': TEXT_MODEL_NAME,
'transcription_endpoint': active_endpoint, # The actual endpoint being used
'asr_enabled': asr_enabled,
# Legacy fields for backwards compatibility
'whisper_endpoint': os.environ.get('TRANSCRIPTION_BASE_URL', 'https://api.openai.com/v1'),
'asr_endpoint': ASR_BASE_URL if asr_enabled else None,
'transcription': transcription_info,
})
except Exception as e:
current_app.logger.error(f"Error getting system info: {e}")
return jsonify(api_error('system_info_unavailable')), 500
# --- Tag API Endpoints ---
def _get_transcription_model_options():
"""Return the configured per-upload transcription model dropdown options.
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)
@system_bp.route('/api/config', methods=['GET'])
def get_config():
"""Get application configuration settings for the frontend."""
try:
# Get configurable file size limit
max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
# Audio-only video uploads: only the extracted audio is stored, so
# the upload itself can be larger than max_file_size_mb. Used by
# the frontend pre-check when "Keep audio only" is on (explicitly
# via toggle when VIDEO_RETENTION=true, or implicitly when
# VIDEO_RETENTION=false).
max_audio_only_video_size_mb = SystemSetting.get_setting(
'max_audio_only_video_size_mb',
int(max_file_size_mb) * 4 if max_file_size_mb else 1000,
)
# Get chunking configuration (supports both legacy and new formats)
chunking_info = {}
if ENABLE_CHUNKING and chunking_service:
mode, limit_value = chunking_service.parse_chunk_limit()
chunking_info = {
'chunking_enabled': True,
'chunking_mode': mode, # 'size' or 'duration'
'chunking_limit': limit_value, # Value in MB or seconds
'chunking_limit_display': f"{limit_value}{'MB' if mode == 'size' else 's'}"
}
else:
chunking_info = {
'chunking_enabled': False,
'chunking_mode': 'size',
'chunking_limit': 20,
'chunking_limit_display': '20MB'
}
# Check if current user can delete (for authenticated requests)
can_delete = True # Default to true for unauthenticated config requests
try:
from flask_login import current_user
if current_user and current_user.is_authenticated:
can_delete = USERS_CAN_DELETE or current_user.is_admin
except:
pass # If not authenticated, use default
# The "Audio removed" filter matters when retention removes audio, or
# when the user can remove audio by hand (same right as deleting).
enable_audio_removed_filter = (ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only') or can_delete
# 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
connector_supports_exact_speaker_count = False # Exact-N connectors (openasr) declare it (#362)
connector_supports_hotwords = USE_ASR_ENDPOINT
connector_supports_initial_prompt = USE_ASR_ENDPOINT
is_asr_connector = False
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
connector_supports_exact_speaker_count = connector.supports_exact_speaker_count
connector_supports_hotwords = connector.supports_hotwords
connector_supports_initial_prompt = connector.supports_initial_prompt
is_asr_connector = registry.get_active_connector_name() == 'asr_endpoint'
except Exception as e:
current_app.logger.warning(f"Could not get connector capabilities: {e}")
# Derive ASR status from connector or legacy env var
asr_enabled = is_asr_connector or USE_ASR_ENDPOINT
# Get user's default transcription language if authenticated
user_transcription_language = ''
user_summary_prompt = ''
try:
from flask_login import current_user
if current_user and current_user.is_authenticated:
if current_user.transcription_language:
user_transcription_language = current_user.transcription_language
if current_user.summary_prompt:
user_summary_prompt = current_user.summary_prompt
except:
pass
# Admin-defined default summary prompt. Used by the upload form to
# surface `{{name}}` placeholders that would otherwise substitute to
# empty strings on uploads that fall through to this prompt.
admin_default_summary_prompt = SystemSetting.get_setting('admin_default_summary_prompt', '') or ''
return jsonify({
'max_file_size_mb': max_file_size_mb,
'recording_disclaimer': SystemSetting.get_setting('recording_disclaimer', ''),
'upload_disclaimer': SystemSetting.get_setting('upload_disclaimer', ''),
'custom_banner': SystemSetting.get_setting('custom_banner', ''),
'use_asr_endpoint': asr_enabled, # Derived from connector or legacy env var
'connector_supports_diarization': connector_supports_diarization, # Connector capability
'connector_supports_speaker_count': connector_supports_speaker_count, # Min/max speakers
'connector_supports_exact_speaker_count': connector_supports_exact_speaker_count, # Exact-N only (#362)
'connector_supports_hotwords': connector_supports_hotwords,
'connector_supports_initial_prompt': connector_supports_initial_prompt,
'enable_internal_sharing': ENABLE_INTERNAL_SHARING,
'enable_audio_removed_filter': enable_audio_removed_filter,
'show_usernames_in_ui': SHOW_USERNAMES_IN_UI,
'can_delete_recordings': can_delete,
'users_can_delete_enabled': USERS_CAN_DELETE,
'enable_incognito_mode': ENABLE_INCOGNITO_MODE,
'incognito_mode_default': INCOGNITO_MODE_DEFAULT,
'enable_folders': SystemSetting.get_setting('enable_folders', False) == True,
'enable_auto_export': ENABLE_AUTO_EXPORT,
'video_retention': VIDEO_RETENTION,
'max_audio_only_video_size_mb': max_audio_only_video_size_mb,
'max_concurrent_uploads': MAX_CONCURRENT_UPLOADS,
'user_transcription_language': user_transcription_language,
'user_summary_prompt': user_summary_prompt,
'admin_default_summary_prompt': admin_default_summary_prompt,
'transcription_model_options': _get_transcription_model_options(),
**chunking_info
})
except Exception as e:
current_app.logger.error(f"Error fetching configuration: {e}")
return jsonify({'error': str(e)}), 500
@system_bp.route('/api/csrf-token', methods=['GET'])
def get_csrf_token():
"""Get a fresh CSRF token for the frontend."""
try:
from flask_wtf.csrf import generate_csrf
token = generate_csrf()
current_app.logger.info("Fresh CSRF token generated successfully")
return jsonify({'csrf_token': token})
except Exception as e:
current_app.logger.error(f"Error generating CSRF token: {e}")
return jsonify({'error': str(e)}), 500
# --- Flask Routes ---
@system_bp.route('/api/permissions/can-delete', methods=['GET'])
@login_required
def check_deletion_permission():
"""Check if the current user can delete recordings."""
try:
can_delete = USERS_CAN_DELETE or current_user.is_admin
return jsonify({
'can_delete': can_delete,
'is_admin': current_user.is_admin,
'users_can_delete_enabled': USERS_CAN_DELETE
})
except Exception as e:
current_app.logger.error(f"Error checking deletion permissions: {e}")
return jsonify({'error': str(e)}), 500