Skip to content

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

Python

Add ASR retry on 500 errors, admin default prompts, custom user prompts, and improved error handling

Murtaza Nasir2636f91ecd8d
diff --git a/DEPLOYMENT_GUIDE.md b/DEPLOYMENT_GUIDE.md
index dbb7994e..15c7fdc9 100644
--- a/DEPLOYMENT_GUIDE.md
+++ b/DEPLOYMENT_GUIDE.md
@@ -182,6 +182,8 @@ This method uses the `/asr` endpoint and enables speaker identification and diar
#### Option 2.1: Single Docker Compose File
+> **⚠️ IMPORTANT NETWORKING NOTE:** When running both containers in the same `docker-compose.yml`, containers communicate using **service names** as hostnames, NOT external IPs or localhost. Use `http://whisper-asr:9000` (the service name and internal port), NOT `http://localhost:6002` or `http://192.168.x.x:6002`.
+
**docker-compose.yml:**
```yaml
services:
@@ -190,7 +192,7 @@ services:
image: onerahmet/openai-whisper-asr-webservice:latest-gpu
container_name: whisper-asr-webservice
ports:
- - "9000:9000"
+ - "9000:9000" # Maps host port 9000 to container port 9000
environment:
- ASR_MODEL=distil-large-v3
- ASR_COMPUTE_TYPE=int8
@@ -238,6 +240,9 @@ TEXT_MODEL_NAME=openai/gpt-4o-mini
# --- Transcription Service (ASR Endpoint) ---
USE_ASR_ENDPOINT=true
+# IMPORTANT: Use container service name, not IP or localhost!
+# Correct: http://whisper-asr:9000 (service name from docker-compose.yml)
+# Wrong: http://localhost:9000, http://127.0.0.1:9000, http://192.168.x.x:9000
ASR_BASE_URL=http://whisper-asr:9000
# Speaker diarization is automatically enabled with ASR
# Optional overrides (defaults shown):
diff --git a/app.py b/app.py
index 761f9221..068632e7 100644
--- a/app.py
+++ b/app.py
@@ -422,6 +422,135 @@ def format_transcription_for_llm(transcription_text):
pass
return transcription_text
+def clean_llm_response(text):
+ """
+ Clean LLM responses by removing thinking tags and excessive whitespace.
+ This handles responses from reasoning models that include <think> tags.
+ """
+ if not text:
+ return ""
+
+ # Remove thinking tags and their content
+ # Handle both <think> and <thinking> tags with various closing formats
+ cleaned = re.sub(r'<think(?:ing)?>.*?</think(?:ing)?>', '', text, flags=re.DOTALL | re.IGNORECASE)
+
+ # Also handle unclosed thinking tags (in case the model doesn't close them)
+ cleaned = re.sub(r'<think(?:ing)?>.*$', '', cleaned, flags=re.DOTALL | re.IGNORECASE)
+
+ # Remove any remaining XML-like tags that might be related to thinking
+ # but preserve markdown formatting
+ cleaned = re.sub(r'<(?!/?(?:code|pre|blockquote|p|br|hr|ul|ol|li|h[1-6]|em|strong|b|i|a|img)(?:\s|>|/))[^>]+>', '', cleaned)
+
+ # Clean up excessive whitespace while preserving intentional formatting
+ # Remove leading/trailing whitespace from each line
+ lines = cleaned.split('\n')
+ cleaned_lines = []
+ for line in lines:
+ # Preserve lines that are part of code blocks or lists
+ if line.strip() or (len(cleaned_lines) > 0 and cleaned_lines[-1].strip().startswith(('```', '-', '*', '1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.'))):
+ cleaned_lines.append(line.rstrip())
+
+ # Join lines and remove multiple consecutive blank lines
+ cleaned = '\n'.join(cleaned_lines)
+ cleaned = re.sub(r'\n{3,}', '\n\n', cleaned)
+
+ # Final strip to remove leading/trailing whitespace
+ return cleaned.strip()
+
+def extract_thinking_content(text):
+ """
+ Extract thinking content from LLM responses.
+ Returns a tuple of (thinking_content, main_content).
+ """
+ if not text:
+ return ("", "")
+
+ # Find all thinking tags and their content
+ thinking_pattern = r'<think(?:ing)?>.*?</think(?:ing)?>'
+ thinking_matches = re.findall(thinking_pattern, text, flags=re.DOTALL | re.IGNORECASE)
+
+ # Extract the content from within the tags
+ thinking_content = ""
+ for match in thinking_matches:
+ # Remove the opening and closing tags
+ content = re.sub(r'^<think(?:ing)?>', '', match, flags=re.IGNORECASE)
+ content = re.sub(r'</think(?:ing)?>$', '', content, flags=re.IGNORECASE)
+ if thinking_content:
+ thinking_content += "\n\n"
+ thinking_content += content.strip()
+
+ # Get the main content by removing thinking tags
+ main_content = clean_llm_response(text)
+
+ return (thinking_content, main_content)
+
+def process_streaming_with_thinking(stream):
+ """
+ Generator that processes a streaming response and separates thinking content.
+ Yields SSE-formatted data with 'delta' for regular content and 'thinking' for thinking content.
+ """
+ content_buffer = ""
+ in_thinking = False
+ thinking_buffer = ""
+
+ for chunk in stream:
+ content = chunk.choices[0].delta.content
+ if content:
+ content_buffer += content
+
+ # Process the buffer to detect and handle thinking tags
+ while True:
+ if not in_thinking:
+ # Look for opening thinking tag
+ think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_start:
+ # Send any content before the thinking tag
+ before_thinking = content_buffer[:think_start.start()]
+ if before_thinking:
+ yield f"data: {json.dumps({'delta': before_thinking})}\n\n"
+
+ # Start capturing thinking content
+ in_thinking = True
+ content_buffer = content_buffer[think_start.end():]
+ thinking_buffer = ""
+ else:
+ # No thinking tag found, send accumulated content
+ if content_buffer:
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
+ content_buffer = ""
+ break
+ else:
+ # We're inside a thinking tag, look for closing tag
+ think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_end:
+ # Capture thinking content up to the closing tag
+ thinking_buffer += content_buffer[:think_end.start()]
+
+ # Send the thinking content as a special type
+ if thinking_buffer.strip():
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+
+ # Continue processing after the closing tag
+ in_thinking = False
+ content_buffer = content_buffer[think_end.end():]
+ thinking_buffer = ""
+ else:
+ # Still inside thinking tag, accumulate content
+ thinking_buffer += content_buffer
+ content_buffer = ""
+ break
+
+ # Handle any remaining content
+ if in_thinking and thinking_buffer:
+ # Unclosed thinking tag - send as thinking content
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+ elif content_buffer:
+ # Regular content
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
+
+ # Signal the end of the stream
+ yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
+
app = Flask(__name__)
# Use environment variables or default paths for Docker compatibility
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:////data/instance/transcriptions.db')
@@ -1459,6 +1588,28 @@ with app.app_context():
)
app.logger.info("Initialized default max_file_size_mb setting")
+ if not SystemSetting.query.filter_by(key='asr_timeout_seconds').first():
+ SystemSetting.set_setting(
+ key='asr_timeout_seconds',
+ value='1800',
+ description='Maximum time in seconds to wait for ASR transcription to complete. Default is 1800 seconds (30 minutes).',
+ setting_type='integer'
+ )
+ app.logger.info("Initialized default asr_timeout_seconds setting")
+
+ if not SystemSetting.query.filter_by(key='admin_default_summary_prompt').first():
+ default_prompt = """Generate a comprehensive summary that includes the following sections:
+- **Key Issues Discussed**: A bulleted list of the main topics
+- **Key Decisions Made**: A bulleted list of any decisions reached
+- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
+ SystemSetting.set_setting(
+ key='admin_default_summary_prompt',
+ value=default_prompt,
+ description='Default summarization prompt used when users have not set their own prompt. This serves as the base prompt for all users.',
+ setting_type='string'
+ )
+ app.logger.info("Initialized admin_default_summary_prompt setting")
+
# Process existing recordings for inquire mode (chunk and embed them)
# Only run if inquire mode is enabled
if ENABLE_INQUIRE_MODE:
@@ -1771,7 +1922,7 @@ Title:"""
raw_response = line
break
- title = raw_response.strip() if raw_response else ""
+ title = clean_llm_response(raw_response) if raw_response else ""
if title:
recording.title = title
@@ -1882,7 +2033,7 @@ def generate_summary_only_task(app_context, recording_id):
system_message_content += f" Ensure your response is in {user_output_language}."
# Add summarization instructions to system message
- # Priority order: tag custom prompt > user summary prompt > default prompt
+ # Priority order: tag custom prompt > user summary prompt > admin default prompt > hardcoded fallback
if tag_custom_prompt:
app.logger.info(f"Using tag custom prompt for recording {recording_id}")
system_message_content += f"\n\nSummarization Instructions:\n{tag_custom_prompt}"
@@ -1890,12 +2041,19 @@ def generate_summary_only_task(app_context, recording_id):
app.logger.info(f"Using user custom prompt for recording {recording_id}")
system_message_content += f"\n\nSummarization Instructions:\n{user_summary_prompt}"
else:
- # Default summary instructions
- default_instructions = """Generate a comprehensive summary that includes the following sections:
+ # Get admin default prompt from system settings
+ admin_default_prompt = SystemSetting.get_setting('admin_default_summary_prompt', None)
+ if admin_default_prompt:
+ app.logger.info(f"Using admin default prompt for recording {recording_id}")
+ system_message_content += f"\n\nSummarization Instructions:\n{admin_default_prompt}"
+ else:
+ # Fallback to hardcoded default if admin hasn't set one
+ default_instructions = """Generate a comprehensive summary that includes the following sections:
- **Key Issues Discussed**: A bulleted list of the main topics
- **Key Decisions Made**: A bulleted list of any decisions reached
- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
- system_message_content += f"\n\nSummarization Instructions:\n{default_instructions}"
+ app.logger.info(f"Using hardcoded default prompt for recording {recording_id}")
+ system_message_content += f"\n\nSummarization Instructions:\n{default_instructions}"
# Build user prompt with context information
current_date = datetime.now().strftime("%B %d, %Y")
@@ -1954,7 +2112,7 @@ Please analyze the above transcription and generate a summary following the prov
raw_response = completion.choices[0].message.content
app.logger.info(f"Raw LLM response for recording {recording_id}: '{raw_response}'")
- summary = raw_response.strip() if raw_response else ""
+ summary = clean_llm_response(raw_response) if raw_response else ""
app.logger.info(f"Processed summary length for recording {recording_id}: {len(summary)} characters")
if summary:
@@ -2088,108 +2246,168 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,
db.session.commit()
return
- with open(actual_filepath, 'rb') as audio_file:
- url = f"{ASR_BASE_URL}/asr"
- params = {
- 'encode': True,
- 'task': 'transcribe',
- 'output': 'json'
- }
- 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
-
- content_type = actual_content_type
- app.logger.info(f"Using MIME type {content_type} for ASR upload.")
- files = {'audio_file': (actual_filename, audio_file, content_type)}
-
- with httpx.Client() as client:
- # Set reasonable timeout to prevent hanging (30 minutes max)
- timeout = httpx.Timeout(None, connect=30.0, read=1800.0, write=30.0, pool=30.0)
- app.logger.info(f"Sending ASR request to {url} with params: {params}")
- response = client.post(url, params=params, files=files, timeout=timeout)
- app.logger.info(f"ASR request completed with status: {response.status_code}")
- response.raise_for_status()
-
- # Parse the JSON response from ASR
- asr_response_data = response.json()
-
- # Debug logging for ASR response
- app.logger.info(f"ASR response keys: {list(asr_response_data.keys())}")
-
- # Log the complete raw JSON response (truncated for readability)
- import json as json_module
- raw_json_str = json_module.dumps(asr_response_data, indent=2)
- if len(raw_json_str) > 5000:
- app.logger.info(f"Raw ASR response (first 5000 chars): {raw_json_str[:5000]}...")
- else:
- app.logger.info(f"Raw ASR response: {raw_json_str}")
+ # Keep track of whether we've already tried WAV conversion
+ wav_conversion_attempted = False
+ wav_converted_filepath = None
+
+ # Retry loop for handling 500 errors with WAV conversion
+ max_attempts = 2
+ for attempt in range(max_attempts):
+ try:
+ # Use converted WAV if available from previous attempt
+ current_filepath = wav_converted_filepath if wav_converted_filepath else actual_filepath
+ current_content_type = 'audio/x-wav' if wav_converted_filepath else actual_content_type
+ current_filename = os.path.basename(current_filepath)
- if 'segments' in asr_response_data:
- app.logger.info(f"Number of segments: {len(asr_response_data['segments'])}")
-
- # Collect all unique speakers from the response
- all_speakers = set()
- segments_with_speakers = 0
- segments_without_speakers = 0
-
- for segment in asr_response_data['segments']:
- if 'speaker' in segment and segment['speaker'] is not None:
- all_speakers.add(segment['speaker'])
- segments_with_speakers += 1
- else:
- segments_without_speakers += 1
-
- app.logger.info(f"Unique speakers found in raw response: {sorted(list(all_speakers))}")
- app.logger.info(f"Segments with speakers: {segments_with_speakers}, without speakers: {segments_without_speakers}")
+ with open(current_filepath, 'rb') as audio_file:
+ url = f"{ASR_BASE_URL}/asr"
+ params = {
+ 'encode': True,
+ 'task': 'transcribe',
+ 'output': 'json'
+ }
+ 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
+
+ content_type = current_content_type
+ app.logger.info(f"Using MIME type {content_type} for ASR upload.")
+ files = {'audio_file': (current_filename, audio_file, content_type)}
- # Log first few segments for debugging
- for i, segment in enumerate(asr_response_data['segments'][:5]):
- segment_keys = list(segment.keys())
- app.logger.info(f"Segment {i} keys: {segment_keys}")
- app.logger.info(f"Segment {i}: speaker='{segment.get('speaker')}', text='{segment.get('text', '')[:50]}...'")
+ with httpx.Client() as client:
+ # Get configurable ASR timeout from database (default 30 minutes)
+ asr_timeout_seconds = SystemSetting.get_setting('asr_timeout_seconds', 1800)
+ timeout = httpx.Timeout(None, connect=30.0, read=float(asr_timeout_seconds), write=30.0, pool=30.0)
+ app.logger.info(f"Sending ASR request to {url} with params: {params} (timeout: {asr_timeout_seconds}s)")
+ response = client.post(url, params=params, files=files, timeout=timeout)
+ app.logger.info(f"ASR request completed with status: {response.status_code}")
+ response.raise_for_status()
+
+ # Parse the JSON response from ASR (moved here so it's accessible)
+ asr_response_data = response.json()
- # Simplify the JSON data
- simplified_segments = []
- if 'segments' in asr_response_data and isinstance(asr_response_data['segments'], list):
- last_known_speaker = None
+ # If we reach here, the request was successful
+ break
+
+ except httpx.HTTPStatusError as e:
+ # Check if it's a 500 error and we haven't tried WAV conversion yet
+ if e.response.status_code == 500 and attempt == 0 and not wav_conversion_attempted:
+ app.logger.warning(f"ASR returned 500 error for recording {recording_id}, attempting WAV conversion and retry...")
- for i, segment in enumerate(asr_response_data['segments']):
- speaker = segment.get('speaker')
- text = segment.get('text', '').strip()
-
- # If segment doesn't have a speaker, use the previous segment's speaker
- if speaker is None:
- if last_known_speaker is not None:
- speaker = last_known_speaker
- app.logger.info(f"Assigned speaker '{speaker}' to segment {i} from previous segment")
- else:
- speaker = 'UNKNOWN_SPEAKER'
- app.logger.warning(f"No previous speaker available for segment {i}, using UNKNOWN_SPEAKER")
- else:
- # Update the last known speaker when we have a valid one
- last_known_speaker = speaker
-
- simplified_segments.append({
- 'speaker': speaker,
- 'sentence': text,
- 'start_time': segment.get('start'),
- 'end_time': segment.get('end')
- })
+ # Convert to WAV using same parameters as reprocessing
+ filename_lower = actual_filename.lower()
+ if not filename_lower.endswith('.wav'):
+ try:
+ base_filepath, file_ext = os.path.splitext(actual_filepath)
+ temp_wav_filepath = f"{base_filepath}_temp.wav"
+
+ app.logger.info(f"Converting {actual_filename} to WAV format for retry...")
+ subprocess.run(
+ ['ffmpeg', '-i', actual_filepath, '-y', '-acodec', 'pcm_s16le', '-ar', '16000', '-ac', '1', temp_wav_filepath],
+ check=True, capture_output=True, text=True
+ )
+ app.logger.info(f"Successfully converted {actual_filepath} to {temp_wav_filepath}")
+
+ wav_converted_filepath = temp_wav_filepath
+ wav_conversion_attempted = True
+ # Continue to next iteration to retry with WAV
+ continue
+ except subprocess.CalledProcessError as conv_error:
+ app.logger.error(f"Failed to convert to WAV: {conv_error}")
+ # Re-raise the original HTTP error if conversion fails
+ raise e
+ else:
+ # Already a WAV file, can't convert further
+ app.logger.error(f"File is already WAV but still getting 500 error")
+ raise e
+ else:
+ # Not a 500 error or already tried conversion, propagate the error
+ raise e
+
+ # Clean up temporary WAV file if created
+ try:
+ if wav_converted_filepath and os.path.exists(wav_converted_filepath):
+ os.remove(wav_converted_filepath)
+ app.logger.info(f"Cleaned up temporary WAV file: {wav_converted_filepath}")
+ except Exception as cleanup_error:
+ app.logger.warning(f"Failed to clean up temporary WAV file: {cleanup_error}")
+
+ # Debug logging for ASR response
+ app.logger.info(f"ASR response keys: {list(asr_response_data.keys())}")
+
+ # Log the complete raw JSON response (truncated for readability)
+ import json as json_module
+ raw_json_str = json_module.dumps(asr_response_data, indent=2)
+ if len(raw_json_str) > 5000:
+ app.logger.info(f"Raw ASR response (first 5000 chars): {raw_json_str[:5000]}...")
+ else:
+ app.logger.info(f"Raw ASR response: {raw_json_str}")
+
+ if 'segments' in asr_response_data:
+ app.logger.info(f"Number of segments: {len(asr_response_data['segments'])}")
+
+ # Collect all unique speakers from the response
+ all_speakers = set()
+ segments_with_speakers = 0
+ segments_without_speakers = 0
+
+ for segment in asr_response_data['segments']:
+ if 'speaker' in segment and segment['speaker'] is not None:
+ all_speakers.add(segment['speaker'])
+ segments_with_speakers += 1
+ else:
+ segments_without_speakers += 1
+
+ app.logger.info(f"Unique speakers found in raw response: {sorted(list(all_speakers))}")
+ app.logger.info(f"Segments with speakers: {segments_with_speakers}, without speakers: {segments_without_speakers}")
+
+ # Log first few segments for debugging
+ for i, segment in enumerate(asr_response_data['segments'][:5]):
+ segment_keys = list(segment.keys())
+ app.logger.info(f"Segment {i} keys: {segment_keys}")
+ app.logger.info(f"Segment {i}: speaker='{segment.get('speaker')}', text='{segment.get('text', '')[:50]}...'")
+
+ # Simplify the JSON data
+ simplified_segments = []
+ if 'segments' in asr_response_data and isinstance(asr_response_data['segments'], list):
+ last_known_speaker = None
+
+ for i, segment in enumerate(asr_response_data['segments']):
+ speaker = segment.get('speaker')
+ text = segment.get('text', '').strip()
- # Log final simplified segments count
- app.logger.info(f"Created {len(simplified_segments)} simplified segments")
- null_speaker_count = sum(1 for seg in simplified_segments if seg['speaker'] is None)
- if null_speaker_count > 0:
- app.logger.warning(f"Found {null_speaker_count} segments with null speakers in final output")
+ # If segment doesn't have a speaker, use the previous segment's speaker
+ if speaker is None:
+ if last_known_speaker is not None:
+ speaker = last_known_speaker
+ app.logger.info(f"Assigned speaker '{speaker}' to segment {i} from previous segment")
+ else:
+ speaker = 'UNKNOWN_SPEAKER'
+ app.logger.warning(f"No previous speaker available for segment {i}, using UNKNOWN_SPEAKER")
+ else:
+ # Update the last known speaker when we have a valid one
+ last_known_speaker = speaker
- # Store the simplified JSON as a string
- recording.transcription = json.dumps(simplified_segments)
+ simplified_segments.append({
+ 'speaker': speaker,
+ 'sentence': text,
+ 'start_time': segment.get('start'),
+ 'end_time': segment.get('end')
+ })
+
+ # Log final simplified segments count
+ app.logger.info(f"Created {len(simplified_segments)} simplified segments")
+ null_speaker_count = sum(1 for seg in simplified_segments if seg['speaker'] is None)
+ if null_speaker_count > 0:
+ app.logger.warning(f"Found {null_speaker_count} segments with null speakers in final output")
+
+ # Store the simplified JSON as a string
+ recording.transcription = json.dumps(simplified_segments)
# Commit the transcription data
db.session.commit()
@@ -2204,11 +2422,22 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,
except Exception as e:
db.session.rollback()
- app.logger.error(f"ASR processing FAILED for recording {recording_id}: {str(e)}", exc_info=True)
+
+ # Handle timeout errors specifically
+ error_msg = str(e)
+ if "timed out" in error_msg.lower() or "timeout" in error_msg.lower():
+ asr_timeout = SystemSetting.get_setting('asr_timeout_seconds', 1800)
+ app.logger.error(f"ASR processing TIMED OUT for recording {recording_id} after {asr_timeout} seconds. Consider increasing 'asr_timeout_seconds' in Admin Dashboard > System Settings.")
+ user_error_msg = f"ASR processing timed out after {asr_timeout} seconds. The file may be too long for the current timeout setting."
+ else:
+ # For non-timeout errors, include more detail
+ app.logger.error(f"ASR processing FAILED for recording {recording_id}: {error_msg}")
+ user_error_msg = f"ASR processing failed: {error_msg}"
+
recording = db.session.get(Recording, recording_id)
if recording:
recording.status = 'FAILED'
- recording.transcription = f"ASR processing failed: {str(e)}"
+ recording.transcription = user_error_msg
db.session.commit()
def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr, start_time, language=None, min_speakers=None, max_speakers=None, tag_id=None):
@@ -2779,6 +3008,160 @@ def download_summary_word(recording_id):
app.logger.error(f"Error generating summary Word document: {e}")
return jsonify({'error': 'Failed to generate Word document'}), 500
[email protected]('/recording/<int:recording_id>/download/chat', methods=['POST'])
+@login_required
+def download_chat_word(recording_id):
+ """Download chat conversation as a Word document."""
+ try:
+ from docx import Document
+ from docx.shared import Inches
+ import re
+ from io import BytesIO
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Check if the recording belongs to the current user
+ if recording.user_id and recording.user_id != current_user.id:
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ # Get chat messages from request
+ data = request.json
+ if not data or 'messages' not in data:
+ return jsonify({'error': 'No messages provided'}), 400
+
+ messages = data['messages']
+ if not messages:
+ return jsonify({'error': 'No messages to download'}), 400
+
+ # Create Word document
+ doc = Document()
+
+ # Add title
+ title = doc.add_heading(f'Chat Conversation: {recording.title or "Untitled Recording"}', 0)
+
+ # Add metadata
+ doc.add_paragraph(f'Recording Date: {recording.created_at.strftime("%Y-%m-%d %H:%M")}')
+ doc.add_paragraph(f'Chat Export Date: {datetime.utcnow().strftime("%Y-%m-%d %H:%M")}')
+ doc.add_paragraph('') # Empty line
+
+ # Add chat messages
+ for message in messages:
+ role = message.get('role', 'unknown')
+ content = message.get('content', '')
+ thinking = message.get('thinking', '')
+
+ # Add role header
+ if role == 'user':
+ p = doc.add_paragraph()
+ p.add_run('You: ').bold = True
+ elif role == 'assistant':
+ p = doc.add_paragraph()
+ p.add_run('Assistant: ').bold = True
+ else:
+ p = doc.add_paragraph()
+ p.add_run(f'{role.title()}: ').bold = True
+
+ # Add thinking content if present
+ if thinking and role == 'assistant':
+ p = doc.add_paragraph()
+ p.add_run('[Model Reasoning]\n').italic = True
+ p.add_run(thinking).italic = True
+ doc.add_paragraph('') # Empty line
+
+ # Add message content
+ # Convert markdown-like formatting
+ lines = content.split('\n')
+ current_paragraph = None
+
+ for line in lines:
+ if line.startswith('# '):
+ # Heading
+ doc.add_heading(line[2:], level=1)
+ current_paragraph = None
+ elif line.startswith('## '):
+ # Subheading
+ doc.add_heading(line[3:], level=2)
+ current_paragraph = None
+ elif line.startswith('### '):
+ # Sub-subheading
+ doc.add_heading(line[4:], level=3)
+ current_paragraph = None
+ elif line.startswith('- ') or line.startswith('* '):
+ # Bullet point
+ p = doc.add_paragraph(style='List Bullet')
+ # Handle bold text
+ text = line[2:]
+ bold_pattern = r'\*\*(.*?)\*\*'
+ parts = re.split(bold_pattern, text)
+ for i, part in enumerate(parts):
+ if i % 2 == 0: # Regular text
+ if part:
+ p.add_run(part)
+ else: # Bold text
+ if part:
+ p.add_run(part).bold = True
+ current_paragraph = None
+ elif re.match(r'^\d+\.', line):
+ # Numbered list
+ p = doc.add_paragraph(style='List Number')
+ text = re.sub(r'^\d+\.\s*', '', line)
+ # Handle bold text
+ bold_pattern = r'\*\*(.*?)\*\*'
+ parts = re.split(bold_pattern, text)
+ for i, part in enumerate(parts):
+ if i % 2 == 0: # Regular text
+ if part:
+ p.add_run(part)
+ else: # Bold text
+ if part:
+ p.add_run(part).bold = True
+ current_paragraph = None
+ else:
+ # Regular paragraph
+ if current_paragraph is None:
+ current_paragraph = doc.add_paragraph()
+ else:
+ current_paragraph.add_run('\n')
+
+ # Handle bold text
+ bold_pattern = r'\*\*(.*?)\*\*'
+ parts = re.split(bold_pattern, line)
+ for i, part in enumerate(parts):
+ if i % 2 == 0: # Regular text
+ if part:
+ current_paragraph.add_run(part)
+ else: # Bold text
+ if part:
+ current_paragraph.add_run(part).bold = True
+
+ doc.add_paragraph('') # Empty line between messages
+
+ # Save to BytesIO
+ doc_stream = BytesIO()
+ doc.save(doc_stream)
+ doc_stream.seek(0)
+
+ # Create safe filename
+ safe_title = re.sub(r'[^\w\s-]', '', recording.title or 'Untitled')
+ safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-')
+ filename = f'chat-{safe_title}.docx' if safe_title else f'chat-recording-{recording_id}.docx'
+
+ response = send_file(
+ doc_stream,
+ as_attachment=True,
+ download_name=filename,
+ mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+ )
+
+ response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
+ return response
+
+ except Exception as e:
+ app.logger.error(f"Error generating chat Word document: {e}")
+ return jsonify({'error': 'Failed to generate Word document'}), 500
+
@app.route('/recording/<int:recording_id>/download/notes')
@login_required
def download_notes_word(recording_id):
@@ -3341,14 +3724,9 @@ Additional context and notes about the meeting:
stream=True
)
- for chunk in stream:
- content = chunk.choices[0].delta.content
- if content:
- # Yield the content in SSE format
- yield f"data: {json.dumps({'delta': content})}\n\n"
-
- # Signal the end of the stream
- yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
+ # Use helper function to process streaming with thinking tag support
+ for response in process_streaming_with_thinking(stream):
+ yield response
except Exception as e:
app.logger.error(f"Error during chat stream generation: {str(e)}")
@@ -3675,40 +4053,16 @@ def account():
flash('Account details updated successfully!', 'success')
return redirect(url_for('account'))
- default_summary_prompt_text = """Identify the key issues discussed. First, give me minutes. Then, give me the key issues discussed. Then, any key takeaways. Then, any next steps. Then, all important things that I didn't ask for but that need to be recorded. Make sure every important nuance is covered.
-
-CRITICAL FORMATTING REQUIREMENTS:
-- Each **Bold Key:** value pair MUST be on its own separate line
-- Add a blank line after bold headers when followed by bullet point lists
-- Never put multiple **Bold:** items on the same line
-- Use proper markdown with consistent line breaks
-
-Example Format:
-
-### Minutes
-
-**Case:** Wisconsin Central v. United States
-
-**Court:** U.S. Supreme Court
-
-**Date:** Not specified
-
-**Counsel:** John Dupree (Petitioner), Cynthia Covner (Respondent)
-
-**Meeting Participants:**
-
-- Bob
-- Alice
-
----
-
-**1. Introduction and Overview:**
-
-- Alice expressed interest in understanding the responsibilities at the north division and the potential for technological innovations.
-....
-### Key Issues Discussed
-....
-//and so on and so forth. Make sure not to miss any nuance or details."""
+ # Get admin default prompt from system settings
+ admin_default_prompt = SystemSetting.get_setting('admin_default_summary_prompt', None)
+ if admin_default_prompt:
+ default_summary_prompt_text = admin_default_prompt
+ else:
+ # Fallback to hardcoded default if admin hasn't set one
+ default_summary_prompt_text = """Generate a comprehensive summary that includes the following sections:
+- **Key Issues Discussed**: A bulleted list of the main topics
+- **Key Decisions Made**: A bulleted list of any decisions reached
+- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
asr_diarize_locked = 'ASR_DIARIZE' in os.environ
@@ -5041,12 +5395,9 @@ Use proper markdown formatting including headings (##), bold (**text**), bullet
stream=True
)
- for chunk in stream:
- content = chunk.choices[0].delta.content
- if content:
- yield f"data: {json.dumps({'delta': content})}\n\n"
-
- yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
+ # Use helper function to process streaming with thinking tag support
+ for response in process_streaming_with_thinking(stream):
+ yield response
return
except Exception as e:
@@ -5386,10 +5737,17 @@ Order your response with notes from the most recent meetings first. Always use p
# Buffer content to detect full transcript requests
response_buffer = ""
+ # Buffer content to detect full transcript requests
+ response_buffer = ""
+ content_buffer = ""
+ in_thinking = False
+ thinking_buffer = ""
+
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
response_buffer += content
+ content_buffer += content
# Check if this is a full transcript request
if response_buffer.strip().startswith("REQUEST_FULL_TRANSCRIPT:"):
@@ -5438,12 +5796,9 @@ Order your response with notes from the most recent meetings first. Always use p
stream=True
)
- for new_chunk in new_stream:
- new_content = new_chunk.choices[0].delta.content
- if new_content:
- yield f"data: {json.dumps({'delta': new_content})}\n\n"
-
- yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
+ # Use helper function to process streaming with thinking tag support
+ for response in process_streaming_with_thinking(new_stream):
+ yield response
return
else:
# Recording not found or no permission
@@ -5457,8 +5812,55 @@ Order your response with notes from the most recent meetings first. Always use p
# Continue with normal streaming
pass
- # Normal streaming - yield content as it comes
- yield f"data: {json.dumps({'delta': content})}\n\n"
+ # Process the buffer to detect and handle thinking tags
+ while True:
+ if not in_thinking:
+ # Look for opening thinking tag
+ think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_start:
+ # Send any content before the thinking tag
+ before_thinking = content_buffer[:think_start.start()]
+ if before_thinking:
+ yield f"data: {json.dumps({'delta': before_thinking})}\n\n"
+
+ # Start capturing thinking content
+ in_thinking = True
+ content_buffer = content_buffer[think_start.end():]
+ thinking_buffer = ""
+ else:
+ # No thinking tag found, send accumulated content
+ if content_buffer:
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
+ content_buffer = ""
+ break
+ else:
+ # We're inside a thinking tag, look for closing tag
+ think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_end:
+ # Capture thinking content up to the closing tag
+ thinking_buffer += content_buffer[:think_end.start()]
+
+ # Send the thinking content as a special type
+ if thinking_buffer.strip():
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+
+ # Continue processing after the closing tag
+ in_thinking = False
+ content_buffer = content_buffer[think_end.end():]
+ thinking_buffer = ""
+ else:
+ # Still inside thinking tag, accumulate content
+ thinking_buffer += content_buffer
+ content_buffer = ""
+ break
+
+ # Handle any remaining content
+ if in_thinking and thinking_buffer:
+ # Unclosed thinking tag - send as thinking content
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+ elif content_buffer:
+ # Regular content
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
diff --git a/env.asr.example b/env.asr.example
index 37fefc6c..3d495a2e 100644
--- a/env.asr.example
+++ b/env.asr.example
@@ -17,8 +17,11 @@ TEXT_MODEL_NAME=openai/gpt-4o-mini
# Note: File chunking is NOT supported with ASR endpoints
USE_ASR_ENDPOINT=true
-# ASR Endpoint URL (e.g., http://localhost:9000 or http://your_asr_host:9000)
-ASR_BASE_URL=http://your_asr_host:9000
+# ASR Endpoint URL
+# For containers in same docker-compose: Use container name and internal port
+# Example: http://whisper-asr:9000 (NOT the host port 6002 or external IP)
+# For external ASR: Use http://192.168.1.100:9000 or http://asr.example.com:9000
+ASR_BASE_URL=http://whisper-asr:9000
# Optional: Override default speaker settings (defaults shown)
# These are automatically set when USE_ASR_ENDPOINT=true
diff --git a/static/js/app.js b/static/js/app.js
index 7cb1ed24..2a026a3e 100644
--- a/static/js/app.js
+++ b/static/js/app.js
@@ -3145,6 +3145,27 @@ document.addEventListener('DOMContentLoaded', () => {
};
// --- Chat Functionality ---
+ // Helper function to check if chat is scrolled to bottom (within bottom 5%)
+ const isChatScrolledToBottom = () => {
+ if (!chatMessagesRef.value) return true;
+ const { scrollTop, scrollHeight, clientHeight } = chatMessagesRef.value;
+ const scrollableHeight = scrollHeight - clientHeight;
+ if (scrollableHeight <= 0) return true; // No scrolling possible
+ const scrollPercentage = scrollTop / scrollableHeight;
+ return scrollPercentage >= 0.95; // Within bottom 5%
+ };
+
+ // Helper function to scroll chat to bottom with smooth behavior
+ const scrollChatToBottom = () => {
+ if (chatMessagesRef.value) {
+ requestAnimationFrame(() => {
+ if (chatMessagesRef.value) {
+ chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
+ }
+ });
+ }
+ };
+
const sendChatMessage = async () => {
if (!chatInput.value.trim() || isChatLoading.value || !selectedRecording.value || selectedRecording.value.status !== 'COMPLETED') {
return;
@@ -3161,9 +3182,8 @@ document.addEventListener('DOMContentLoaded', () => {
isChatLoading.value = true;
await nextTick();
- if (chatMessagesRef.value) {
- chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
- }
+ // Always scroll to bottom when user sends a new message
+ scrollChatToBottom();
let assistantMessage = null;
@@ -3207,19 +3227,60 @@ document.addEventListener('DOMContentLoaded', () => {
if (jsonStr) {
try {
const data = JSON.parse(jsonStr);
+ if (data.thinking) {
+ // Check scroll position BEFORE updating content
+ const shouldScroll = isChatScrolledToBottom();
+
+ if (isFirstChunk) {
+ isChatLoading.value = false;
+ assistantMessage = reactive({
+ role: 'assistant',
+ content: '',
+ html: '',
+ thinking: data.thinking,
+ thinkingExpanded: false
+ });
+ chatMessages.value.push(assistantMessage);
+ isFirstChunk = false;
+ } else if (assistantMessage) {
+ // Append to existing thinking content
+ if (assistantMessage.thinking) {
+ assistantMessage.thinking += '\n\n' + data.thinking;
+ } else {
+ assistantMessage.thinking = data.thinking;
+ }
+ }
+
+ // Scroll if we were at bottom before the update
+ if (shouldScroll) {
+ await nextTick();
+ scrollChatToBottom();
+ }
+ }
if (data.delta) {
+ // Check scroll position BEFORE updating content
+ const shouldScroll = isChatScrolledToBottom();
+
if (isFirstChunk) {
isChatLoading.value = false;
- assistantMessage = reactive({ role: 'assistant', content: '', html: '' });
+ assistantMessage = reactive({
+ role: 'assistant',
+ content: '',
+ html: '',
+ thinking: '',
+ thinkingExpanded: false
+ });
chatMessages.value.push(assistantMessage);
isFirstChunk = false;
}
+
assistantMessage.content += data.delta;
assistantMessage.html = marked.parse(assistantMessage.content);
- await nextTick();
- if (chatMessagesRef.value) {
- chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
+ // Scroll if we were at bottom before the update
+ if (shouldScroll) {
+ await nextTick();
+ scrollChatToBottom();
}
}
if (data.end_of_stream) {
@@ -3250,8 +3311,9 @@ document.addEventListener('DOMContentLoaded', () => {
} finally {
isChatLoading.value = false;
await nextTick();
- if (chatMessagesRef.value) {
- chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
+ // Final scroll only if user is at bottom
+ if (isChatScrolledToBottom()) {
+ scrollChatToBottom();
}
}
};
@@ -3612,6 +3674,60 @@ document.addEventListener('DOMContentLoaded', () => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
+ showToast('Notes downloaded successfully!', 'fa-check-circle');
+ } catch (error) {
+ console.error('Download failed:', error);
+ showToast('Failed to download notes', 'fa-exclamation-circle');
+ }
+ };
+
+ const downloadChat = async () => {
+ if (!selectedRecording.value || chatMessages.value.length === 0) {
+ showToast('No chat messages to download.', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/recording/${selectedRecording.value.id}/download/chat`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken.value
+ },
+ body: JSON.stringify({
+ messages: chatMessages.value
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ showToast(error.error || 'Failed to download chat', 'fa-exclamation-circle');
+ return;
+ }
+
+ // Create blob and download
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ a.href = url;
+
+ // Get filename from response headers or use default
+ const contentDisposition = response.headers.get('Content-Disposition');
+ let filename = 'chat.docx';
+ if (contentDisposition) {
+ const matches = /filename="(.+)"/.exec(contentDisposition);
+ if (matches) {
+ filename = matches[1];
+ }
+ }
+ a.download = filename;
+
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+
showToast('Notes downloaded successfully!');
} catch (error) {
console.error('Download failed:', error);
@@ -4164,9 +4280,9 @@ document.addEventListener('DOMContentLoaded', () => {
confirmDelete, cancelDelete, deleteRecording,
toggleEditParticipants, toggleEditMeetingDate, toggleEditSummary, cancelEditSummary, saveEditSummary, toggleEditNotes,
cancelEditNotes, saveEditNotes, initializeMarkdownEditor, saveInlineEdit,
- sendChatMessage, startColumnResize, handleChatKeydown, seekAudio, seekAudioFromEvent, onPlayerVolumeChange,
+ sendChatMessage, isChatScrolledToBottom, scrollChatToBottom, startColumnResize, handleChatKeydown, seekAudio, seekAudioFromEvent, onPlayerVolumeChange,
showToast, copyMessage, copyTranscription, copySummary, copyNotes,
- downloadSummary, downloadNotes,
+ downloadSummary, downloadNotes, downloadChat,
toggleInbox, toggleHighlight,
toggleTranscriptionViewMode,
reprocessTranscription,
diff --git a/templates/account.html b/templates/account.html
index 1e5dac4c..5677f0fc 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -87,6 +87,9 @@
<a href="#" id="tab-account" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b-2 sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-[var(--border-accent)] text-[var(--text-accent)] bg-[var(--bg-tertiary)] sm:bg-transparent">
<i class="fas fa-user-circle mr-2"></i><span>Account Information</span>
</a>
+ <a href="#" id="tab-prompts" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent">
+ <i class="fas fa-file-alt mr-2"></i><span>Custom Prompts</span>
+ </a>
<a href="#" id="tab-shares" class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent">
<i class="fas fa-share-alt mr-2"></i><span>Shared Transcripts</span>
</a>
@@ -135,7 +138,7 @@
</div>
<div class="mb-6">
- <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Language & Prompt Preferences</h3>
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Language Preferences</h3>
<div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] space-y-4">
<div>
<label for="transcription_language" class="block text-sm font-medium text-[var(--text-muted)]">Transcription Language</label>
@@ -147,11 +150,6 @@
<input type="text" name="output_language" id="output_language" value="{{ current_user.output_language or '' }}" placeholder="e.g., English, Spanish, Chinese" 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)]">
<p class="text-xs text-[var(--text-light)] mt-1">Language for titles, summaries, and chat. Leave blank for default (default behavior of your chosen model).</p>
</div>
- <div>
- <label for="summary_prompt" class="block text-sm font-medium text-[var(--text-muted)]">Custom Summary Prompt</label>
- <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>
</div>
@@ -231,6 +229,64 @@
</div>
</div>
+ <div id="content-prompts" class="hidden">
+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Custom Prompts</h2>
+
+ <form method="POST" action="{{ url_for('account') }}" class="space-y-6">
+ <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+
+ <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-4">Summary Generation Prompt</h3>
+
+ <div class="mb-4">
+ <label for="summary_prompt_custom" class="block text-sm font-medium text-[var(--text-muted)] mb-2">
+ Your Custom Summary Prompt
+ </label>
+ <textarea name="summary_prompt" id="summary_prompt_custom" rows="8"
+ placeholder="Describe how you want your summaries structured. Leave blank to use the admin's default prompt."
+ class="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 '' }}</textarea>
+ <p class="text-xs text-[var(--text-light)] mt-2">
+ This prompt will be used to generate summaries for your transcriptions. It overrides the admin's default prompt.
+ </p>
+ </div>
+
+ <div class="mt-6 p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-secondary)]">
+ <h4 class="text-sm font-semibold text-[var(--text-accent)] mb-2">
+ <i class="fas fa-info-circle mr-1"></i>
+ Current Default Prompt (Used if you leave the above blank)
+ </h4>
+ <div class="bg-[var(--bg-primary)] p-3 rounded border border-[var(--border-primary)]">
+ <pre class="text-xs text-[var(--text-muted)] whitespace-pre-wrap">{{ default_summary_prompt_text }}</pre>
+ </div>
+ </div>
+
+ <div class="mt-4">
+ <details class="cursor-pointer">
+ <summary class="text-sm text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]">
+ <i class="fas fa-question-circle mr-1"></i>
+ Tips for Writing Effective Prompts
+ </summary>
+ <div class="mt-3 p-3 bg-[var(--bg-info-light)] text-[var(--text-info-strong)] rounded-lg text-sm">
+ <ul class="list-disc list-inside space-y-1">
+ <li>Be specific about the sections you want in your summary</li>
+ <li>Use clear formatting instructions (e.g., "Use bullet points", "Create numbered lists")</li>
+ <li>Specify if you want certain information prioritized</li>
+ <li>The system will automatically provide the transcript content to the AI</li>
+ <li>Your output language preference (if set) will be applied automatically</li>
+ </ul>
+ </div>
+ </details>
+ </div>
+ </div>
+
+ <div class="flex justify-end">
+ <button type="submit" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <i class="fas fa-save mr-2"></i> Save Custom Prompt
+ </button>
+ </div>
+ </form>
+ </div>
+
<div id="content-shares" class="hidden">
<h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">My Shared Transcripts</h2>
<div id="shares-container" class="space-y-4">
@@ -679,77 +735,70 @@
<script>
document.addEventListener('DOMContentLoaded', function() {
const tabAccount = document.getElementById('tab-account');
+ const tabPrompts = document.getElementById('tab-prompts');
const tabShares = document.getElementById('tab-shares');
const tabTags = document.getElementById('tab-tags');
const tabAbout = document.getElementById('tab-about');
const contentAccount = document.getElementById('content-account');
+ const contentPrompts = document.getElementById('content-prompts');
const contentShares = document.getElementById('content-shares');
const contentTags = document.getElementById('content-tags');
const contentAbout = document.getElementById('content-about');
const sharesContainer = document.getElementById('shares-container');
+ // Simplified tab switching
+ const tabs = [
+ { tab: tabAccount, content: contentAccount, name: 'account' },
+ { tab: tabPrompts, content: contentPrompts, name: 'prompts' },
+ { tab: tabShares, content: contentShares, name: 'shares' },
+ { tab: tabTags, content: contentTags, name: 'tags' },
+ { tab: tabAbout, content: contentAbout, name: 'about' }
+ ];
+
+ function switchToTab(targetName) {
+ tabs.forEach(({ tab, content, name }) => {
+ if (name === targetName) {
+ // Active tab
+ tab.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
+ tab.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
+ content.classList.remove('hidden');
+ } else {
+ // Inactive tab
+ tab.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
+ tab.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
+ content.classList.add('hidden');
+ }
+ });
+
+ // Load content when switching tabs
+ if (targetName === 'shares') {
+ loadShares();
+ } else if (targetName === 'tags') {
+ loadTags();
+ } else if (targetName === 'about') {
+ loadSystemInfo();
+ }
+ }
+
function showAccountTab() {
- tabAccount.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabAccount.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- contentAccount.classList.remove('hidden');
- contentShares.classList.add('hidden');
- contentTags.classList.add('hidden');
- contentAbout.classList.add('hidden');
+ switchToTab('account');
+ }
+
+ function showPromptsTab() {
+ switchToTab('prompts');
}
function showSharesTab() {
- tabShares.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabShares.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- contentShares.classList.remove('hidden');
- contentAccount.classList.add('hidden');
- contentTags.classList.add('hidden');
- contentAbout.classList.add('hidden');
- loadShares();
+ switchToTab('shares');
}
function showTagsTab() {
- tabTags.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabTags.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- contentTags.classList.remove('hidden');
- contentAccount.classList.add('hidden');
- contentShares.classList.add('hidden');
- contentAbout.classList.add('hidden');
- loadTags();
+ switchToTab('tags');
}
function showAboutTab() {
- tabAbout.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabAbout.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]', 'hover:bg-[var(--bg-tertiary)]', 'sm:hover:bg-transparent');
- tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]', 'bg-[var(--bg-tertiary)]', 'sm:bg-transparent');
- contentAbout.classList.remove('hidden');
- contentAccount.classList.add('hidden');
- contentShares.classList.add('hidden');
- contentTags.classList.add('hidden');
- loadSystemInfo();
+ switchToTab('about');
}
tabAccount.addEventListener('click', (e) => {
@@ -757,6 +806,11 @@
showAccountTab();
});
+ tabPrompts.addEventListener('click', (e) => {
+ e.preventDefault();
+ showPromptsTab();
+ });
+
tabShares.addEventListener('click', (e) => {
e.preventDefault();
showSharesTab();
diff --git a/templates/admin.html b/templates/admin.html
index ee462d45..0eeb4fea 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -111,6 +111,11 @@
class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm">
<i class="fas fa-cogs mr-2"></i><span>System Settings</span>
</button>
+ <button @click="activeTab = 'prompts'"
+ :class="activeTab === 'prompts' ? 'border-[var(--border-focus)] text-[var(--text-accent)] bg-[var(--bg-tertiary)] sm:bg-transparent' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent'"
+ class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm">
+ <i class="fas fa-file-alt mr-2"></i><span>Default Prompts</span>
+ </button>
<button @click="activeTab = 'vectorstore'"
:class="activeTab === 'vectorstore' ? 'border-[var(--border-focus)] text-[var(--text-accent)] bg-[var(--bg-tertiary)] sm:bg-transparent' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] sm:hover:bg-transparent'"
class="flex items-center whitespace-nowrap py-3 sm:py-4 px-3 sm:px-1 border-b sm:border-b-2 border-l-4 sm:border-l-0 font-medium text-sm"
@@ -333,6 +338,9 @@
</span>
<span v-else-if="setting.key === 'max_file_size_mb'" class="text-[var(--text-primary)]">
${ Number(setting.value).toLocaleString() } MB
+ </span>
+ <span v-else-if="setting.key === 'asr_timeout_seconds'" class="text-[var(--text-primary)]">
+ ${ Number(setting.value).toLocaleString() } seconds
</span>
<span v-else>${ setting.value || 'Not set' }</span>
</div>
@@ -355,6 +363,136 @@
</div>
</div>
+ <!-- Default Prompts Tab -->
+ <div v-show="activeTab === 'prompts'">
+ <div class="mb-6">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-4">Default Prompts</h3>
+ <div class="bg-[var(--bg-info-light)] text-[var(--text-info-strong)] p-4 rounded-lg mb-4">
+ <i class="fas fa-info-circle mr-2"></i>
+ This default prompt will be used for all users who haven't set their own custom prompt in their account settings.
+ </div>
+ </div>
+
+ <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
+ <div class="mb-4">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
+ Default Summarization Prompt
+ </label>
+ <p class="text-sm text-[var(--text-muted)] mb-3">
+ This prompt will be used to generate summaries for all recordings when users haven't set their own prompt.
+ </p>
+ <textarea
+ v-model="defaultSummaryPrompt"
+ rows="8"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Enter the default summarization prompt...">
+ </textarea>
+ </div>
+
+ <div class="flex justify-between items-center">
+ <div>
+ <button @click="resetDefaultPrompt"
+ class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">
+ <i class="fas fa-undo mr-2"></i> Reset to Default
+ </button>
+ </div>
+ <div>
+ <button @click="saveDefaultPrompt"
+ :disabled="isSavingPrompt"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] disabled:opacity-50 disabled:cursor-not-allowed">
+ <i v-if="isSavingPrompt" class="fas fa-spinner fa-spin mr-2"></i>
+ <i v-else class="fas fa-save mr-2"></i>
+ ${ isSavingPrompt ? 'Saving...' : 'Save Changes' }
+ </button>
+ </div>
+ </div>
+
+ <div v-if="promptSaveMessage" class="mt-4">
+ <div :class="promptSaveError ? 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]' : 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'"
+ class="p-3 rounded-md text-sm">
+ ${ promptSaveMessage }
+ </div>
+ </div>
+ </div>
+
+ <div class="mt-6 bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">
+ <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">Prompt Hierarchy</h4>
+ <p class="text-sm text-[var(--text-muted)] mb-3">
+ The system uses the following priority order when selecting which prompt to use:
+ </p>
+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)]">
+ <li><strong>Tag Custom Prompt:</strong> If a recording has tags with custom prompts</li>
+ <li><strong>User Custom Prompt:</strong> If the user has set their own prompt in account settings</li>
+ <li><strong>Admin Default Prompt:</strong> The prompt configured above (shown on this page)</li>
+ <li><strong>System Fallback:</strong> A hardcoded default if none of the above are set</li>
+ </ol>
+ </div>
+
+ <!-- Full LLM Prompt Structure Expander -->
+ <div class="mt-6 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)]">
+ <button @click="showFullPromptStructure = !showFullPromptStructure"
+ class="w-full p-6 flex justify-between items-center hover:bg-[var(--bg-quaternary)] transition-colors duration-200">
+ <h4 class="text-md font-medium text-[var(--text-secondary)]">
+ <i class="fas fa-code mr-2"></i>
+ View Full LLM Prompt Structure
+ </h4>
+ <i :class="showFullPromptStructure ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"
+ class="text-[var(--text-muted)]"></i>
+ </button>
+
+ <div v-show="showFullPromptStructure" class="border-t border-[var(--border-primary)]">
+ <div class="p-6 space-y-6">
+ <div>
+ <h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">System Prompt:</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">
+
+Summarization Instructions:
+${ defaultSummaryPrompt || originalDefaultPrompt }</span></pre>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] mt-2">
+ <i class="fas fa-info-circle mr-1"></i>
+ Note: If the user has set an output language preference, " Ensure your response is in {language}." will be added.
+ </p>
+ </div>
+
+ <div>
+ <h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">User Message Template:</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:
+"""
+{transcript_text}
+"""
+
+Please analyze the above transcription and generate a summary following the provided instructions.</pre>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] mt-2">
+ <i class="fas fa-info-circle mr-1"></i>
+ Placeholders are replaced with actual values when processing a recording.
+ </p>
+ </div>
+
+ <div>
+ <h5 class="text-sm font-semibold text-[var(--text-accent)] mb-2">Additional Context:</h5>
+ <div class="bg-[var(--bg-info-light)] p-4 rounded-md">
+ <ul class="text-xs text-[var(--text-info-strong)] space-y-2">
+ <li><i class="fas fa-check-circle mr-1"></i> Transcripts are limited to a configurable character count (default: 30,000)</li>
+ <li><i class="fas fa-check-circle mr-1"></i> JSON transcripts are converted to clean text format before sending</li>
+ <li><i class="fas fa-check-circle mr-1"></i> If multiple tag prompts exist, they are merged in the order tags were added</li>
+ <li><i class="fas fa-check-circle mr-1"></i> The model used is configured via TEXT_MODEL_NAME environment variable</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Vector Store Tab -->
<div v-show="activeTab === 'vectorstore'" v-if="inquireModeEnabled">
<div class="flex justify-between items-center mb-6">
@@ -603,6 +741,144 @@
</div>
</div>
</div>
+
+ <!-- Edit System Setting Modal -->
+ <div v-if="showEditSettingModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-lg">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Edit System Setting</h3>
+ <button @click="showEditSettingModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)] text-2xl leading-none">&times;</button>
+ </div>
+
+ <div v-if="editingSetting" class="space-y-4">
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Setting Key</label>
+ <div class="px-3 py-2 bg-[var(--bg-tertiary)] text-[var(--text-muted)] rounded-md font-mono text-sm">
+ ${ editingSetting.key }
+ </div>
+ </div>
+
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Description</label>
+ <div class="px-3 py-2 text-[var(--text-muted)] text-sm">
+ ${ editingSetting.description || 'No description available' }
+ </div>
+ </div>
+
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Type</label>
+ <span class="inline-block px-2 py-1 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded text-xs">
+ ${ editingSetting.setting_type }
+ </span>
+ </div>
+
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Current Value</label>
+ <div class="px-3 py-2 bg-[var(--bg-tertiary)] text-[var(--text-muted)] rounded-md">
+ <span v-if="editingSetting.key === 'transcript_length_limit' && editingSetting.value === '-1'">
+ No Limit
+ </span>
+ <span v-else-if="editingSetting.key === 'transcript_length_limit'">
+ ${ Number(editingSetting.value).toLocaleString() } characters
+ </span>
+ <span v-else-if="editingSetting.key === 'max_file_size_mb'">
+ ${ Number(editingSetting.value).toLocaleString() } MB
+ </span>
+ <span v-else-if="editingSetting.key === 'asr_timeout_seconds'">
+ ${ Number(editingSetting.value).toLocaleString() } seconds (${ Math.round(Number(editingSetting.value) / 60) } minutes)
+ </span>
+ <span v-else>${ editingSetting.value || 'Not set' }</span>
+ </div>
+ </div>
+
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">New Value</label>
+
+ <!-- Boolean type -->
+ <div v-if="editingSetting.setting_type === 'boolean'" class="flex items-center space-x-4">
+ <label class="flex items-center cursor-pointer">
+ <input v-model="settingNewValue" type="radio" value="true" class="mr-2 text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
+ <span class="text-[var(--text-primary)]">Enabled</span>
+ </label>
+ <label class="flex items-center cursor-pointer">
+ <input v-model="settingNewValue" type="radio" value="false" class="mr-2 text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
+ <span class="text-[var(--text-primary)]">Disabled</span>
+ </label>
+ </div>
+
+ <!-- Integer/Float type with special handling for specific keys -->
+ <div v-else-if="editingSetting.setting_type === 'integer' || editingSetting.setting_type === 'float'" class="space-y-2">
+ <!-- Special input for transcript_length_limit -->
+ <div v-if="editingSetting.key === 'transcript_length_limit'" class="space-y-2">
+ <div class="flex items-center space-x-2">
+ <input v-model="settingUseNoLimit" type="checkbox" id="noLimit" class="rounded border-[var(--border-secondary)] text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
+ <label for="noLimit" class="text-sm text-[var(--text-secondary)]">No limit (use entire transcript)</label>
+ </div>
+ <input v-if="!settingUseNoLimit" v-model.number="settingNewValue" type="number" min="1000" step="1000"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Enter character limit (e.g., 30000)">
+ <small v-if="!settingUseNoLimit" class="text-[var(--text-muted)]">Recommended: 30000-50000 characters for most LLMs</small>
+ </div>
+
+ <!-- Special input for max_file_size_mb -->
+ <div v-else-if="editingSetting.key === 'max_file_size_mb'" class="space-y-2">
+ <input v-model.number="settingNewValue" type="number" min="1" max="10000" step="50"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Enter size in MB">
+ <small class="text-[var(--text-muted)]">Maximum file size in megabytes (1-10000 MB)</small>
+ </div>
+
+ <!-- Special input for asr_timeout_seconds -->
+ <div v-else-if="editingSetting.key === 'asr_timeout_seconds'" class="space-y-2">
+ <div class="flex space-x-2">
+ <div class="flex-1">
+ <input v-model.number="settingTimeoutMinutes" type="number" min="1" max="600" step="1"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Minutes">
+ <small class="text-[var(--text-muted)]">Minutes</small>
+ </div>
+ <div class="flex-1">
+ <input v-model.number="settingTimeoutSeconds" type="number" min="0" max="59" step="1"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Seconds">
+ <small class="text-[var(--text-muted)]">Seconds</small>
+ </div>
+ </div>
+ <div class="text-sm text-[var(--text-muted)]">
+ Total: <span class="font-medium text-[var(--text-primary)]">${ (settingTimeoutMinutes * 60 + settingTimeoutSeconds).toLocaleString() } seconds</span>
+ </div>
+ <small class="text-[var(--text-muted)]">Recommended: 30-120 minutes for long audio files</small>
+ </div>
+
+ <!-- Default number input -->
+ <input v-else v-model.number="settingNewValue" :type="editingSetting.setting_type === 'integer' ? 'number' : 'text'"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ :placeholder="`Enter ${editingSetting.setting_type} value`">
+ </div>
+
+ <!-- String type -->
+ <textarea v-else v-model="settingNewValue" rows="3"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ :placeholder="'Enter value'"></textarea>
+ </div>
+
+ <div v-if="settingError" class="p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
+ ${ settingError }
+ </div>
+ </div>
+
+ <div class="flex justify-end space-x-3 mt-6">
+ <button @click="showEditSettingModal = false"
+ class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button @click="saveSettingValue"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ Save Changes
+ </button>
+ </div>
+ </div>
+ </div>
</div>
<script>
@@ -658,6 +934,17 @@
const isProcessingRecordings = ref(false);
const processingResult = ref(null);
+ // Default Prompts state
+ const defaultSummaryPrompt = ref('');
+ const isSavingPrompt = ref(false);
+ const promptSaveMessage = ref('');
+ const promptSaveError = ref(false);
+ const showFullPromptStructure = ref(false);
+ const originalDefaultPrompt = `Generate a comprehensive summary that includes the following sections:
+- **Key Issues Discussed**: A bulleted list of the main topics
+- **Key Decisions Made**: A bulleted list of any decisions reached
+- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned`;
+
// Computed properties
const filteredUsers = computed(() => {
if (!userSearchQuery.value) return users.value;
@@ -715,16 +1002,102 @@
}
};
+ const showEditSettingModal = ref(false);
+ const editingSetting = ref(null);
+ const settingNewValue = ref('');
+ const settingUseNoLimit = ref(false);
+ const settingTimeoutMinutes = ref(30);
+ const settingTimeoutSeconds = ref(0);
+ const settingError = ref('');
+
const editSetting = (setting) => {
- // Create a prompt for editing the setting
- let newValue = prompt(
- `Edit setting: ${setting.key}\n\nDescription: ${setting.description || 'No description'}\nType: ${setting.setting_type}\nCurrent value: ${setting.value || 'Not set'}\n\nEnter new value:`,
- setting.value || ''
- );
+ editingSetting.value = { ...setting };
+ settingError.value = '';
- if (newValue !== null) {
- updateSetting(setting.key, newValue, setting.description, setting.setting_type);
+ // Initialize form values based on setting type and key
+ if (setting.key === 'transcript_length_limit') {
+ if (setting.value === '-1') {
+ settingUseNoLimit.value = true;
+ settingNewValue.value = 30000; // Default if unchecked
+ } else {
+ settingUseNoLimit.value = false;
+ settingNewValue.value = parseInt(setting.value) || 30000;
+ }
+ } else if (setting.key === 'asr_timeout_seconds') {
+ const totalSeconds = parseInt(setting.value) || 1800;
+ settingTimeoutMinutes.value = Math.floor(totalSeconds / 60);
+ settingTimeoutSeconds.value = totalSeconds % 60;
+ } else if (setting.setting_type === 'boolean') {
+ settingNewValue.value = setting.value || 'false';
+ } else {
+ settingNewValue.value = setting.value || '';
}
+
+ showEditSettingModal.value = true;
+ };
+
+ const saveSettingValue = async () => {
+ settingError.value = '';
+
+ let finalValue;
+
+ // Validate and prepare the value based on setting type
+ if (editingSetting.value.key === 'transcript_length_limit') {
+ if (settingUseNoLimit.value) {
+ finalValue = '-1';
+ } else {
+ const num = parseInt(settingNewValue.value);
+ if (isNaN(num) || num < 1000) {
+ settingError.value = 'Please enter a valid number of at least 1000 characters';
+ return;
+ }
+ finalValue = num.toString();
+ }
+ } else if (editingSetting.value.key === 'max_file_size_mb') {
+ const num = parseInt(settingNewValue.value);
+ if (isNaN(num) || num < 1 || num > 10000) {
+ settingError.value = 'Please enter a valid size between 1 and 10000 MB';
+ return;
+ }
+ finalValue = num.toString();
+ } else if (editingSetting.value.key === 'asr_timeout_seconds') {
+ const totalSeconds = (settingTimeoutMinutes.value * 60) + settingTimeoutSeconds.value;
+ if (totalSeconds < 60) {
+ settingError.value = 'Timeout must be at least 60 seconds';
+ return;
+ }
+ if (totalSeconds > 36000) {
+ settingError.value = 'Timeout cannot exceed 10 hours (36000 seconds)';
+ return;
+ }
+ finalValue = totalSeconds.toString();
+ } else if (editingSetting.value.setting_type === 'integer') {
+ const num = parseInt(settingNewValue.value);
+ if (isNaN(num)) {
+ settingError.value = 'Please enter a valid integer';
+ return;
+ }
+ finalValue = num.toString();
+ } else if (editingSetting.value.setting_type === 'float') {
+ const num = parseFloat(settingNewValue.value);
+ if (isNaN(num)) {
+ settingError.value = 'Please enter a valid number';
+ return;
+ }
+ finalValue = num.toString();
+ } else {
+ finalValue = settingNewValue.value;
+ }
+
+ // Save the setting
+ await updateSetting(
+ editingSetting.value.key,
+ finalValue,
+ editingSetting.value.description,
+ editingSetting.value.setting_type
+ );
+
+ showEditSettingModal.value = false;
};
const updateSetting = async (key, value, description, settingType) => {
@@ -978,6 +1351,69 @@
};
// Inquire Mode methods
+ // Default Prompts methods
+ const loadDefaultPrompt = async () => {
+ try {
+ // Load the admin_default_summary_prompt from settings
+ const response = await fetch('/admin/settings');
+ if (!response.ok) throw new Error('Failed to load settings');
+
+ const settings = await response.json();
+ const promptSetting = settings.find(s => s.key === 'admin_default_summary_prompt');
+ if (promptSetting) {
+ defaultSummaryPrompt.value = promptSetting.value || '';
+ }
+ } catch (error) {
+ console.error('Error loading default prompt:', error);
+ promptSaveMessage.value = 'Failed to load default prompt';
+ promptSaveError.value = true;
+ }
+ };
+
+ const saveDefaultPrompt = async () => {
+ isSavingPrompt.value = true;
+ promptSaveMessage.value = '';
+ promptSaveError.value = false;
+
+ try {
+ const response = await fetch('/admin/settings', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
+ },
+ body: JSON.stringify({
+ key: 'admin_default_summary_prompt',
+ value: defaultSummaryPrompt.value,
+ description: 'Default summarization prompt used when users have not set their own prompt. This serves as the base prompt for all users.',
+ setting_type: 'string'
+ })
+ });
+
+ if (!response.ok) throw new Error('Failed to save prompt');
+
+ promptSaveMessage.value = 'Default prompt saved successfully!';
+ promptSaveError.value = false;
+
+ // Clear message after 3 seconds
+ setTimeout(() => {
+ promptSaveMessage.value = '';
+ }, 3000);
+ } catch (error) {
+ console.error('Error saving default prompt:', error);
+ promptSaveMessage.value = 'Failed to save default prompt. Please try again.';
+ promptSaveError.value = true;
+ } finally {
+ isSavingPrompt.value = false;
+ }
+ };
+
+ const resetDefaultPrompt = () => {
+ defaultSummaryPrompt.value = originalDefaultPrompt;
+ promptSaveMessage.value = 'Prompt reset to system default. Click "Save Changes" to apply.';
+ promptSaveError.value = false;
+ };
+
const loadInquireStatus = async () => {
try {
const response = await fetch('/admin/inquire/status');
@@ -1069,6 +1505,7 @@
loadUsers();
loadStats();
initializeDarkMode();
+ loadDefaultPrompt();
if (inquireModeEnabled.value) {
loadInquireStatus();
}
@@ -1082,6 +1519,10 @@
loadStats();
} else if (newTab === 'settings') {
loadSettings();
+ } else if (newTab === 'prompts') {
+ loadDefaultPrompt();
+ } else if (newTab === 'vectorstore' && inquireModeEnabled.value) {
+ loadInquireStatus();
}
});
@@ -1105,12 +1546,29 @@
editingUser,
userToDelete,
+ // Settings modal state
+ showEditSettingModal,
+ editingSetting,
+ settingNewValue,
+ settingUseNoLimit,
+ settingTimeoutMinutes,
+ settingTimeoutSeconds,
+ settingError,
+
// Inquire Mode state
inquireModeEnabled,
inquireStatus,
isProcessingRecordings,
processingResult,
+ // Default Prompts state
+ defaultSummaryPrompt,
+ isSavingPrompt,
+ promptSaveMessage,
+ promptSaveError,
+ showFullPromptStructure,
+ originalDefaultPrompt,
+
// Computed
filteredUsers,
getProcessingProgress,
@@ -1120,6 +1578,7 @@
loadStats,
loadSettings,
editSetting,
+ saveSettingValue,
updateSetting,
formatDate,
addUser,
@@ -1134,7 +1593,12 @@
// Inquire Mode methods
loadInquireStatus,
processAllRecordings,
- processBatchRecordings
+ processBatchRecordings,
+
+ // Default Prompts methods
+ loadDefaultPrompt,
+ saveDefaultPrompt,
+ resetDefaultPrompt
};
},
delimiters: ['${', '}'] // Use different delimiters to avoid conflict with Flask's Jinja2
diff --git a/templates/index.html b/templates/index.html
index eb4460cc..e1073539 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -918,7 +918,30 @@
<i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>
<p class="text-[var(--text-muted)]">Ask questions about this transcription</p>
</div>
- <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.role === 'user' ? 'user-message ml-auto' : 'ai-message']">
+ <div v-for="(message, index) in chatMessages" :key="index"
+ :class="['message relative group', message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
+ message.role === 'assistant' ? 'pr-10' : '']">
+ <!-- Copy button for assistant messages -->
+ <button v-if="message.role === 'assistant'"
+ @click="copyMessage(message.content, $event)"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
+ title="Copy message">
+ <i class="fas fa-copy text-sm"></i>
+ </button>
+ <!-- Show thinking content if available -->
+ <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
+ <button @click="message.thinkingExpanded = !message.thinkingExpanded"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
+ <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
+ <span>Model Reasoning</span>
+ <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
+ </button>
+ <div v-if="message.thinkingExpanded"
+ class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
+ <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
+ </div>
+ </div>
+ <!-- Main message content -->
<div v-if="message.html" v-html="message.html"></div>
<div v-else class="whitespace-pre-wrap">${message.content}</div>
</div>
@@ -1348,14 +1371,27 @@
<!-- Chat Section -->
<div class="border-t border-[var(--border-primary)] flex flex-col">
<!-- Chat Toggle -->
- <button @click="showChat = !showChat"
- class="bg-[var(--bg-tertiary)] px-4 py-3 text-left hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center justify-between">
- <span class="font-medium flex items-center">
- <i class="fas fa-comments mr-2"></i>
- Chat with Transcription
- </span>
- <i :class="['fas transition-transform duration-200', showChat ? 'fa-chevron-down' : 'fa-chevron-up']"></i>
- </button>
+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center">
+ <button @click="showChat = !showChat"
+ class="flex-1 text-left flex items-center">
+ <span class="font-medium flex items-center">
+ <i class="fas fa-comments mr-2"></i>
+ Chat with Transcription
+ </span>
+ </button>
+ <div class="flex items-center gap-2">
+ <button v-if="chatMessages.length > 0"
+ @click="downloadChat"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
+ title="Download chat as Word document">
+ <i class="fas fa-download text-sm"></i>
+ </button>
+ <button @click="showChat = !showChat"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i :class="['fas transition-transform duration-200', showChat ? 'fa-chevron-down' : 'fa-chevron-up']"></i>
+ </button>
+ </div>
+ </div>
<!-- Chat Content -->
<div v-if="showChat" class="flex-1 flex flex-col min-h-0 max-h-96">
@@ -1370,17 +1406,32 @@
<div v-for="(message, index) in chatMessages"
:key="index"
:class="[
- 'message',
- message.role === 'user' ? 'user-message ml-auto' : 'ai-message'
+ 'message relative group',
+ message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
+ message.role === 'assistant' ? 'pr-10' : ''
]">
- <div class="copyable" v-if="message.role === 'assistant'">
- <button @click="copyMessage(message.content, $event)"
- class="copy-btn absolute top-2 right-2 opacity-0 group-hover:opacity-100">
- <i class="fas fa-copy"></i>
+ <!-- Copy button for assistant messages -->
+ <button v-if="message.role === 'assistant'"
+ @click="copyMessage(message.content, $event)"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
+ title="Copy message">
+ <i class="fas fa-copy text-sm"></i>
+ </button>
+ <!-- Show thinking content if available -->
+ <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
+ <button @click="message.thinkingExpanded = !message.thinkingExpanded"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
+ <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
+ <span>Model Reasoning</span>
+ <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
</button>
- <div v-if="message.html" v-html="message.html"></div>
- <div v-else class="whitespace-pre-wrap">${message.content}</div>
+ <div v-if="message.thinkingExpanded"
+ class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
+ <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
+ </div>
</div>
+ <!-- Main message content -->
+ <div v-if="message.html" v-html="message.html"></div>
<div v-else class="whitespace-pre-wrap">${message.content}</div>
</div>
@@ -1419,7 +1470,7 @@
</div>
<!-- Empty State -->
- <div v-else class="flex-1 flex items-center justify-center">
+ <div v-else-if="currentView === 'detail' && !selectedRecording" class="flex-1 flex items-center justify-center">
<div class="text-center">
<i class="fas fa-microphone text-6xl text-[var(--text-muted)] mb-4"></i>
<h2 class="text-2xl font-bold mb-2">Select a Recording</h2>