Skip to content

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

Python

Fix duplicate copy buttons in docs and add automatic audio format conversion for unsupported formats

Murtaza Nasir8eb68429fd26
diff --git a/docs/javascripts/extra.js b/docs/javascripts/extra.js
index aebb1c14..2fef1b23 100644
--- a/docs/javascripts/extra.js
+++ b/docs/javascripts/extra.js
@@ -1,49 +1,6 @@
// Custom JavaScript for Speakr documentation
-// Add copy button to code blocks
document.addEventListener('DOMContentLoaded', function() {
- // Initialize copy to clipboard for code blocks
- const codeBlocks = document.querySelectorAll('pre > code');
-
- codeBlocks.forEach(function(codeBlock) {
- // Skip if already has a copy button
- if (codeBlock.parentElement.querySelector('.copy-button')) return;
-
- const button = document.createElement('button');
- button.className = 'copy-button';
- button.textContent = 'Copy';
- button.style.position = 'absolute';
- button.style.top = '0.5em';
- button.style.right = '0.5em';
- button.style.padding = '0.25em 0.5em';
- button.style.fontSize = '0.875em';
- button.style.background = 'var(--md-code-bg-color)';
- button.style.color = 'var(--md-code-fg-color)';
- button.style.border = '1px solid var(--md-default-fg-color--lightest)';
- button.style.borderRadius = '0.25em';
- button.style.cursor = 'pointer';
-
- const pre = codeBlock.parentElement;
- pre.style.position = 'relative';
- pre.appendChild(button);
-
- button.addEventListener('click', async function() {
- try {
- await navigator.clipboard.writeText(codeBlock.textContent);
- button.textContent = 'Copied!';
- setTimeout(() => {
- button.textContent = 'Copy';
- }, 2000);
- } catch (err) {
- console.error('Failed to copy:', err);
- button.textContent = 'Failed';
- setTimeout(() => {
- button.textContent = 'Copy';
- }, 2000);
- }
- });
- });
-
// Add smooth scrolling for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
diff --git a/src/app.py b/src/app.py
index 7a60eca7..55e921bd 100644
--- a/src/app.py
+++ b/src/app.py
@@ -2725,33 +2725,94 @@ def transcribe_single_file(filepath, recording):
db.session.commit()
raise Exception(f"Audio extraction failed: {str(e)}")
- with open(actual_filepath, 'rb') as audio_file:
- transcription_client = OpenAI(
- api_key=transcription_api_key,
- base_url=transcription_base_url,
- http_client=http_client_no_proxy
- )
- whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
-
- user_transcription_language = None
- if recording and recording.owner:
- user_transcription_language = recording.owner.transcription_language
-
- transcription_language = user_transcription_language
+ # List of formats supported by Whisper API
+ WHISPER_SUPPORTED_FORMATS = ['flac', 'm4a', 'mp3', 'mp4', 'mpeg', 'mpga', 'oga', 'ogg', 'wav', 'webm']
+
+ # Check if the file format needs conversion
+ file_ext = os.path.splitext(actual_filepath)[1].lower().lstrip('.')
+ converted_filepath = None
+
+ try:
+ with open(actual_filepath, 'rb') as audio_file:
+ transcription_client = OpenAI(
+ api_key=transcription_api_key,
+ base_url=transcription_base_url,
+ http_client=http_client_no_proxy
+ )
+ whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
+
+ user_transcription_language = None
+ if recording and recording.owner:
+ user_transcription_language = recording.owner.transcription_language
+
+ transcription_language = user_transcription_language
- transcription_params = {
- "model": whisper_model,
- "file": audio_file
- }
+ transcription_params = {
+ "model": whisper_model,
+ "file": audio_file
+ }
- if transcription_language:
- transcription_params["language"] = transcription_language
- app.logger.info(f"Using transcription language: {transcription_language}")
- else:
- app.logger.info("Transcription language not set, using auto-detection or service default.")
+ if transcription_language:
+ transcription_params["language"] = transcription_language
+ app.logger.info(f"Using transcription language: {transcription_language}")
+ else:
+ app.logger.info("Transcription language not set, using auto-detection or service default.")
- transcript = transcription_client.audio.transcriptions.create(**transcription_params)
- return transcript.text
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ return transcript.text
+
+ except Exception as e:
+ # Check if it's a format error
+ error_message = str(e)
+ if "Invalid file format" in error_message or "Supported formats" in error_message:
+ app.logger.warning(f"Unsupported audio format '{file_ext}' detected, converting to MP3...")
+
+ # Convert to MP3
+ import tempfile
+ temp_mp3_filepath = None
+ try:
+ with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_mp3:
+ temp_mp3_filepath = temp_mp3.name
+
+ # Use ffmpeg to convert to MP3 with consistent settings
+ subprocess.run(
+ ['ffmpeg', '-i', actual_filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],
+ check=True,
+ capture_output=True
+ )
+ app.logger.info(f"Successfully converted {actual_filepath} to MP3 format")
+ converted_filepath = temp_mp3_filepath
+
+ # Retry transcription with converted file
+ with open(converted_filepath, 'rb') as audio_file:
+ transcription_client = OpenAI(
+ api_key=transcription_api_key,
+ base_url=transcription_base_url,
+ http_client=http_client_no_proxy
+ )
+
+ transcription_params = {
+ "model": whisper_model,
+ "file": audio_file
+ }
+
+ if transcription_language:
+ transcription_params["language"] = transcription_language
+
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ return transcript.text
+
+ finally:
+ # Clean up temporary converted file
+ if converted_filepath and os.path.exists(converted_filepath):
+ try:
+ os.unlink(converted_filepath)
+ app.logger.info(f"Cleaned up temporary converted file: {converted_filepath}")
+ except Exception as cleanup_error:
+ app.logger.warning(f"Failed to clean up temporary file {converted_filepath}: {cleanup_error}")
+ else:
+ # Re-raise if it's not a format error
+ raise
def transcribe_with_chunking(app_context, recording_id, filepath, filename_for_asr):
"""Transcribe a large audio file using chunking."""
@@ -2847,7 +2908,31 @@ def transcribe_with_chunking(app_context, recording_id, filepath, filename_for_a
app.logger.info(f"Chunk {i+1}: Using timeout config - connect: 30s, read: 300s, write: 60s")
app.logger.info(f"Chunk {i+1}: Max retries: 2, API timeout: 300s")
- transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ try:
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ except Exception as chunk_error:
+ # Check if it's a format error (unlikely for chunks since they're MP3, but handle it)
+ error_msg = str(chunk_error)
+ if "Invalid file format" in error_msg or "Supported formats" in error_msg:
+ app.logger.warning(f"Chunk {i+1} format issue, attempting conversion...")
+ # Convert chunk to MP3 if needed
+ import tempfile
+ with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_mp3:
+ temp_mp3_path = temp_mp3.name
+ try:
+ subprocess.run(
+ ['ffmpeg', '-i', chunk['path'], '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_path],
+ check=True,
+ capture_output=True
+ )
+ with open(temp_mp3_path, 'rb') as converted_chunk:
+ transcription_params['file'] = converted_chunk
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ finally:
+ if os.path.exists(temp_mp3_path):
+ os.unlink(temp_mp3_path)
+ else:
+ raise
api_time = time.time() - api_start
app.logger.info(f"Chunk {i+1}: API call completed in {api_time:.2f}s")
diff --git a/templates/admin.html b/templates/admin.html
index a3b84446..725df264 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -476,31 +476,34 @@
<div>
<h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">${t('adminDashboard.systemPrompt')}:</h5>
<div class="bg-[var(--bg-secondary)] p-4 rounded-md border border-[var(--border-secondary)]">
- <pre class="text-xs text-[var(--text-secondary)] whitespace-pre-wrap font-mono">You are an AI assistant that generates comprehensive summaries for meeting transcripts. Respond only with the summary in Markdown format. Do NOT use markdown code blocks (```markdown). Provide raw markdown content directly.<span v-if="defaultSummaryPrompt || originalDefaultPrompt">
+ <pre class="text-xs text-[var(--text-secondary)] whitespace-pre-wrap font-mono">You are an AI assistant that generates comprehensive summaries for meeting transcripts. Respond only with the summary in Markdown format. Do NOT use markdown code blocks (```markdown). Provide raw markdown content directly.
-${t('adminDashboard.summarizationInstructions')}:
-${ defaultSummaryPrompt || originalDefaultPrompt }</span></pre>
+Context:
+- Current date: {current_date}
+- Tags applied to this transcript by the user: {tag_names} <span class="text-[var(--text-muted)]">(if tags exist)</span>
+- Information about the user: Name: {name}, Job title: {job_title}, Company: {company} <span class="text-[var(--text-muted)]">(if provided)</span>
+
+<span class="text-[var(--text-muted)]">Language Requirement: You MUST generate the entire summary in {user_output_language}. This is mandatory. (if language preference is set)</span></pre>
</div>
- <p class="text-xs text-[var(--text-muted)] mt-2">
- <i class="fas fa-info-circle mr-1"></i>
- ${t('adminDashboard.languagePreferenceNote')}
- </p>
</div>
<div>
<h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">${t('adminDashboard.userMessageTemplate')}:</h5>
<div class="bg-[var(--bg-secondary)] p-4 rounded-md border border-[var(--border-secondary)]">
- <pre class="text-xs text-[var(--text-secondary)] whitespace-pre-wrap font-mono">Context:
-- Current date: {current_date}
-- Tags applied to this transcript by the user: {tag_names} <span class="text-[var(--text-muted)]">(if tags exist)</span>
-- Information about the user: Name: {name}, Job title: {job_title}, Company: {company} <span class="text-[var(--text-muted)]">(if provided)</span>
-
-Transcription:
+ <pre class="text-xs text-[var(--text-secondary)] whitespace-pre-wrap font-mono">Transcription:
"""
{transcript_text}
"""
-Please analyze the above transcription and generate a summary following the provided instructions.</pre>
+Summarization Instructions:
+<span class="text-[var(--text-muted)]">/* This section is dynamically replaced with one of the following (in order of priority):
+ 1. Combined tag prompts (if tags with custom prompts are selected)
+ 2. User's personal summarization prompt (if set in account settings)
+ 3. Admin default prompt (shown below)
+ 4. System fallback prompt */</span>
+<span v-if="defaultSummaryPrompt || originalDefaultPrompt">${ defaultSummaryPrompt || originalDefaultPrompt }</span>
+
+<span class="text-[var(--text-muted)]">{language_directive} (e.g., "Ensure your response is in {language}." if language is set)</span></pre>
</div>
<p class="text-xs text-[var(--text-muted)] mt-2">
<i class="fas fa-info-circle mr-1"></i>