Skip to content

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

Python

added asr endpoint

Murtaza Nasir00e9dc168148
diff --git a/app.py b/app.py
index ef4664de..905575bb 100644
--- a/app.py
+++ b/app.py
@@ -85,6 +85,7 @@ class User(db.Model, UserMixin):
name = db.Column(db.String(100), nullable=True)
job_title = db.Column(db.String(100), nullable=True)
company = db.Column(db.String(100), nullable=True)
+ diarize = db.Column(db.Boolean, default=False)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
@@ -199,6 +200,8 @@ with app.app_context():
app.logger.info("Added job_title column to user table")
if add_column_if_not_exists(engine, 'user', 'company', 'VARCHAR(100)'):
app.logger.info("Added company column to user table")
+ if add_column_if_not_exists(engine, 'user', 'diarize', 'BOOLEAN'):
+ app.logger.info("Added diarize column to user table")
except Exception as e:
app.logger.error(f"Error during database migration: {e}")
@@ -229,92 +232,54 @@ else:
transcription_api_key = os.environ.get("TRANSCRIPTION_API_KEY", "cant-be-empty")
transcription_base_url = os.environ.get("TRANSCRIPTION_BASE_URL", "https://openrouter.ai/api/v1")
+# ASR endpoint configuration
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ASR_BASE_URL = os.environ.get('ASR_BASE_URL')
+ASR_ENCODE = os.environ.get('ASR_ENCODE', 'true').lower() == 'true'
+ASR_TASK = os.environ.get('ASR_TASK', 'transcribe')
+ASR_DIARIZE = os.environ.get('ASR_DIARIZE', 'true').lower() == 'true'
+ASR_MIN_SPEAKERS = os.environ.get('ASR_MIN_SPEAKERS')
+ASR_MAX_SPEAKERS = os.environ.get('ASR_MAX_SPEAKERS')
+
app.logger.info(f"Using OpenRouter model for summaries: {TEXT_MODEL_NAME}")
app.logger.info(f"Using Whisper API at: {transcription_base_url}")
+if USE_ASR_ENDPOINT:
+ app.logger.info(f"ASR endpoint is enabled at: {ASR_BASE_URL}")
# --- Background Transcription & Summarization Task ---
-def transcribe_audio_task(app_context, recording_id, filepath, original_filename):
- """Runs the transcription and summarization in a background thread."""
- # output_language = os.environ.get("OUTPUT_LANGUAGE", None) # Get preferred output language - Now per user
-
- with app_context: # Need app context for db operations in thread
+def generate_summary_task(app_context, recording_id):
+ """Generates title and summary for a recording."""
+ with app_context:
recording = db.session.get(Recording, recording_id)
if not recording:
- app.logger.error(f"Error: Recording {recording_id} not found for transcription.")
+ app.logger.error(f"Error: Recording {recording_id} not found for summary generation.")
return
- try:
- app.logger.info(f"Starting transcription for recording {recording_id} ({original_filename})...")
- recording.status = 'PROCESSING'
+ if client is None:
+ app.logger.warning(f"Skipping summary for {recording_id}: OpenRouter client not configured.")
+ recording.summary = "[Summary skipped: OpenRouter client not configured]"
+ recording.status = 'COMPLETED'
db.session.commit()
+ return
- # --- Step 1: Transcription ---
- with open(filepath, 'rb') as audio_file:
- # NOTE: This still uses the hardcoded Whisper model.
- # If you want OpenRouter for transcription too, change the model here
- # and potentially adjust the API call if needed.
- # For now, assuming Whisper via a local compatible endpoint.
- # You might need a *separate* client for Whisper if it's at a different URL.
- # Example using the configured client (assuming it points to Whisper or OpenRouter handles it):
- transcription_client = OpenAI(
- api_key=transcription_api_key,
- base_url=transcription_base_url,
- http_client=http_client_no_proxy # Reuse the same client configuration
- )
- # Get the Whisper model name from environment variables
- whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
-
- user_transcription_language = None
- user_output_language = None
- if recording and recording.owner: # Check if recording and owner exist
- user_transcription_language = recording.owner.transcription_language
- user_output_language = recording.owner.output_language
-
- # Get the transcription language from user preferences or environment as fallback (optional)
- # For now, prioritize user setting. If not set by user, it will be None.
- # transcription_language = user_transcription_language or os.environ.get("TRANSCRIPTION_LANGUAGE", None)
- transcription_language = user_transcription_language # Prioritize user setting
-
- transcription_params = {
- "model": whisper_model,
- "file": audio_file
- }
+ recording.status = 'SUMMARIZING'
+ db.session.commit()
+ app.logger.info(f"Requesting title and summary from OpenRouter for recording {recording_id} using model {TEXT_MODEL_NAME}...")
- 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 not recording.transcription or len(recording.transcription.strip()) < 10:
+ app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping summarization.")
+ recording.status = 'COMPLETED'
+ recording.summary = "[Summary skipped due to short transcription]"
+ db.session.commit()
+ return
- transcript = transcription_client.audio.transcriptions.create(**transcription_params)
- recording.transcription = transcript.text
- app.logger.info(f"Transcription completed for recording {recording_id}. Text length: {len(recording.transcription)}")
- # Don't commit yet, proceed to summarization
+ user_summary_prompt = None
+ user_output_language = None
+ if recording.owner:
+ user_summary_prompt = recording.owner.summary_prompt
+ user_output_language = recording.owner.output_language
- # --- Step 2: Title & Summary Generation using OpenRouter ---
- if client is None: # Check if OpenRouter client initialized successfully earlier
- app.logger.warning(f"Skipping summary for {recording_id}: OpenRouter client not configured.")
- recording.summary = "[Summary skipped: OpenRouter client not configured]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return # Exit cleanly
-
- recording.status = 'SUMMARIZING' # Update status
- db.session.commit()
- app.logger.info(f"Requesting title and summary from OpenRouter for recording {recording_id} using model {TEXT_MODEL_NAME}...")
-
- if not recording.transcription or len(recording.transcription.strip()) < 10: # Basic check for valid transcript
- app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping summarization.")
- recording.status = 'COMPLETED' # Mark as completed even without summary
- recording.summary = "[Summary skipped due to short transcription]"
- db.session.commit()
- return # Exit the task cleanly
-
- user_summary_prompt = None
- if recording and recording.owner and recording.owner.summary_prompt:
- user_summary_prompt = recording.owner.summary_prompt
-
- default_summary_prompt = """Analyze the following audio transcription and generate a concise title and a brief summary.
+ default_summary_prompt = """Analyze the following audio transcription and generate a concise title and a brief summary.
Transcription:
\"\"\"
@@ -345,17 +310,11 @@ Example Format:
JSON Response:"""
- # Prepare the prompt for OpenRouter
- # Use user_output_language for prompts
- language_directive = f"Please provide the title and summary in {user_output_language}." if user_output_language else ""
+ language_directive = f"Please provide the title and summary in {user_output_language}." if user_output_language else ""
+
+ if user_summary_prompt:
+ prompt_text = f"""Analyze the following audio transcription and generate a concise title and a summary according to the following instructions.
- if user_summary_prompt:
- # If user has a custom prompt, we assume it includes placeholders for transcription and language
- # Or, we can define a structure for how their prompt should be used.
- # For now, let's assume their prompt is a complete replacement for the "summary" part.
- # We still need to provide the transcription.
- prompt_text = f"""Analyze the following audio transcription and generate a concise title and a summary according to the following instructions.
-
Transcription:
\"\"\"
{recording.transcription[:50000]}
@@ -369,143 +328,147 @@ For the "summary": {user_summary_prompt}.
{language_directive}
JSON Response:"""
- else:
- prompt_text = default_summary_prompt.format(transcription=recording.transcription[:30000], language_directive=language_directive)
-
- # Old prompt_text for reference, to be replaced by the logic above
- # prompt_text = f"""Analyze the following audio transcription and generate a concise title and a brief summary.
+ else:
+ prompt_text = default_summary_prompt.format(transcription=recording.transcription[:30000], language_directive=language_directive)
+
+ system_message_content = "You are an AI assistant that generates titles and summaries for meeting transcripts. Respond only with the requested JSON object."
+ if user_output_language:
+ system_message_content += f" Ensure your response (both title and summary) is in {user_output_language}."
- # The prompt guides the model towards the desired output
+ try:
+ completion = client.chat.completions.create(
+ model=TEXT_MODEL_NAME,
+ messages=[
+ {"role": "system", "content": system_message_content},
+ {"role": "user", "content": prompt_text}
+ ],
+ temperature=0.5,
+ max_tokens=int(os.environ.get("SUMMARY_MAX_TOKENS", "3000")),
+ response_format={"type": "json_object"}
+ )
+
+ response_content = completion.choices[0].message.content
+ json_match = re.search(r'```(?:json)?(.*?)```|(.+)', response_content, re.DOTALL)
+ sanitized_response = json_match.group(1) if json_match.group(1) else json_match.group(2)
+ sanitized_response = sanitized_response.strip()
+ summary_data = json.loads(sanitized_response)
- system_message_content = "You are an AI assistant that generates titles and summaries for meeting transcripts. Respond only with the requested JSON object."
- if user_output_language: # Use user_output_language here
- system_message_content += f" Ensure your response (both title and summary) is in {user_output_language}."
+ raw_title = summary_data.get("title")
+ raw_summary = summary_data.get("summary")
- try:
- # Log the request details for debugging
- app.logger.info(f"Making OpenRouter API request for recording {recording_id}")
- app.logger.debug(f"Model: {TEXT_MODEL_NAME}")
- app.logger.debug(f"System message length: {len(system_message_content)}")
- app.logger.debug(f"User prompt length: {len(prompt_text)}")
-
- # Use the OpenRouter client configured earlier
- completion = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
- messages=[
- {"role": "system", "content": system_message_content},
- {"role": "user", "content": prompt_text}
- ],
- temperature=0.5, # Adjust temperature as needed
- max_tokens=int(os.environ.get("SUMMARY_MAX_TOKENS", "3000")), # Adjust based on expected title+summary length
- response_format={"type": "json_object"} # Request JSON output
- )
-
- app.logger.info(f"OpenRouter API request completed for recording {recording_id}")
+ recording.title = raw_title.strip() if isinstance(raw_title, str) else "[Title not generated]"
+ recording.summary = raw_summary.strip() if isinstance(raw_summary, str) else "[Summary not generated]"
+ recording.status = 'COMPLETED'
+ app.logger.info(f"Title and summary processed successfully for recording {recording_id}.")
- response_content = completion.choices[0].message.content
- app.logger.debug(f"Raw OpenRouter response for {recording_id}: {response_content}")
-
- try:
- response_content = completion.choices[0].message.content
- app.logger.debug(f"Raw OpenRouter response for {recording_id}: {response_content}")
-
- # Check if response is empty or None
- if not response_content or response_content.strip() == "":
- app.logger.error(f"Empty response from OpenRouter for {recording_id}")
- recording.summary = "[AI summary generation failed: Empty response from API]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return
+ except Exception as summary_e:
+ app.logger.error(f"Error calling OpenRouter API for summary ({recording_id}): {str(summary_e)}")
+ recording.summary = f"[AI summary generation failed: API Error ({str(summary_e)})]"
+ recording.status = 'COMPLETED'
- # Use regex to extract JSON content from potential markdown code blocks
- # This looks for content between markdown code blocks or just takes the whole content
- json_match = re.search(r'```(?:json)?(.*?)```|(.+)', response_content, re.DOTALL)
-
- if json_match:
- # Use the first group that matched (either between ``` or the whole content)
- sanitized_response = json_match.group(1) if json_match.group(1) else json_match.group(2)
- sanitized_response = sanitized_response.strip()
- else:
- sanitized_response = response_content.strip()
-
- # Additional check for empty sanitized response
- if not sanitized_response or sanitized_response.strip() in ["{}", ""]:
- app.logger.error(f"Empty or invalid JSON response from OpenRouter for {recording_id}: '{sanitized_response}'")
- recording.summary = "[AI summary generation failed: Invalid JSON response]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return
-
- summary_data = json.loads(sanitized_response) # Use sanitized_response here
-
- # Check if the parsed JSON is empty or doesn't contain expected keys
- if not summary_data or (not summary_data.get("title") and not summary_data.get("summary")):
- app.logger.error(f"OpenRouter returned empty or invalid JSON structure for {recording_id}: {summary_data}")
- recording.summary = "[AI summary generation failed: Empty response structure]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return
-
- raw_title = summary_data.get("title")
- raw_summary = summary_data.get("summary")
+ db.session.commit()
- # Process title
- if isinstance(raw_title, str):
- processed_title = raw_title.strip()
- elif raw_title is None:
- processed_title = "[Title not generated]"
- app.logger.warning(f"Title was missing in OpenRouter response for {recording_id}.")
- else: # It's some other type, e.g. dict
- processed_title = "[Title generation error: Unexpected format]"
- app.logger.warning(f"Title had unexpected format for {recording_id}: {type(raw_title)}. Content: {raw_title}")
+def transcribe_audio_asr(app_context, recording_id, filepath, original_filename, language=None, diarize=False, min_speakers=None, max_speakers=None):
+ """Transcribes audio using the ASR webservice."""
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ app.logger.error(f"Error: Recording {recording_id} not found for ASR transcription.")
+ return
- # Process summary
- if isinstance(raw_summary, str):
- processed_summary = raw_summary.strip()
- elif isinstance(raw_summary, dict):
- # If summary is a dict (structured), convert to formatted JSON string
- processed_summary = json.dumps(raw_summary, indent=2)
- app.logger.info(f"Generated summary for {recording_id} was a dictionary, converted to JSON string.")
- elif raw_summary is None:
- processed_summary = "[Summary not generated]"
- app.logger.warning(f"Summary was missing in OpenRouter response for {recording_id}.")
- else: # It's some other type
- processed_summary = "[Summary generation error: Unexpected format]"
- app.logger.warning(f"Summary had unexpected format for {recording_id}: {type(raw_summary)}. Content: {raw_summary}")
+ try:
+ app.logger.info(f"Starting ASR transcription for recording {recording_id}...")
+ recording.status = 'PROCESSING'
+ db.session.commit()
- if raw_title is not None and raw_summary is not None: # Check if keys were present
- recording.title = processed_title
- recording.summary = processed_summary
- recording.status = 'COMPLETED'
- app.logger.info(f"Title and summary processed successfully for recording {recording_id}.")
- else:
- # Handle cases where one or both keys might be missing, even if not strictly an error above
- if raw_title is None:
- recording.title = recording.title or "[Title not generated]" # Keep existing if any
- else:
- recording.title = processed_title
+ with open(filepath, 'rb') as audio_file:
+ url = f"{ASR_BASE_URL}/asr"
+ params = {
+ 'encode': ASR_ENCODE,
+ 'task': ASR_TASK,
+ 'output': 'txt'
+ }
+ if language:
+ params['language'] = language
+ if diarize:
+ params['diarize'] = diarize
+ if min_speakers:
+ params['min_speakers'] = min_speakers
+ if max_speakers:
+ params['max_speakers'] = max_speakers
+
+ files = {'audio_file': (original_filename, audio_file, 'audio/mpeg')}
+
+ with httpx.Client() as client:
+ response = client.post(url, params=params, files=files, timeout=None)
+ response.raise_for_status()
+ recording.transcription = response.text
+
+ app.logger.info(f"ASR transcription completed for recording {recording_id}.")
+ generate_summary_task(app_context, recording_id)
- if raw_summary is None:
- recording.summary = "[AI summary generation failed: Missing summary key]"
- else:
- recording.summary = processed_summary
-
- app.logger.warning(f"OpenRouter response for {recording_id} might have lacked 'title' or 'summary'. Title: {raw_title is not None}, Summary: {raw_summary is not None}. Response: {sanitized_response}")
- recording.status = 'COMPLETED' # Still completed, but summary might be partial/failed
+ except Exception as e:
+ db.session.rollback()
+ app.logger.error(f"ASR processing FAILED for recording {recording_id}: {str(e)}", exc_info=True)
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ recording.status = 'FAILED'
+ recording.transcription = f"ASR processing failed: {str(e)}"
+ db.session.commit()
- except json.JSONDecodeError as json_e:
- app.logger.error(f"Failed to parse JSON response from OpenRouter for {recording_id}: {json_e}. Response: {sanitized_response}")
- recording.summary = f"[AI summary generation failed: Invalid JSON response ({json_e})]"
- recording.status = 'COMPLETED' # Mark as completed, summary failed
+def transcribe_audio_task(app_context, recording_id, filepath, original_filename):
+ """Runs the transcription and summarization in a background thread."""
+ if USE_ASR_ENDPOINT:
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ user_diarize = recording.owner.diarize if recording.owner else False
+ user_transcription_language = recording.owner.transcription_language if recording.owner else None
+ transcribe_audio_asr(app_context, recording_id, filepath, original_filename, language=user_transcription_language, diarize=user_diarize)
+ return
+
+ with app_context: # Need app context for db operations in thread
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ app.logger.error(f"Error: Recording {recording_id} not found for transcription.")
+ return
+
+ try:
+ app.logger.info(f"Starting transcription for recording {recording_id} ({original_filename})...")
+ recording.status = 'PROCESSING'
+ db.session.commit()
+
+ # --- Step 1: Transcription ---
+ with open(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
+ user_output_language = None
+ if recording and recording.owner:
+ user_transcription_language = recording.owner.transcription_language
+ user_output_language = recording.owner.output_language
+
+ transcription_language = user_transcription_language
- except Exception as summary_e:
- app.logger.error(f"Error calling OpenRouter API for summary ({recording_id}): {str(summary_e)}")
- # Keep transcription, but mark summary failed. Don't change status from SUMMARIZING yet.
- recording.summary = f"[AI summary generation failed: API Error ({str(summary_e)})]"
- recording.status = 'COMPLETED' # Even if summary fails, transcription worked.
+ 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.")
- db.session.commit() # Final commit for this step
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ recording.transcription = transcript.text
+ app.logger.info(f"Transcription completed for recording {recording_id}. Text length: {len(recording.transcription)}")
+ generate_summary_task(app_context, recording_id)
except Exception as e:
db.session.rollback() # Rollback if any step failed critically
@@ -524,6 +487,111 @@ JSON Response:"""
db.session.commit()
[email protected]('/recording/<int:recording_id>/update_speakers', methods=['POST'])
+@login_required
+def update_speakers(recording_id):
+ """Updates speaker labels in a transcription with provided names."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if recording.user_id and recording.user_id != current_user.id:
+ return jsonify({'error': 'You do not have permission to edit this recording'}), 403
+
+ data = request.json
+ speaker_map = data.get('speaker_map')
+ regenerate_summary = data.get('regenerate_summary', False)
+
+ if not speaker_map:
+ return jsonify({'error': 'No speaker map provided'}), 400
+
+ transcription = recording.transcription
+ new_participants = []
+
+ for speaker_label, new_name_info in speaker_map.items():
+ new_name = new_name_info['name']
+ if new_name_info.get('isMe'):
+ new_name = current_user.name or 'Me'
+
+ if new_name:
+ # Regex to handle variations like [SPEAKER_00], [ SPEAKER_00 ], etc.
+ transcription = re.sub(r'\[\s*' + re.escape(speaker_label) + r'\s*\]', f'[{new_name}]', transcription)
+ if new_name not in new_participants:
+ new_participants.append(new_name)
+
+ recording.transcription = transcription
+ if new_participants:
+ recording.participants = ', '.join(new_participants)
+
+ db.session.commit()
+
+ if regenerate_summary:
+ app.logger.info(f"Regenerating summary for recording {recording_id} after speaker update.")
+ thread = threading.Thread(
+ target=generate_summary_task,
+ args=(app.app_context(), recording.id)
+ )
+ thread.start()
+
+ return jsonify({
+ 'success': True,
+ 'message': 'Speakers updated successfully.',
+ 'recording': recording.to_dict()
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ app.logger.error(f"Error updating speakers for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': str(e)}), 500
+
[email protected]('/recording/<int:recording_id>/reprocess_asr', methods=['POST'])
+@login_required
+def reprocess_asr(recording_id):
+ """Reprocess transcription for a given recording using ASR."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if recording.user_id and recording.user_id != current_user.id:
+ return jsonify({'error': 'You do not have permission to reprocess this recording'}), 403
+
+ if not recording.audio_path or not os.path.exists(recording.audio_path):
+ return jsonify({'error': 'Audio file not found for reprocessing'}), 404
+
+ if recording.status in ['PROCESSING', 'SUMMARIZING']:
+ return jsonify({'error': 'Recording is already being processed'}), 400
+
+ data = request.json
+ language = data.get('language')
+ min_speakers = data.get('min_speakers')
+ max_speakers = data.get('max_speakers')
+
+ recording.transcription = None
+ recording.summary = None
+ recording.status = 'PROCESSING'
+ db.session.commit()
+
+ app.logger.info(f"Starting ASR reprocessing for recording {recording_id}")
+
+ thread = threading.Thread(
+ target=transcribe_audio_asr,
+ args=(app.app_context(), recording.id, recording.audio_path, recording.original_filename or f"Recording {recording.id}", language, True, min_speakers, max_speakers)
+ )
+ thread.start()
+
+ return jsonify({
+ 'success': True,
+ 'message': 'ASR reprocessing started',
+ 'recording': recording.to_dict()
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ app.logger.error(f"Error reprocessing ASR for recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
# --- Chat with Transcription ---
@app.route('/chat', methods=['POST'])
@login_required
@@ -975,6 +1043,7 @@ def account():
user_name = request.form.get('user_name')
user_job_title = request.form.get('user_job_title')
user_company = request.form.get('user_company')
+ diarize = 'diarize' in request.form
current_user.transcription_language = transcription_lang if transcription_lang else None
current_user.output_language = output_lang if output_lang else None
@@ -982,6 +1051,7 @@ def account():
current_user.name = user_name if user_name else None
current_user.job_title = user_job_title if user_job_title else None
current_user.company = user_company if user_company else None
+ current_user.diarize = diarize
db.session.commit()
flash('Account details updated successfully!', 'success')
diff --git a/static/js/app.js b/static/js/app.js
index 1e9de772..96c91844 100644
--- a/static/js/app.js
+++ b/static/js/app.js
@@ -38,10 +38,19 @@ document.addEventListener('DOMContentLoaded', () => {
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const showReprocessModal = ref(false);
+ const showAsrReprocessModal = ref(false);
+ const showSpeakerModal = ref(false);
const editingRecording = ref(null); // Holds a *copy* for the modal
const recordingToDelete = ref(null);
const reprocessType = ref(null); // 'transcription' or 'summary'
const reprocessRecording = ref(null);
+ const asrReprocessOptions = reactive({
+ language: '',
+ min_speakers: null,
+ max_speakers: null
+ });
+ const speakerMap = ref({});
+ const regenerateSummaryAfterSpeakerUpdate = ref(true);
// const autoSaveTimeout = ref(null); // Autosave not implemented for modal
const isLoadingRecordings = ref(true);
const globalError = ref(null);
@@ -124,6 +133,19 @@ document.addEventListener('DOMContentLoaded', () => {
return windowWidth.value < 1024; // Tailwind's lg breakpoint
});
+ const identifiedSpeakers = computed(() => {
+ if (!selectedRecording.value?.transcription) {
+ return [];
+ }
+ const speakerRegex = /\[(SPEAKER_\d+)\]/g;
+ const speakers = new Set();
+ let match;
+ while ((match = speakerRegex.exec(selectedRecording.value.transcription)) !== null) {
+ speakers.add(match[1]);
+ }
+ return Array.from(speakers);
+ });
+
// --- Methods ---
const setGlobalError = (message, duration = 7000) => {
@@ -978,6 +1000,8 @@ document.addEventListener('DOMContentLoaded', () => {
await performReprocessTranscription(recordingId);
} else if (type === 'summary') {
await performReprocessSummary(recordingId);
+ } else if (type === 'asr') {
+ await performAsrReprocess(recordingId);
}
};
@@ -990,6 +1014,75 @@ document.addEventListener('DOMContentLoaded', () => {
const recording = recordings.value.find(r => r.id === recordingId) || selectedRecording.value;
confirmReprocess('summary', recording);
};
+
+ const confirmAsrReprocess = (recording) => {
+ reprocessRecording.value = recording;
+ asrReprocessOptions.language = recording.owner?.transcription_language || '';
+ asrReprocessOptions.min_speakers = null;
+ asrReprocessOptions.max_speakers = null;
+ showAsrReprocessModal.value = true;
+ };
+
+ const cancelAsrReprocess = () => {
+ showAsrReprocessModal.value = false;
+ reprocessRecording.value = null;
+ };
+
+ const executeAsrReprocess = async () => {
+ if (!reprocessRecording.value) return;
+ const recordingId = reprocessRecording.value.id;
+
+ await performAsrReprocess(recordingId, asrReprocessOptions.language, asrReprocessOptions.min_speakers, asrReprocessOptions.max_speakers);
+ cancelAsrReprocess();
+ };
+
+ const openSpeakerModal = () => {
+ speakerMap.value = identifiedSpeakers.value.reduce((acc, speaker) => {
+ acc[speaker] = { name: '', isMe: false };
+ return acc;
+ }, {});
+ showSpeakerModal.value = true;
+ };
+
+ const closeSpeakerModal = () => {
+ showSpeakerModal.value = false;
+ };
+
+ const saveSpeakerNames = async () => {
+ if (!selectedRecording.value) return;
+
+ try {
+ const response = await fetch(`/recording/${selectedRecording.value.id}/update_speakers`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ speaker_map: speakerMap.value,
+ regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update speakers');
+
+ // Update the recording in the UI
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index] = data.recording;
+ }
+ selectedRecording.value = data.recording;
+
+ showToast('Speaker names updated successfully!', 'fa-check-circle');
+ closeSpeakerModal();
+
+ if (regenerateSummaryAfterSpeakerUpdate.value) {
+ startReprocessingPoll(selectedRecording.value.id);
+ }
+
+ } catch (error) {
+ console.error('Save Speaker Names Error:', error);
+ setGlobalError(`Failed to save speaker names: ${error.message}`);
+ }
+ };
const performReprocessTranscription = async (recordingId) => {
if (!recordingId) {
@@ -1127,6 +1220,44 @@ document.addEventListener('DOMContentLoaded', () => {
}
};
+ const performAsrReprocess = async (recordingId, language, minSpeakers, maxSpeakers) => {
+ if (!recordingId) {
+ setGlobalError('No recording ID provided for ASR reprocessing.');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/recording/${recordingId}/reprocess_asr`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ language: language,
+ min_speakers: minSpeakers,
+ max_speakers: maxSpeakers
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to start ASR reprocessing');
+
+ const index = recordings.value.findIndex(r => r.id === recordingId);
+ if (index !== -1) {
+ recordings.value[index] = data.recording;
+ }
+
+ if (selectedRecording.value?.id === recordingId) {
+ selectedRecording.value = data.recording;
+ }
+
+ showToast('ASR reprocessing started', 'fa-sync-alt');
+ startReprocessingPoll(recordingId);
+
+ } catch (error) {
+ console.error('ASR Reprocess Error:', error);
+ setGlobalError(`Failed to start ASR reprocessing: ${error.message}`);
+ }
+ };
+
// --- Chat functionality ---
// Resizable panels state
const transcriptionFlex = ref(2);
@@ -1447,6 +1578,20 @@ document.addEventListener('DOMContentLoaded', () => {
confirmReprocess,
cancelReprocess,
executeReprocess,
+ // ASR Reprocessing
+ showAsrReprocessModal,
+ asrReprocessOptions,
+ confirmAsrReprocess,
+ cancelAsrReprocess,
+ executeAsrReprocess,
+ // Speaker Identification
+ showSpeakerModal,
+ speakerMap,
+ regenerateSummaryAfterSpeakerUpdate,
+ identifiedSpeakers,
+ openSpeakerModal,
+ closeSpeakerModal,
+ saveSpeakerNames,
}
},
delimiters: ['${', '}'] // Keep Vue delimiters distinct from Flask's Jinja
diff --git a/templates/account.html b/templates/account.html
index 7988a5c8..87da1695 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -189,6 +189,13 @@
<textarea name="summary_prompt" id="summary_prompt" rows="6" placeholder="Describe how you want your summaries structured. Leave blank to use the default prompt." 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)]">{{ current_user.summary_prompt or default_summary_prompt_text }}</textarea>
<p class="text-xs text-[var(--text-light)] mt-1">This prompt will be used to generate the summary for your transcriptions. You can use placeholders like {{transcription}} and {{language_directive}} if needed, though the system will try to intelligently place the transcription content.</p>
</div>
+ <div>
+ <label for="diarize" class="flex items-center text-sm font-medium text-[var(--text-muted)]">
+ <input type="checkbox" name="diarize" id="diarize" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" {% if current_user.diarize %}checked{% endif %}>
+ <span class="ml-2">Enable Diarization</span>
+ </label>
+ <p class="text-xs text-[var(--text-light)] mt-1">When using the ASR endpoint, this will enable speaker diarization.</p>
+ </div>
</div>
</div>
diff --git a/templates/index.html b/templates/index.html
index 5be350d0..3ec49e19 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -175,6 +175,60 @@
</button>
</div>
</div>
+ </div>
+ <!-- Speaker Identification Modal -->
+ <div v-if="showSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-lg">
+ <div class="p-5 border-b border-[var(--border-primary)]">
+ <h3 class="text-xl font-bold text-[var(--text-primary)]">Identify Speakers</h3>
+ </div>
+ <div class="p-6 space-y-4 max-h-[60vh] overflow-y-auto custom-scrollbar">
+ <div v-for="(speaker, index) in identifiedSpeakers" :key="speaker" class="flex items-center space-x-3">
+ <span class="font-mono text-sm text-[var(--text-muted)] w-28">${ speaker }</span>
+ <input type="text" v-model="speakerMap[speaker].name" class="flex-grow 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="'Enter name for ' + speaker">
+ <label class="flex items-center text-sm text-[var(--text-muted)]">
+ <input type="checkbox" v-model="speakerMap[speaker].isMe" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2">Me</span>
+ </label>
+ </div>
+ </div>
+ <div class="p-6 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)]">
+ <label class="flex items-center text-sm text-[var(--text-muted)]">
+ <input type="checkbox" v-model="regenerateSummaryAfterSpeakerUpdate" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2">Regenerate summary after updating names</span>
+ </label>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)]">
+ <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">Cancel</button>
+ <button @click="saveSpeakerNames" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save Names</button>
+ </div>
+ </div>
+ </div>
+ <!-- ASR Reprocess Modal -->
+ <div v-if="showAsrReprocessModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md">
+ <div class="p-5 border-b border-[var(--border-primary)]">
+ <h3 class="text-xl font-bold text-[var(--text-primary)]">ASR Reprocess Options</h3>
+ </div>
+ <div class="p-6 space-y-4">
+ <div>
+ <label for="asr-language" class="block text-sm font-medium text-[var(--text-muted)]">Language</label>
+ <input type="text" id="asr-language" 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">
+ </div>
+ <div>
+ <label for="asr-min-speakers" class="block text-sm font-medium text-[var(--text-muted)]">Min Speakers</label>
+ <input type="number" id="asr-min-speakers" 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="Optional">
+ </div>
+ <div>
+ <label for="asr-max-speakers" class="block text-sm font-medium text-[var(--text-muted)]">Max Speakers</label>
+ <input type="number" id="asr-max-speakers" 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="Optional">
+ </div>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)]">
+ <button @click="cancelAsrReprocess" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">Cancel</button>
+ <button @click="executeAsrReprocess" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Reprocess</button>
+ </div>
+ </div>
</div>
</div>
{% else %}
@@ -434,6 +488,12 @@
title="Reprocess transcription">
<i class="fas fa-sync-alt"></i>
</button>
+ <button @click="confirmAsrReprocess(selectedRecording)"
+ v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-accent)] p-1 rounded"
+ title="Reprocess with ASR">
+ <i class="fas fa-cogs"></i>
+ </button>
</div>
</div>
<div class="transcription-box custom-scrollbar relative">
@@ -491,6 +551,12 @@
title="Reprocess summary">
<i class="fas fa-sync-alt"></i>
</button>
+ <button @click="openSpeakerModal"
+ v-if="identifiedSpeakers.length > 0"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-accent)] p-1 rounded"
+ title="Identify Speakers">
+ <i class="fas fa-user-tag"></i>
+ </button>
</template>
<!-- Notes buttons - shown when notes tab is active -->
<template v-if="selectedTab === 'notes'">