Skip to content

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

Python

Improve summarization prompt handling and UI navigation

Murtaza Nasir7bd424595e8c
diff --git a/app.py b/app.py
index 438c636e..761f9221 100644
--- a/app.py
+++ b/app.py
@@ -8,7 +8,7 @@ try:
except ImportError:
from markupsafe import Markup
from flask_sqlalchemy import SQLAlchemy
-from datetime import datetime
+from datetime import datetime, timedelta
from openai import OpenAI # Keep using the OpenAI library
import json
from werkzeug.utils import secure_filename
@@ -1526,7 +1526,17 @@ TEXT_MODEL_API_KEY = os.environ.get("TEXT_MODEL_API_KEY")
TEXT_MODEL_BASE_URL = os.environ.get("TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")
TEXT_MODEL_NAME = os.environ.get("TEXT_MODEL_NAME", "openai/gpt-3.5-turbo") # Default if not set
-http_client_no_proxy = httpx.Client(verify=True) # verify=True is default, but good to be explicit
+# Set up HTTP client with custom headers for OpenRouter app identification
+app_headers = {
+ "HTTP-Referer": "https://github.com/murtaza-nasir/speakr", # Your app's repo URL for OpenRouter visibility
+ "X-Title": "Speakr - AI Audio Transcription", # Your app name for OpenRouter visibility
+ "User-Agent": "Speakr/1.0 (https://github.com/murtaza-nasir/speakr)" # Custom user agent for better tracking
+}
+
+http_client_no_proxy = httpx.Client(
+ verify=True,
+ headers=app_headers
+)
try:
# Always attempt to create client - use API key if provided, otherwise use placeholder
@@ -1537,10 +1547,52 @@ try:
http_client=http_client_no_proxy
)
app.logger.info(f"LLM client initialized for endpoint: {TEXT_MODEL_BASE_URL}. Using model: {TEXT_MODEL_NAME}")
+ if "openrouter" in TEXT_MODEL_BASE_URL.lower():
+ app.logger.info("OpenRouter integration: App identification headers added for visibility in logs")
except Exception as client_init_e:
app.logger.error(f"Failed to initialize LLM client: {client_init_e}", exc_info=True)
client = None
+def call_llm_completion(messages, temperature=0.7, response_format=None, stream=False, max_tokens=None):
+ """
+ Centralized function for LLM API calls with proper error handling and logging.
+
+ Args:
+ messages: List of message dicts with 'role' and 'content'
+ temperature: Sampling temperature (0-1)
+ response_format: Optional response format dict (e.g., {"type": "json_object"})
+ stream: Whether to stream the response
+ max_tokens: Optional maximum tokens to generate
+
+ Returns:
+ OpenAI completion object or generator (if streaming)
+ """
+ if not client:
+ raise ValueError("LLM client not initialized")
+
+ if not TEXT_MODEL_API_KEY:
+ raise ValueError("TEXT_MODEL_API_KEY not configured")
+
+ try:
+ completion_args = {
+ "model": TEXT_MODEL_NAME,
+ "messages": messages,
+ "temperature": temperature,
+ "stream": stream
+ }
+
+ if response_format:
+ completion_args["response_format"] = response_format
+
+ if max_tokens:
+ completion_args["max_tokens"] = max_tokens
+
+ return client.chat.completions.create(**completion_args)
+
+ except Exception as e:
+ app.logger.error(f"LLM API call failed: {e}")
+ raise
+
# Store details for the transcription client (potentially different)
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")
@@ -1694,8 +1746,7 @@ Title:"""
try:
- completion = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ completion = call_llm_completion(
messages=[
{"role": "system", "content": system_message_content},
{"role": "user", "content": prompt_text}
@@ -1799,14 +1850,13 @@ def generate_summary_only_task(app_context, recording_id):
tag_custom_prompt = tag_custom_prompts[0]['prompt']
app.logger.info(f"Using single custom prompt from tag '{tag_custom_prompts[0]['name']}' for recording {recording_id}")
else:
- # Merge multiple prompts with clear separation, preserving the order tags were added
+ # Merge multiple prompts seamlessly as unified instructions
merged_parts = []
- for i, tag_prompt in enumerate(tag_custom_prompts, 1):
- ordinal = {1: '1st', 2: '2nd', 3: '3rd'}.get(i, f'{i}th')
- merged_parts.append(f"{i}. From tag '{tag_prompt['name']}' (added {ordinal}):\n{tag_prompt['prompt']}")
+ for tag_prompt in tag_custom_prompts:
+ merged_parts.append(tag_prompt['prompt'])
tag_custom_prompt = "\n\n".join(merged_parts)
tag_names = [tp['name'] for tp in tag_custom_prompts]
- app.logger.info(f"Merged custom prompts from {len(tag_custom_prompts)} tags in order added ({', '.join(tag_names)}) for recording {recording_id}")
+ app.logger.info(f"Combined custom prompts from {len(tag_custom_prompts)} tags in order added ({', '.join(tag_names)}) for recording {recording_id}")
else:
tag_custom_prompt = None
@@ -1826,58 +1876,63 @@ def generate_summary_only_task(app_context, recording_id):
language_directive = f"Please provide the summary in {user_output_language}." if user_output_language else ""
+ # Build system message with summarization instructions
+ system_message_content = "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."
+ if user_output_language:
+ 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
if tag_custom_prompt:
app.logger.info(f"Using tag custom prompt for recording {recording_id}")
- prompt_text = f"""Analyze the following audio transcription and generate a summary according to the following instructions.
-
-Instructions: {tag_custom_prompt}
-
-Transcription:
-\"\"\"
-{transcript_text}
-\"\"\"
-
-{language_directive}
-
-Respond with only the summary in Markdown format. Do NOT wrap your response in markdown code blocks (```markdown). Provide the markdown content directly without any code block formatting."""
-
+ system_message_content += f"\n\nSummarization Instructions:\n{tag_custom_prompt}"
elif user_summary_prompt:
app.logger.info(f"Using user custom prompt for recording {recording_id}")
- prompt_text = f"""Analyze the following audio transcription and generate a summary according to the following instructions.
-
-Instructions: {user_summary_prompt}
-
-Transcription:
-\"\"\"
-{transcript_text}
-\"\"\"
-
-{language_directive}
-
-Respond with only the summary in Markdown format. Do NOT wrap your response in markdown code blocks (```markdown). Provide the markdown content directly without any code block formatting."""
-
+ system_message_content += f"\n\nSummarization Instructions:\n{user_summary_prompt}"
else:
- # Default summary prompt
- prompt_text = f"""Analyze the following audio transcription and generate a detailed, well-structured summary in Markdown format.
+ # Default summary instructions
+ 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}"
+
+ # Build user prompt with context information
+ current_date = datetime.now().strftime("%B %d, %Y")
+
+ # Build context information
+ context_parts = []
+ context_parts.append(f"Current date: {current_date}")
+
+ # Add selected tags information
+ if recording.tags:
+ tag_names = [tag.name for tag in recording.tags]
+ context_parts.append(f"Tags applied to this transcript by the user: {', '.join(tag_names)}")
+
+ # Add user profile information if available
+ if recording.owner:
+ user_context_parts = []
+ if recording.owner.name:
+ user_context_parts.append(f"Name: {recording.owner.name}")
+ if recording.owner.job_title:
+ user_context_parts.append(f"Job title: {recording.owner.job_title}")
+ if recording.owner.company:
+ user_context_parts.append(f"Company: {recording.owner.company}")
+
+ if user_context_parts:
+ context_parts.append(f"Information about the user: {', '.join(user_context_parts)}")
+
+ # Combine context and transcript
+ context_section = "Context:\n" + "\n".join(f"- {part}" for part in context_parts)
+
+ prompt_text = f"""{context_section}
Transcription:
\"\"\"
{transcript_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
-
-{language_directive}
-
-Respond with only the summary in Markdown format. Do NOT wrap your response in markdown code blocks (```markdown). Provide the markdown content directly without any code block formatting."""
-
- system_message_content = "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."
- if user_output_language:
- system_message_content += f" Ensure your response is in {user_output_language}."
+Please analyze the above transcription and generate a summary following the provided instructions."""
# Debug logging: Log the complete prompt being sent to the LLM
app.logger.info(f"Sending summarization prompt to LLM (length: {len(prompt_text)} chars). Set LOG_LEVEL=DEBUG to see full prompt details.")
@@ -1887,8 +1942,7 @@ Respond with only the summary in Markdown format. Do NOT wrap your response in m
app.logger.debug(f"=== END SUMMARIZATION DEBUG for recording {recording_id} ===")
try:
- completion = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ completion = call_llm_completion(
messages=[
{"role": "system", "content": system_message_content},
{"role": "user", "content": prompt_text}
@@ -1922,8 +1976,12 @@ Respond with only the summary in Markdown format. Do NOT wrap your response in m
recording.status = 'FAILED'
db.session.commit()
-def extract_audio_from_video(video_filepath, output_format='wav', cleanup_original=True):
- """Extract audio from video containers using FFmpeg."""
+def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_original=True):
+ """Extract audio from video containers using FFmpeg.
+
+ Uses MP3 codec for optimal compatibility and predictable file sizes.
+ 64kbps MP3 provides good speech quality at ~480KB per minute.
+ """
try:
# Generate output filename with audio extension
base_filepath, file_ext = os.path.splitext(video_filepath)
@@ -1932,18 +1990,26 @@ def extract_audio_from_video(video_filepath, output_format='wav', cleanup_origin
app.logger.info(f"Extracting audio from video: {video_filepath} -> {temp_audio_filepath}")
- # Extract audio using FFmpeg - optimized for transcription
+ # Extract audio using FFmpeg - using MP3 for consistency with chunking
subprocess.run([
'ffmpeg', '-i', video_filepath, '-y',
'-vn', # No video
- '-acodec', 'pcm_s16le', # Uncompressed audio for best quality
- '-ar', '16000', # 16kHz sample rate (good for speech)
- '-ac', '1', # Mono
+ '-codec:a', 'libmp3lame', # Use LAME MP3 encoder explicitly
+ '-b:a', '64k', # 64kbps bitrate (better quality than chunking's 32k, still small)
+ '-ar', '22050', # 22.05kHz sample rate (good for speech, better than 16kHz)
+ '-ac', '1', # Mono (sufficient for speech, reduces file size)
+ '-compression_level', '2', # Better compression
temp_audio_filepath
], check=True, capture_output=True, text=True)
app.logger.info(f"Successfully extracted audio to {temp_audio_filepath}")
+ # Optionally preserve temp file for debugging (set PRESERVE_TEMP_AUDIO=true in env)
+ if os.getenv('PRESERVE_TEMP_AUDIO', 'false').lower() == 'true':
+ import shutil
+ shutil.copy2(temp_audio_filepath, temp_audio_filepath.replace('_temp', '_debug'))
+ app.logger.info(f"Debug: Preserved temp audio file as {temp_audio_filepath.replace('_temp', '_debug')}")
+
# Rename temp file to final filename
os.rename(temp_audio_filepath, final_audio_filepath)
@@ -2002,7 +2068,7 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,
app.logger.info(f"Video container detected ({actual_content_type}), extracting audio...")
try:
# Extract audio from video
- audio_filepath, audio_mime_type = extract_audio_from_video(filepath, 'wav')
+ audio_filepath, audio_mime_type = extract_audio_from_video(filepath, 'mp3')
# Update paths and MIME type for ASR processing
actual_filepath = audio_filepath
@@ -2132,17 +2198,9 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,
# Generate title immediately
generate_title_task(app_context, recording_id)
- # Only auto-generate summary if recording has a tag with custom prompt
- should_auto_summarize = False
- if recording.tags:
- for tag in recording.tags:
- if tag.custom_prompt:
- should_auto_summarize = True
- app.logger.info(f"Auto-generating summary for recording {recording_id} due to tag '{tag.name}' with custom prompt")
- break
-
- if should_auto_summarize:
- generate_summary_only_task(app_context, recording_id)
+ # Always auto-generate summary for all recordings
+ app.logger.info(f"Auto-generating summary for recording {recording_id}")
+ generate_summary_only_task(app_context, recording_id)
except Exception as e:
db.session.rollback()
@@ -2235,17 +2293,9 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,
# Generate title immediately
generate_title_task(app_context, recording_id)
- # Only auto-generate summary if recording has a tag with custom prompt
- should_auto_summarize = False
- if recording.tags:
- for tag in recording.tags:
- if tag.custom_prompt:
- should_auto_summarize = True
- app.logger.info(f"Auto-generating summary for recording {recording_id} due to tag '{tag.name}' with custom prompt")
- break
-
- if should_auto_summarize:
- generate_summary_only_task(app_context, recording_id)
+ # Always auto-generate summary for all recordings
+ app.logger.info(f"Auto-generating summary for recording {recording_id}")
+ generate_summary_only_task(app_context, recording_id)
except Exception as e:
db.session.rollback() # Rollback if any step failed critically
@@ -3064,8 +3114,7 @@ JSON Response:
"""
try:
- completion = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ completion = call_llm_completion(
messages=[
{"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers. Your response must be a single, valid JSON object."},
{"role": "user", "content": prompt}
@@ -3136,8 +3185,7 @@ JSON Response:
"""
try:
- completion = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ completion = call_llm_completion(
messages=[
{"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers based on contextual clues in the dialogue. Analyze the conversation carefully to find names mentioned when speakers address each other or introduce themselves. Your response must be a single, valid JSON object containing only the requested speaker identifications."},
{"role": "user", "content": prompt}
@@ -3286,8 +3334,7 @@ Additional context and notes about the meeting:
def generate():
try:
# Enable streaming
- stream = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ stream = call_llm_completion(
messages=messages,
temperature=0.7,
max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),
@@ -3498,216 +3545,8 @@ def reprocess_summary(recording_id):
# Start summary generation in background thread
def reprocess_summary_task(app_context, recording_id):
- with app_context:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- app.logger.error(f"Recording {recording_id} not found during summary reprocessing")
- return
-
- try:
- # Get user preferences
- 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
-
- # Prepare prompt (same logic as in transcribe_audio_task)
- default_summary_prompt = """Analyze the following audio transcription and generate a concise title and a brief summary.
-
-Transcription:
-\"\"\"
-{transcription}
-\"\"\"
-
-Respond STRICTLY with a JSON object containing two keys: "title" (a short, descriptive title, max 6 words without using words introductory words and phrases like brief, "discussion on", "Meeting about" etc.) and "minutes" (a paragraph summarizing the key points, max 150 words). The title should get to the point without inroductory phrases as we have very little space to show the title.
-{language_directive}
-Example Format:
-{{
- "title": "Q3 Results for SPERO Program",
- "summary": "### Minutes
-
-**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.
-"
-}}
-
-JSON Response:"""
-
- language_directive = f"Please provide the title and summary in {user_output_language}." if user_output_language else ""
-
- # Format transcription for LLM (convert JSON to clean text format like clipboard copy)
- formatted_transcription = format_transcription_for_llm(recording.transcription)
-
- # Get configurable transcript length limit for reprocessing
- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
- if transcript_limit == -1:
- # No limit
- transcript_text = formatted_transcription
- else:
- transcript_text = formatted_transcription[:transcript_limit]
-
- 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.
-
-Transcription:
-\"\"\"
-{transcript_text}
-\"\"\"
-
-Generate a response STRICTLY as a JSON object with two keys: "title" and "summary". The summary should be markdown content (do NOT wrap in ```markdown code blocks), not JSON.
-
-For the "title": create a short, descriptive title (max 6 words, no introductory phrases like "brief", "discussion on", "Meeting about").
-For the "summary": {user_summary_prompt}.
-
-{language_directive}
-
-JSON Response:"""
- else:
- prompt_text = default_summary_prompt.format(transcription=transcript_text, 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}."
-
- # Debug logging: Log the complete prompt being sent to the LLM
- app.logger.info(f"Making OpenRouter API request for summary reprocessing {recording_id}")
- app.logger.info(f"Sending reprocess summary prompt to LLM (length: {len(prompt_text)} chars). Set LOG_LEVEL=DEBUG to see full prompt details.")
- app.logger.debug(f"=== REPROCESS SUMMARY DEBUG for recording {recording_id} ===")
- app.logger.debug(f"Model: {TEXT_MODEL_NAME}")
- app.logger.debug(f"System message: {system_message_content}")
- app.logger.debug(f"User prompt (length: {len(prompt_text)} chars):\n{prompt_text}")
- app.logger.debug(f"=== END REPROCESS SUMMARY DEBUG for recording {recording_id} ===")
-
- # Call OpenRouter API
- 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"}
- )
-
- app.logger.info(f"OpenRouter API request completed for summary reprocessing {recording_id}")
-
- response_content = completion.choices[0].message.content
- app.logger.debug(f"Raw OpenRouter response for summary reprocessing {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 summary reprocessing {recording_id}")
- recording.summary = "[AI summary generation failed: Empty response from API]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return
-
- # Parse response (same logic as in transcribe_audio_task)
- json_match = re.search(r'```(?:json)?(.*?)```|(.+)', response_content, re.DOTALL)
-
- if json_match:
- 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 summary reprocessing {recording_id}: '{sanitized_response}'")
- recording.summary = "[AI summary generation failed: Invalid JSON response]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return
-
- summary_data = safe_json_loads(sanitized_response, {})
-
- # 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 summary reprocessing {recording_id}: {summary_data}")
- recording.summary = "[AI summary generation failed: Empty response structure]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return
-
- # Debug log the parsed response
- app.logger.debug(f"Parsed summary data for reprocessing {recording_id}: {summary_data}")
-
- raw_title = summary_data.get("title")
- raw_summary = summary_data.get("summary")
-
- # Log what we got from the response
- app.logger.debug(f"Raw title for reprocessing {recording_id}: {raw_title}")
- app.logger.debug(f"Raw summary for reprocessing {recording_id}: {raw_summary}")
-
- # 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 summary reprocessing {recording_id}.")
- else:
- processed_title = "[Title generation error: Unexpected format]"
- app.logger.warning(f"Title had unexpected format for summary reprocessing {recording_id}: {type(raw_title)}. Content: {raw_title}")
-
- # Process summary
- if isinstance(raw_summary, str):
- processed_summary = raw_summary.strip()
- elif isinstance(raw_summary, dict):
- processed_summary = json.dumps(raw_summary, indent=2)
- app.logger.info(f"Generated summary for reprocessing {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 summary reprocessing {recording_id}.")
- else:
- processed_summary = "[Summary generation error: Unexpected format]"
- app.logger.warning(f"Summary had unexpected format for summary reprocessing {recording_id}: {type(raw_summary)}. Content: {raw_summary}")
-
- # Check if both title and summary are valid before updating
- if raw_title is not None and raw_summary is not None:
- recording.title = processed_title
- recording.summary = processed_summary
- recording.status = 'COMPLETED'
- app.logger.info(f"Summary reprocessing completed successfully for recording {recording_id}")
- else:
- # Handle cases where one or both keys might be missing
- if raw_title is None:
- recording.title = recording.title or "[Title not generated]" # Keep existing if any
- else:
- recording.title = processed_title
-
- 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 summary reprocessing {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
-
- db.session.commit()
-
- except json.JSONDecodeError as json_e:
- app.logger.error(f"Failed to parse JSON response from OpenRouter for summary reprocessing {recording_id}: {json_e}. Response: {sanitized_response}")
- recording.summary = f"[AI summary generation failed: Invalid JSON response ({json_e})]"
- recording.status = 'COMPLETED'
- db.session.commit()
-
- except Exception as summary_e:
- app.logger.error(f"Error during summary reprocessing for recording {recording_id}: {str(summary_e)}")
- recording.summary = format_api_error_message(str(summary_e))
- recording.status = 'COMPLETED'
- db.session.commit()
+ app.logger.info(f"Starting summary reprocessing for recording {recording_id} using generate_summary_only_task")
+ generate_summary_only_task(app_context, recording_id)
thread = threading.Thread(
target=reprocess_summary_task,
@@ -4228,14 +4067,34 @@ def get_config():
# Get configurable file size limit
max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
+ # Get chunking configuration (supports both legacy and new formats)
+ chunking_info = {}
+ if ENABLE_CHUNKING and chunking_service:
+ mode, limit_value = chunking_service.parse_chunk_limit()
+ chunking_info = {
+ 'chunking_enabled': True,
+ 'chunking_mode': mode, # 'size' or 'duration'
+ 'chunking_limit': limit_value, # Value in MB or seconds
+ 'chunking_limit_display': f"{limit_value}{'MB' if mode == 'size' else 's'}"
+ }
+ else:
+ chunking_info = {
+ 'chunking_enabled': False,
+ 'chunking_mode': 'size',
+ 'chunking_limit': 20,
+ 'chunking_limit_display': '20MB'
+ }
+
return jsonify({
'max_file_size_mb': max_file_size_mb,
- 'use_asr_endpoint': USE_ASR_ENDPOINT
+ 'use_asr_endpoint': USE_ASR_ENDPOINT,
+ **chunking_info
})
except Exception as e:
app.logger.error(f"Error fetching configuration: {e}")
return jsonify({'error': str(e)}), 500
+
@app.route('/api/csrf-token', methods=['GET'])
@csrf.exempt # Exempt this endpoint from CSRF protection since it's providing tokens
def get_csrf_token():
@@ -4281,6 +4140,217 @@ def get_recordings():
app.logger.error(f"Error fetching recordings: {e}")
return jsonify({'error': str(e)}), 500
[email protected]('/api/recordings', methods=['GET'])
+@login_required
[email protected]("1250 per hour")
+def get_recordings_paginated():
+ """Get recordings with pagination and server-side filtering."""
+ try:
+ # Parse query parameters
+ page = request.args.get('page', 1, type=int)
+ per_page = min(request.args.get('per_page', 25, type=int), 100) # Cap at 100 per page
+ search_query = request.args.get('q', '').strip()
+
+ # Build base query
+ stmt = select(Recording).where(Recording.user_id == current_user.id)
+
+ # Apply search filters if provided
+ if search_query:
+ # Parse search query for special syntax
+ import re
+
+ # Extract date filters
+ date_filters = re.findall(r'date:(\S+)', search_query.lower())
+ tag_filters = re.findall(r'tag:(\S+)', search_query.lower())
+
+ # Remove special syntax to get text search
+ text_query = re.sub(r'date:\S+', '', search_query, flags=re.IGNORECASE)
+ text_query = re.sub(r'tag:\S+', '', text_query, flags=re.IGNORECASE).strip()
+
+ # Apply date filters
+ for date_filter in date_filters:
+ if date_filter == 'today':
+ today = datetime.now().date()
+ stmt = stmt.where(
+ db.or_(
+ db.func.date(Recording.meeting_date) == today,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) == today
+ )
+ )
+ )
+ elif date_filter == 'yesterday':
+ yesterday = datetime.now().date() - timedelta(days=1)
+ stmt = stmt.where(
+ db.or_(
+ db.func.date(Recording.meeting_date) == yesterday,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) == yesterday
+ )
+ )
+ )
+ elif date_filter == 'thisweek':
+ today = datetime.now().date()
+ start_of_week = today - timedelta(days=today.weekday())
+ stmt = stmt.where(
+ db.or_(
+ Recording.meeting_date >= start_of_week,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= start_of_week
+ )
+ )
+ )
+ elif date_filter == 'lastweek':
+ today = datetime.now().date()
+ end_of_last_week = today - timedelta(days=today.weekday())
+ start_of_last_week = end_of_last_week - timedelta(days=7)
+ stmt = stmt.where(
+ db.or_(
+ db.and_(
+ Recording.meeting_date >= start_of_last_week,
+ Recording.meeting_date < end_of_last_week
+ ),
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= start_of_last_week,
+ db.func.date(Recording.created_at) < end_of_last_week
+ )
+ )
+ )
+ elif date_filter == 'thismonth':
+ today = datetime.now().date()
+ start_of_month = today.replace(day=1)
+ stmt = stmt.where(
+ db.or_(
+ Recording.meeting_date >= start_of_month,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= start_of_month
+ )
+ )
+ )
+ elif date_filter == 'lastmonth':
+ today = datetime.now().date()
+ first_day_this_month = today.replace(day=1)
+ last_day_last_month = first_day_this_month - timedelta(days=1)
+ first_day_last_month = last_day_last_month.replace(day=1)
+ stmt = stmt.where(
+ db.or_(
+ db.and_(
+ Recording.meeting_date >= first_day_last_month,
+ Recording.meeting_date <= last_day_last_month
+ ),
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= first_day_last_month,
+ db.func.date(Recording.created_at) <= last_day_last_month
+ )
+ )
+ )
+ elif re.match(r'^\d{4}-\d{2}-\d{2}$', date_filter):
+ # Specific date format YYYY-MM-DD
+ target_date = datetime.strptime(date_filter, '%Y-%m-%d').date()
+ stmt = stmt.where(
+ db.or_(
+ db.func.date(Recording.meeting_date) == target_date,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) == target_date
+ )
+ )
+ )
+ elif re.match(r'^\d{4}-\d{2}$', date_filter):
+ # Month format YYYY-MM
+ year, month = map(int, date_filter.split('-'))
+ stmt = stmt.where(
+ db.or_(
+ db.and_(
+ db.extract('year', Recording.meeting_date) == year,
+ db.extract('month', Recording.meeting_date) == month
+ ),
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.extract('year', Recording.created_at) == year,
+ db.extract('month', Recording.created_at) == month
+ )
+ )
+ )
+ elif re.match(r'^\d{4}$', date_filter):
+ # Year format YYYY
+ year = int(date_filter)
+ stmt = stmt.where(
+ db.or_(
+ db.extract('year', Recording.meeting_date) == year,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.extract('year', Recording.created_at) == year
+ )
+ )
+ )
+
+ # Apply tag filters
+ if tag_filters:
+ # Join with tags table and filter by tag names
+ tag_conditions = []
+ for tag_filter in tag_filters:
+ tag_conditions.append(Tag.name.ilike(f'%{tag_filter}%'))
+
+ stmt = stmt.join(RecordingTag).join(Tag).where(db.or_(*tag_conditions))
+
+ # Apply text search
+ if text_query:
+ text_conditions = [
+ Recording.title.ilike(f'%{text_query}%'),
+ Recording.participants.ilike(f'%{text_query}%'),
+ Recording.transcription.ilike(f'%{text_query}%'),
+ Recording.notes.ilike(f'%{text_query}%')
+ ]
+ stmt = stmt.where(db.or_(*text_conditions))
+
+ # Apply ordering (most recent first based on meeting_date or created_at)
+ stmt = stmt.order_by(
+ db.case(
+ (Recording.meeting_date.is_not(None), Recording.meeting_date),
+ else_=db.func.date(Recording.created_at)
+ ).desc(),
+ Recording.created_at.desc()
+ )
+
+ # Get total count for pagination info
+ count_stmt = select(db.func.count()).select_from(stmt.subquery())
+ total_count = db.session.execute(count_stmt).scalar()
+
+ # Apply pagination
+ offset = (page - 1) * per_page
+ stmt = stmt.offset(offset).limit(per_page)
+
+ # Execute query
+ recordings = db.session.execute(stmt).scalars().all()
+
+ # Calculate pagination metadata
+ total_pages = (total_count + per_page - 1) // per_page
+ has_next = page < total_pages
+ has_prev = page > 1
+
+ return jsonify({
+ 'recordings': [recording.to_dict() for recording in recordings],
+ 'pagination': {
+ 'page': page,
+ 'per_page': per_page,
+ 'total': total_count,
+ 'total_pages': total_pages,
+ 'has_next': has_next,
+ 'has_prev': has_prev
+ }
+ })
+
+ except Exception as e:
+ app.logger.error(f"Error fetching paginated recordings: {e}")
+ return jsonify({'error': str(e)}), 500
+
@app.route('/api/inbox_recordings', methods=['GET'])
@login_required
@limiter.limit("1250 per hour") # Allow frequent polling for inbox recordings
@@ -4936,8 +5006,7 @@ Examples:
- "Make this more structured" → DIRECT"""
try:
- router_response = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ router_response = call_llm_completion(
messages=[
{"role": "system", "content": "You are a query router. Respond with only 'RAG' or 'DIRECT'."},
{"role": "user", "content": router_prompt}
@@ -4962,8 +5031,7 @@ Previous conversation context (if relevant):
Use proper markdown formatting including headings (##), bold (**text**), bullet points (-), etc."""
- stream = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ stream = call_llm_completion(
messages=[
{"role": "system", "content": direct_prompt},
{"role": "user", "content": user_message}
@@ -5013,8 +5081,7 @@ Examples:
Respond with only a JSON array of strings: ["term1", "term2", "term3", ...]"""
try:
- enrichment_response = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ enrichment_response = call_llm_completion(
messages=[
{"role": "system", "content": "You are a query enhancement assistant. Respond only with valid JSON arrays of search terms."},
{"role": "user", "content": enrichment_prompt}
@@ -5309,8 +5376,7 @@ Order your response with notes from the most recent meetings first. Always use p
messages.append({"role": "user", "content": user_message})
# Enable streaming
- stream = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ stream = call_llm_completion(
messages=messages,
temperature=0.7,
max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),
@@ -5365,8 +5431,7 @@ Order your response with notes from the most recent meetings first. Always use p
# Generate new response with full context
yield create_status_response('responding', 'Analyzing full transcript...')
- new_stream = client.chat.completions.create(
- model=TEXT_MODEL_NAME,
+ new_stream = call_llm_completion(
messages=updated_messages,
temperature=0.7,
max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),
diff --git a/audio_chunking.py b/audio_chunking.py
index 5e610c2f..71772650 100644
--- a/audio_chunking.py
+++ b/audio_chunking.py
@@ -104,54 +104,67 @@ class AudioChunkingService:
logger.error(f"Error getting audio duration for {file_path}: {e}")
return None
- def convert_to_wav_and_get_info(self, file_path: str, temp_dir: str) -> Tuple[str, float, float]:
+ def convert_to_mp3_and_get_info(self, file_path: str, temp_dir: str) -> Tuple[str, float, float]:
"""
- Convert the input file to WAV format and get its size and duration info.
+ Convert the input file to MP3 format for consistency and get its size and duration info.
Args:
file_path: Path to the source audio file
- temp_dir: Directory to store the temporary WAV file
+ temp_dir: Directory to store the temporary MP3 file
Returns:
- Tuple of (wav_file_path, duration_seconds, size_bytes)
+ Tuple of (mp3_file_path, duration_seconds, size_bytes)
"""
try:
- # Generate WAV filename
+ # Generate MP3 filename
base_name = os.path.splitext(os.path.basename(file_path))[0]
- wav_filename = f"{base_name}_converted.wav"
- wav_path = os.path.join(temp_dir, wav_filename)
+ mp3_filename = f"{base_name}_converted.mp3"
+ mp3_path = os.path.join(temp_dir, mp3_filename)
- # Convert to 32kbps MP3 using the same settings we use for chunks
+ # Convert to 64kbps MP3 using better quality settings
cmd = [
'ffmpeg', '-i', file_path,
- '-acodec', 'mp3',
- '-ab', '32k',
- '-ar', '16000',
- '-ac', '1',
+ '-codec:a', 'libmp3lame', # Use LAME MP3 encoder explicitly
+ '-b:a', '64k', # 64kbps bitrate for better quality
+ '-ar', '22050', # 22.05kHz sample rate (better than 16kHz)
+ '-ac', '1', # Mono (sufficient for speech)
+ '-compression_level', '2', # Better compression
'-y', # Overwrite output file
- wav_path
+ mp3_path
]
- logger.info(f"Converting {file_path} to 32kbps MP3 format for accurate chunking...")
+ logger.info(f"Converting {file_path} to 64kbps MP3 format for accurate chunking...")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise ValueError(f"ffmpeg conversion failed: {result.stderr}")
- if not os.path.exists(wav_path):
- raise ValueError("WAV file was not created")
+ if not os.path.exists(mp3_path):
+ raise ValueError("MP3 file was not created")
- # Get the size and duration of the converted WAV file
- wav_size = os.path.getsize(wav_path)
- wav_duration = self.get_audio_duration(wav_path)
+ # Get the size and duration of the converted MP3 file
+ mp3_size = os.path.getsize(mp3_path)
+ mp3_duration = self.get_audio_duration(mp3_path)
- if not wav_duration:
- raise ValueError("Could not determine WAV file duration")
+ if not mp3_duration:
+ raise ValueError("Could not determine MP3 file duration")
- logger.info(f"Converted WAV: {wav_size/1024/1024:.1f}MB, {wav_duration:.1f}s")
- return wav_path, wav_duration, wav_size
+ logger.info(f"Converted MP3: {mp3_size/1024/1024:.1f}MB, {mp3_duration:.1f}s")
+
+ # Optionally preserve converted file for debugging (set PRESERVE_CHUNK_DEBUG=true in env)
+ if os.getenv('PRESERVE_CHUNK_DEBUG', 'false').lower() == 'true':
+ import shutil
+ # Save debug files in /data/uploads/debug/ directory
+ debug_dir = '/data/uploads/debug'
+ os.makedirs(debug_dir, exist_ok=True)
+ debug_filename = os.path.basename(mp3_path).replace('_converted', '_converted_debug')
+ debug_path = os.path.join(debug_dir, debug_filename)
+ shutil.copy2(mp3_path, debug_path)
+ logger.info(f"Debug: Preserved converted file as {debug_path}")
+
+ return mp3_path, mp3_duration, mp3_size
except Exception as e:
- logger.error(f"Error converting file to WAV: {e}")
+ logger.error(f"Error converting file to MP3: {e}")
raise
def parse_chunk_limit(self) -> Tuple[str, float]:
@@ -256,8 +269,8 @@ class AudioChunkingService:
"""
Split audio file into overlapping chunks.
- First converts the file to WAV format to get accurate size information,
- then calculates optimal chunk duration based on the actual WAV file size.
+ First converts the file to MP3 format to get accurate size information,
+ then calculates optimal chunk duration based on the actual MP3 file size.
Args:
file_path: Path to the source audio file
@@ -270,46 +283,46 @@ class AudioChunkingService:
wav_path = None
try:
- # Step 1: Convert to WAV and get accurate size/duration info
- wav_path, wav_duration, wav_size = self.convert_to_wav_and_get_info(file_path, temp_dir)
+ # Step 1: Convert to MP3 and get accurate size/duration info
+ mp3_path, mp3_duration, mp3_size = self.convert_to_mp3_and_get_info(file_path, temp_dir)
# Step 2: Calculate optimal chunking strategy
- num_chunks, chunk_duration = self.calculate_optimal_chunking(wav_size, wav_duration)
+ num_chunks, chunk_duration = self.calculate_optimal_chunking(mp3_size, mp3_duration)
# If only 1 chunk needed, no actual chunking required
if num_chunks == 1:
- logger.info(f"File duration {wav_duration:.1f}s is within limit - no chunking needed")
+ logger.info(f"File duration {mp3_duration:.1f}s is within limit - no chunking needed")
# Return the single "chunk" as the whole file
base_name = os.path.splitext(os.path.basename(file_path))[0]
- chunk_filename = f"{base_name}_chunk_000.wav"
+ chunk_filename = f"{base_name}_chunk_000.mp3"
chunk_path = os.path.join(temp_dir, chunk_filename)
# Copy the converted file as the single chunk
import shutil
- shutil.copy2(wav_path, chunk_path)
+ shutil.copy2(mp3_path, chunk_path)
chunk_info = {
'index': 0,
'path': chunk_path,
'filename': chunk_filename,
'start_time': 0,
- 'end_time': wav_duration,
- 'duration': wav_duration,
- 'size_bytes': wav_size,
- 'size_mb': wav_size / (1024 * 1024)
+ 'end_time': mp3_duration,
+ 'duration': mp3_duration,
+ 'size_bytes': mp3_size,
+ 'size_mb': mp3_size / (1024 * 1024)
}
chunks.append(chunk_info)
- logger.info(f"Created single chunk for entire file: {wav_duration:.1f}s")
+ logger.info(f"Created single chunk for entire file: {mp3_duration:.1f}s")
return chunks
# Calculate step size to create exactly num_chunks with overlap
- # Total coverage needed: wav_duration + (overlap * (num_chunks - 1))
+ # Total coverage needed: mp3_duration + (overlap * (num_chunks - 1))
# Each chunk covers: chunk_duration
# Step between chunks to get exactly num_chunks
if num_chunks > 1:
- step_duration = (wav_duration - chunk_duration) / (num_chunks - 1)
+ step_duration = (mp3_duration - chunk_duration) / (num_chunks - 1)
else:
- step_duration = wav_duration
+ step_duration = mp3_duration
current_start = 0
chunk_index = 0
@@ -322,7 +335,7 @@ class AudioChunkingService:
current_start = chunk_index * step_duration
# Calculate end time for this chunk
- chunk_end = min(current_start + chunk_duration, wav_duration)
+ chunk_end = min(current_start + chunk_duration, mp3_duration)
actual_duration = chunk_end - current_start
# Skip very short chunks at the end (shouldn't happen with proper calculation)
@@ -332,12 +345,12 @@ class AudioChunkingService:
# Generate chunk filename
base_name = os.path.splitext(os.path.basename(file_path))[0]
- chunk_filename = f"{base_name}_chunk_{chunk_index:03d}.wav"
+ chunk_filename = f"{base_name}_chunk_{chunk_index:03d}.mp3"
chunk_path = os.path.join(temp_dir, chunk_filename)
- # Extract chunk from the converted WAV file (more efficient than re-converting)
+ # Extract chunk from the converted MP3 file (more efficient than re-converting)
cmd = [
- 'ffmpeg', '-i', wav_path,
+ 'ffmpeg', '-i', mp3_path,
'-ss', str(current_start),
'-t', str(actual_duration),
'-acodec', 'copy', # Copy codec since it's already in the right format
@@ -371,6 +384,17 @@ class AudioChunkingService:
chunks.append(chunk_info)
logger.info(f"Created chunk {chunk_index}: {current_start:.1f}s-{chunk_end:.1f}s ({chunk_size/1024/1024:.1f}MB)")
+
+ # Optionally preserve chunks for debugging (set PRESERVE_CHUNK_DEBUG=true in env)
+ if os.getenv('PRESERVE_CHUNK_DEBUG', 'false').lower() == 'true':
+ import shutil
+ # Save debug chunks in /data/uploads/debug/ directory
+ debug_dir = '/data/uploads/debug'
+ os.makedirs(debug_dir, exist_ok=True)
+ debug_filename = os.path.basename(chunk_path).replace('.mp3', '_debug.mp3')
+ debug_path = os.path.join(debug_dir, debug_filename)
+ shutil.copy2(chunk_path, debug_path)
+ logger.info(f"Debug: Preserved chunk as {debug_path}")
else:
logger.error(f"Chunk file not created: {chunk_path}")
@@ -679,13 +703,13 @@ class AudioChunkingService:
return recommendations
- def cleanup_chunks(self, chunks: List[Dict[str, Any]], temp_wav_path: str = None) -> None:
+ def cleanup_chunks(self, chunks: List[Dict[str, Any]], temp_mp3_path: str = None) -> None:
"""
- Clean up temporary chunk files and WAV file.
+ Clean up temporary chunk files and MP3 file.
Args:
chunks: List of chunk information dictionaries
- temp_wav_path: Optional path to temporary WAV file to clean up
+ temp_mp3_path: Optional path to temporary MP3 file to clean up
"""
for chunk in chunks:
try:
@@ -696,13 +720,13 @@ class AudioChunkingService:
except Exception as e:
logger.warning(f"Error cleaning up chunk {chunk.get('filename', 'unknown')}: {e}")
- # Clean up temporary WAV file if provided
- if temp_wav_path and os.path.exists(temp_wav_path):
+ # Clean up temporary MP3 file if provided
+ if temp_mp3_path and os.path.exists(temp_mp3_path):
try:
- os.remove(temp_wav_path)
- logger.debug(f"Cleaned up temporary WAV file: {temp_wav_path}")
+ os.remove(temp_mp3_path)
+ logger.debug(f"Cleaned up temporary MP3 file: {temp_mp3_path}")
except Exception as e:
- logger.warning(f"Error cleaning up temporary WAV file: {e}")
+ logger.warning(f"Error cleaning up temporary MP3 file: {e}")
class ChunkProcessingError(Exception):
"""Exception raised when chunk processing fails."""
diff --git a/static/js/app.js b/static/js/app.js
index 47f118e4..7cb1ed24 100644
--- a/static/js/app.js
+++ b/static/js/app.js
@@ -29,6 +29,16 @@ document.addEventListener('DOMContentLoaded', () => {
const searchQuery = ref('');
const isLoadingRecordings = ref(true);
const globalError = ref(null);
+
+ // --- Pagination State ---
+ const currentPage = ref(1);
+ const perPage = ref(25);
+ const totalRecordings = ref(0);
+ const totalPages = ref(0);
+ const hasNextPage = ref(false);
+ const hasPrevPage = ref(false);
+ const isLoadingMore = ref(false);
+ const searchDebounceTimer = ref(null);
// --- Enhanced Search & Organization State ---
const sortBy = ref('created_at'); // 'created_at' or 'meeting_date'
@@ -56,6 +66,10 @@ document.addEventListener('DOMContentLoaded', () => {
const progressPopupMinimized = ref(false);
const progressPopupClosed = ref(false);
const maxFileSizeMB = ref(250); // Default value, will be updated from API
+ const chunkingEnabled = ref(true); // Default value, will be updated from API
+ const chunkingMode = ref('size'); // 'size' or 'duration', will be updated from API
+ const chunkingLimit = ref(20); // Value in MB or seconds, will be updated from API
+ const chunkingLimitDisplay = ref('20MB'); // Human readable display, will be updated from API
// --- Audio Recording State ---
const isRecording = ref(false);
@@ -191,83 +205,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
const filteredRecordings = computed(() => {
- if (!searchQuery.value.trim()) {
- return recordings.value;
- }
-
- const query = searchQuery.value.toLowerCase().trim();
-
- // Parse different search parts
- const dateMatches = [...query.matchAll(/date:(\S+)/g)];
- const tagMatches = [...query.matchAll(/tag:(\S+)/g)];
-
- // Remove special syntax from query to get regular text search
- let textQuery = query.replace(/date:\S+/g, '').replace(/tag:\S+/g, '').trim();
-
- return recordings.value.filter(recording => {
- let matches = true;
-
- // Check date filters (ALL must match if multiple)
- if (dateMatches.length > 0) {
- const dateMatched = dateMatches.every(match => {
- const dateQuery = match[1];
- const recordingDate = getDateForSorting(recording);
- if (!recordingDate) return false;
-
- if (dateQuery === 'today') {
- return isToday(recordingDate);
- } else if (dateQuery === 'yesterday') {
- return isYesterday(recordingDate);
- } else if (dateQuery === 'thisweek') {
- return isThisWeek(recordingDate);
- } else if (dateQuery === 'lastweek') {
- return isLastWeek(recordingDate);
- } else if (dateQuery === 'thismonth') {
- return isThisMonth(recordingDate);
- } else if (dateQuery === 'lastmonth') {
- return isLastMonth(recordingDate);
- } else if (/^\d{4}-\d{2}-\d{2}$/.test(dateQuery)) {
- const searchDate = new Date(dateQuery + 'T00:00:00');
- return isSameDay(recordingDate, searchDate);
- } else if (/^\d{4}-\d{2}$/.test(dateQuery)) {
- const [year, month] = dateQuery.split('-');
- return recordingDate.getFullYear() === parseInt(year) &&
- recordingDate.getMonth() === parseInt(month) - 1;
- } else if (/^\d{4}$/.test(dateQuery)) {
- return recordingDate.getFullYear() === parseInt(dateQuery);
- }
- return false;
- });
- matches = matches && dateMatched;
- }
-
- // Check tag filters (ALL must match if multiple)
- if (tagMatches.length > 0) {
- const tagMatched = tagMatches.every(match => {
- const tagQuery = match[1].toLowerCase();
- if (!recording.tags || recording.tags.length === 0) return false;
- return recording.tags.some(tag =>
- tag.name.toLowerCase().includes(tagQuery)
- );
- });
- matches = matches && tagMatched;
- }
-
- // Check text search if there's remaining text
- if (textQuery) {
- const textMatched = (
- (recording.title && recording.title.toLowerCase().includes(textQuery)) ||
- (recording.participants && recording.participants.toLowerCase().includes(textQuery)) ||
- (recording.transcription && recording.transcription.toLowerCase().includes(textQuery)) ||
- (recording.notes && recording.notes.toLowerCase().includes(textQuery)) ||
- (recording.tags && recording.tags.length > 0 &&
- recording.tags.some(tag => tag.name.toLowerCase().includes(textQuery)))
- );
- matches = matches && textMatched;
- }
-
- return matches;
- });
+ return recordings.value;
});
const highlightedTranscript = computed(() => {
@@ -1835,6 +1773,10 @@ document.addEventListener('DOMContentLoaded', () => {
}
const clientId = `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
+
+ // Auto-summarization will always occur for all uploads
+ const willAutoSummarize = true;
+
uploadQueue.value.push({
file: fileObject,
notes: notes,
@@ -1843,7 +1785,8 @@ document.addEventListener('DOMContentLoaded', () => {
status: 'queued',
recordingId: null,
clientId: clientId,
- error: null
+ error: null,
+ willAutoSummarize: willAutoSummarize
});
filesAdded++;
} else if (fileObject) {
@@ -1952,6 +1895,7 @@ document.addEventListener('DOMContentLoaded', () => {
processingProgress.value = 30;
recordings.value.unshift(data);
+ totalRecordings.value++; // Update total count
pollProcessingStatus(nextFileItem);
} else {
@@ -1999,7 +1943,13 @@ document.addEventListener('DOMContentLoaded', () => {
processingProgress.value = 40;
pollInterval.value = setInterval(async () => {
- if (!currentlyProcessingFile.value || currentlyProcessingFile.value.clientId !== fileItem.clientId || ['completed', 'failed'].includes(fileItem.status)) {
+ // Check if we should stop polling
+ const shouldStopPolling = !currentlyProcessingFile.value ||
+ currentlyProcessingFile.value.clientId !== fileItem.clientId ||
+ fileItem.status === 'failed' ||
+ (fileItem.status === 'completed' && (!fileItem.willAutoSummarize || fileItem.summaryCompleted));
+
+ if (shouldStopPolling) {
console.log(`Polling stopped for ${fileItem.clientId} as it's no longer active or finished.`);
clearInterval(pollInterval.value);
pollInterval.value = null;
@@ -2027,19 +1977,110 @@ document.addEventListener('DOMContentLoaded', () => {
}
}
+ const previousStatus = fileItem.status;
fileItem.status = data.status;
fileItem.file.name = data.title || data.original_filename;
if (data.status === 'COMPLETED') {
console.log(`Processing COMPLETED for ${fileItem.file.name} (ID: ${recordingId})`);
- processingMessage.value = 'Processing complete!';
- processingProgress.value = 100;
- fileItem.status = 'completed';
+
+ // If this was previously summarizing, it's now fully complete
+ if (previousStatus === 'summarizing') {
+ console.log(`Auto-summary completed for ${fileItem.file.name}`);
+ processingMessage.value = 'Processing complete!';
+ processingProgress.value = 100;
+ fileItem.status = 'completed';
+ fileItem.summaryCompleted = true;
+
+ // This is final completion - clean up immediately and synchronously
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+
+ // Keep completed items visible in the modal - don't remove them
+ console.log(`Completed item ${fileItem.clientId} will remain visible in queue`);
+
+ // Use immediate startProcessingQueue instead of nextTick to avoid duplication
+ startProcessingQueue();
+ return; // Exit early to prevent further processing
+ }
+ // If auto-summarization will occur and hasn't started yet, wait for it
+ else if (fileItem.willAutoSummarize && !fileItem.hasCheckedForAutoSummary) {
+ processingMessage.value = 'Transcription complete!';
+ processingProgress.value = 85;
+ fileItem.status = 'awaiting_summary'; // Use intermediate status to keep it in upload queue
+ // Don't mark as summaryCompleted yet, continue polling
+ }
+ // No auto-summarization expected, complete normally
+ else {
+ processingMessage.value = 'Processing complete!';
+ processingProgress.value = 100;
+ fileItem.status = 'completed';
+ fileItem.summaryCompleted = true; // No summary expected, so consider it complete
+
+ // Complete immediately for files without auto-summarization
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+
+ // Keep completed items visible in the modal - don't remove them
+ console.log(`Completed item ${fileItem.clientId} will remain visible in queue`);
+
+ startProcessingQueue();
+ return; // Exit early to prevent further processing
+ }
+
+ // For files with auto-summarization, mark that they've been checked and continue polling
+ if (fileItem.willAutoSummarize && !fileItem.hasCheckedForAutoSummary) {
+ fileItem.hasCheckedForAutoSummary = true;
+ fileItem.autoSummaryStartTime = Date.now();
+ console.log(`Auto-summary expected for ${fileItem.file.name}, continuing to poll...`);
+ // Don't complete yet, continue polling
+ return;
+ }
+
+ // If we have auto-summarization and we've been waiting, check if we should timeout
+ if (fileItem.willAutoSummarize && fileItem.hasCheckedForAutoSummary) {
+ const waitTime = Date.now() - fileItem.autoSummaryStartTime;
+ const maxWaitTime = 60000; // 60 seconds
+
+ if (waitTime > maxWaitTime) {
+ // Timeout - complete the process
+ console.log(`Auto-summary timeout for ${fileItem.file.name}, completing...`);
+ processingMessage.value = 'Processing complete!';
+ processingProgress.value = 100;
+ fileItem.status = 'completed';
+ fileItem.summaryCompleted = true; // Mark as complete due to timeout
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+
+ // Keep completed items visible in the modal - don't remove them
+ console.log(`Timed-out item ${fileItem.clientId} will remain visible in queue`);
+
+ startProcessingQueue();
+ } else {
+ // Still waiting for auto-summary, continue polling
+ return;
+ }
+ }
+
+ // Normal completion path (no auto-summary check needed)
clearInterval(pollInterval.value);
pollInterval.value = null;
resetCurrentFileProcessingState();
isProcessingActive.value = false;
- await nextTick();
+
+ // Remove this item from uploadQueue immediately to prevent duplication
+ const queueIndex = uploadQueue.value.findIndex(item => item.clientId === fileItem.clientId);
+ if (queueIndex !== -1) {
+ uploadQueue.value.splice(queueIndex, 1);
+ console.log(`Removed completed item ${fileItem.clientId} from queue immediately`);
+ }
+
startProcessingQueue();
} else if (data.status === 'FAILED') {
@@ -2057,20 +2098,48 @@ document.addEventListener('DOMContentLoaded', () => {
startProcessingQueue();
} else if (data.status === 'PROCESSING') {
- // Check if this is a large file that might be using chunking
- // Note: This is just for UI feedback, actual chunking threshold is handled server-side
- const chunkThreshold = 25 * 1024 * 1024; // Default UI threshold
- const isLargeFile = fileItem.file.size > chunkThreshold;
- if (isLargeFile) {
- processingMessage.value = 'Processing large file (chunking may be used)...';
- processingProgress.value = Math.round(Math.min(70, processingProgress.value + Math.random() * 3));
+ // Check if this file will actually use chunking based on all conditions:
+ // 1. Chunking must be enabled in config
+ // 2. Must NOT be using ASR endpoint (ASR handles large files natively)
+ // 3. For size-based: File size must exceed the limit (can determine immediately)
+ // 4. For time-based: Can't determine client-side, but backend logs show it gets duration
+
+ const couldUseChunking = chunkingEnabled.value && !useAsrEndpoint.value;
+
+ if (couldUseChunking) {
+ if (chunkingMode.value === 'size') {
+ // Size-based chunking: we can determine definitively
+ const chunkThresholdBytes = chunkingLimit.value * 1024 * 1024;
+ const willUseChunking = fileItem.file.size > chunkThresholdBytes;
+
+ if (willUseChunking) {
+ processingMessage.value = 'Processing large file (chunking in progress)...';
+ // If auto-summarization will occur, cap at 70%, otherwise 80%
+ const maxProgress = fileItem.willAutoSummarize ? 70 : 80;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 3));
+ } else {
+ processingMessage.value = 'Transcription in progress...';
+ // If auto-summarization will occur, cap at 65%, otherwise 75%
+ const maxProgress = fileItem.willAutoSummarize ? 65 : 75;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 5));
+ }
+ } else {
+ // Duration-based chunking: Backend determines this after getting duration
+ // Show a neutral processing message since we can't know client-side
+ processingMessage.value = 'Processing file (chunking determined server-side)...';
+ const maxProgress = fileItem.willAutoSummarize ? 70 : 80;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 3));
+ }
} else {
processingMessage.value = 'Transcription in progress...';
- processingProgress.value = Math.round(Math.min(65, processingProgress.value + Math.random() * 5));
+ const maxProgress = fileItem.willAutoSummarize ? 65 : 75;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 5));
}
} else if (data.status === 'SUMMARIZING') {
- processingMessage.value = 'Generating title & summary...';
- processingProgress.value = Math.round(Math.min(95, processingProgress.value + Math.random() * 5));
+ console.log(`Auto-summary started for ${fileItem.file.name}`);
+ processingMessage.value = 'Generating summary...';
+ processingProgress.value = 90;
+ fileItem.status = 'summarizing';
} else {
processingMessage.value = 'Waiting in queue...';
processingProgress.value = 45;
@@ -2094,24 +2163,55 @@ document.addEventListener('DOMContentLoaded', () => {
};
// --- Data Loading ---
- const loadRecordings = async () => {
+ const loadRecordings = async (page = 1, append = false, searchQuery = '') => {
globalError.value = null;
- isLoadingRecordings.value = true;
+ if (!append) {
+ isLoadingRecordings.value = true;
+ } else {
+ isLoadingMore.value = true;
+ }
+
try {
- const response = await fetch('/recordings');
+ const params = new URLSearchParams({
+ page: page.toString(),
+ per_page: perPage.value.toString()
+ });
+
+ if (searchQuery.trim()) {
+ params.set('q', searchQuery.trim());
+ }
+
+ const response = await fetch(`/api/recordings?${params}`);
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Failed to load recordings');
- recordings.value = data;
-
- const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');
- if (lastRecordingId) {
- const recordingToSelect = recordings.value.find(r => r.id == lastRecordingId);
- if (recordingToSelect) {
- selectRecording(recordingToSelect);
+
+ // Update pagination state
+ currentPage.value = data.pagination.page;
+ totalRecordings.value = data.pagination.total;
+ totalPages.value = data.pagination.total_pages;
+ hasNextPage.value = data.pagination.has_next;
+ hasPrevPage.value = data.pagination.has_prev;
+
+ // Update recordings data
+ if (append) {
+ // Append to existing recordings (infinite scroll)
+ recordings.value = [...recordings.value, ...data.recordings];
+ } else {
+ // Replace recordings (fresh load or search)
+ recordings.value = data.recordings;
+
+ // Try to restore last selected recording
+ const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');
+ if (lastRecordingId && data.recordings.length > 0) {
+ const recordingToSelect = data.recordings.find(r => r.id == lastRecordingId);
+ if (recordingToSelect) {
+ selectRecording(recordingToSelect);
+ }
}
}
- const incompleteRecordings = recordings.value.filter(r => ['PENDING', 'PROCESSING', 'SUMMARIZING'].includes(r.status));
+ // Handle incomplete recordings for processing queue
+ const incompleteRecordings = data.recordings.filter(r => ['PENDING', 'PROCESSING', 'SUMMARIZING'].includes(r.status));
if (incompleteRecordings.length > 0 && !isProcessingActive.value) {
console.warn(`Found ${incompleteRecordings.length} incomplete recording(s) on load.`);
for (const recording of incompleteRecordings) {
@@ -2135,10 +2235,35 @@ document.addEventListener('DOMContentLoaded', () => {
} catch (error) {
console.error('Load Recordings Error:', error);
setGlobalError(`Failed to load recordings: ${error.message}`);
- recordings.value = [];
+ if (!append) {
+ recordings.value = [];
+ }
} finally {
isLoadingRecordings.value = false;
+ isLoadingMore.value = false;
+ }
+ };
+
+ // Load more recordings (infinite scroll)
+ const loadMoreRecordings = async () => {
+ if (!hasNextPage.value || isLoadingMore.value) return;
+ await loadRecordings(currentPage.value + 1, true, searchQuery.value);
+ };
+
+ // Search with debouncing
+ const performSearch = async (query = '') => {
+ currentPage.value = 1;
+ await loadRecordings(1, false, query);
+ };
+
+ // Debounced search function
+ const debouncedSearch = (query) => {
+ if (searchDebounceTimer.value) {
+ clearTimeout(searchDebounceTimer.value);
}
+ searchDebounceTimer.value = setTimeout(() => {
+ performSearch(query);
+ }, 300); // 300ms debounce
};
const loadTags = async () => {
@@ -2790,6 +2915,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (!response.ok) throw new Error(data.error || 'Failed to delete recording');
recordings.value = recordings.value.filter(r => r.id !== idToDelete);
+ totalRecordings.value--; // Update total count
const queueIndex = uploadQueue.value.findIndex(item => item.recordingId === idToDelete);
if (queueIndex !== -1) {
@@ -3586,12 +3712,12 @@ document.addEventListener('DOMContentLoaded', () => {
watch(uploadQueue, (newQueue, oldQueue) => {
if (newQueue.length === 0 && oldQueue.length > 0 && !isProcessingActive.value) {
console.log("Upload queue processing finished.");
- setTimeout(() => progressPopupMinimized.value = true, 1000);
+ setTimeout(() => progressPopupMinimized.value = true, 500);
setTimeout(() => {
if (completedInQueue.value === totalInQueue.value && !isProcessingActive.value) {
progressPopupClosed.value = true;
}
- }, 5000);
+ }, 2000);
}
}, { deep: true });
@@ -3676,6 +3802,11 @@ document.addEventListener('DOMContentLoaded', () => {
}
});
});
+
+ // Watch for search query changes
+ watch(searchQuery, (newQuery) => {
+ debouncedSearch(newQuery);
+ });
// --- Configuration Loading ---
const loadConfiguration = async () => {
@@ -3684,7 +3815,11 @@ document.addEventListener('DOMContentLoaded', () => {
if (response.ok) {
const config = await response.json();
maxFileSizeMB.value = config.max_file_size_mb || 250;
- console.log(`Loaded max file size: ${maxFileSizeMB.value} MB`);
+ chunkingEnabled.value = config.chunking_enabled !== undefined ? config.chunking_enabled : true;
+ chunkingMode.value = config.chunking_mode || 'size';
+ chunkingLimit.value = config.chunking_limit || 20;
+ chunkingLimitDisplay.value = config.chunking_limit_display || '20MB';
+ console.log(`Loaded configuration: max size ${maxFileSizeMB.value}MB, chunking ${chunkingEnabled.value ? 'enabled' : 'disabled'} (${chunkingLimitDisplay.value})`);
} else {
console.warn('Failed to load configuration, using default values');
}
@@ -3735,39 +3870,62 @@ document.addEventListener('DOMContentLoaded', () => {
const existingRecording = recordings.value.find(r => r.id === recording.id);
if (!existingRecording) {
recordings.value.unshift(recording);
+ totalRecordings.value++; // Update total count
}
- // Check if this recording is already in the upload queue
+ // Check if this recording is already in the upload queue or currently being processed
const existingItem = uploadQueue.value.find(item => item.recordingId === recording.id);
- if (!existingItem) {
- console.log(`Found new inbox recording: ${recording.original_filename}`);
- // Add it to the queue to be displayed in the progress modal
- const inboxItem = {
- file: {
- name: recording.original_filename || `Recording ${recording.id}`,
- size: recording.file_size || 0
- },
- status: 'pending', // It's already being processed on backend
- recordingId: recording.id,
- clientId: `inbox-${recording.id}-${Date.now()}`,
- error: null,
- isReprocessing: true, // Use reprocessing logic to poll for status
- reprocessType: 'transcription'
- };
- uploadQueue.value.unshift(inboxItem);
-
- // If nothing is currently being processed, make this the active item for the main progress bar
- if (!isProcessingActive.value && !currentlyProcessingFile.value) {
- currentlyProcessingFile.value = inboxItem;
+ const isCurrentlyProcessing = currentlyProcessingFile.value && currentlyProcessingFile.value.recordingId === recording.id;
+
+ // Don't add if it's already in queue or being processed
+ if (existingItem || isCurrentlyProcessing) {
+ // Update status if the existing item status has changed
+ if (existingItem && existingItem.status !== recording.status) {
+ console.log(`Updating status for existing recording ${recording.original_filename}: ${existingItem.status} -> ${recording.status}`);
}
-
- // Show progress modal if it's hidden
- progressPopupMinimized.value = false;
- progressPopupClosed.value = false;
+ return;
+ }
+
+ // Only add recordings that are still processing (not completed)
+ if (recording.status === 'COMPLETED') {
+ console.log(`Skipping completed inbox recording: ${recording.original_filename}`);
+ return;
+ }
+
+ console.log(`Found new inbox recording: ${recording.original_filename} (status: ${recording.status})`);
+
+ // Don't add recordings that are already being handled by main processing
+ if (recording.status === 'SUMMARIZING' && isProcessingActive.value) {
+ console.log(`Skipping ${recording.original_filename} - already in summarization phase of main processing`);
+ return;
+ }
+
+ // Add it to the queue to be displayed in the progress modal
+ const inboxItem = {
+ file: {
+ name: recording.original_filename || `Recording ${recording.id}`,
+ size: recording.file_size || 0
+ },
+ status: 'pending', // It's already being processed on backend
+ recordingId: recording.id,
+ clientId: `inbox-${recording.id}-${Date.now()}`,
+ error: null,
+ isReprocessing: true, // Use reprocessing logic to poll for status
+ reprocessType: 'transcription'
+ };
+ uploadQueue.value.unshift(inboxItem);
- // Start polling its status
- startReprocessingPoll(recording.id);
+ // If nothing is currently being processed, make this the active item for the main progress bar
+ if (!isProcessingActive.value && !currentlyProcessingFile.value) {
+ currentlyProcessingFile.value = inboxItem;
}
+
+ // Show progress modal if it's hidden
+ progressPopupMinimized.value = false;
+ progressPopupClosed.value = false;
+
+ // Start polling its status
+ startReprocessingPoll(recording.id);
});
}
} catch (error) {
@@ -3939,7 +4097,10 @@ document.addEventListener('DOMContentLoaded', () => {
return {
// Core State
currentView, dragover, recordings, selectedRecording, selectedTab, searchQuery,
- isLoadingRecordings, globalError, maxFileSizeMB, sortBy,
+ isLoadingRecordings, globalError, maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit, chunkingLimitDisplay, sortBy,
+
+ // Pagination State
+ currentPage, perPage, totalRecordings, totalPages, hasNextPage, hasPrevPage, isLoadingMore,
// UI State
browser,
@@ -3999,7 +4160,7 @@ document.addEventListener('DOMContentLoaded', () => {
toggleSidebar, switchToUploadView, selectRecording,
handleDragOver, handleDragLeave, handleDrop, handleFileSelect, addFilesToQueue,
startRecording, stopRecording, uploadRecordedAudio, discardRecording,
- loadRecordings, saveMetadata, editRecording, cancelEdit, saveEdit,
+ loadRecordings, loadMoreRecordings, performSearch, debouncedSearch, saveMetadata, editRecording, cancelEdit, saveEdit,
confirmDelete, cancelDelete, deleteRecording,
toggleEditParticipants, toggleEditMeetingDate, toggleEditSummary, cancelEditSummary, saveEditSummary, toggleEditNotes,
cancelEditNotes, saveEditNotes, initializeMarkdownEditor, saveInlineEdit,
diff --git a/templates/account.html b/templates/account.html
index ce3ce6ff..acbe1ae5 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -953,8 +953,7 @@
// Update footer on page load
updateFooter();
- });
-
+
// Dark mode toggle functionality
const darkModeToggle = document.getElementById('darkModeToggle');
const darkModeIcon = document.getElementById('darkModeIcon');
@@ -1615,6 +1614,19 @@
}
});
+ // Check for URL hash and show appropriate tab
+ const urlHash = window.location.hash.substring(1); // Remove the '#' symbol
+ if (urlHash === 'tags') {
+ showTagsTab();
+ } else if (urlHash === 'shares') {
+ showSharesTab();
+ } else if (urlHash === 'about') {
+ showAboutTab();
+ } else {
+ // Default to account tab
+ showAccountTab();
+ }
+ });
</script>
</body>
</html>
diff --git a/templates/index.html b/templates/index.html
index 07d6e2d1..eb4460cc 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -48,19 +48,19 @@
class="h-full flex flex-col opacity-0 transition-opacity duration-500">
<!-- Header -->
- <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">
+ <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-3 sm:px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">
<!-- Left side: Menu toggle and logo -->
- <div class="flex items-center gap-4">
+ <div class="flex items-center gap-2 sm:gap-4 min-w-0 flex-shrink">
<!-- Menu Toggle Button -->
<button @click="toggleSidebar"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200">
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200 flex-shrink-0 flex items-center justify-center">
<i class="fas fa-bars text-lg"></i>
</button>
<!-- Logo and Title -->
- <div class="flex items-center gap-3">
- <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-8 h-8">
- <h1 class="text-xl font-bold text-[var(--text-primary)]">Speakr</h1>
+ <div class="flex items-center gap-2 sm:gap-3 min-w-0">
+ <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-7 h-7 sm:w-8 sm:h-8 flex-shrink-0">
+ <h1 class="text-lg sm:text-xl font-bold text-[var(--text-primary)] truncate">Speakr</h1>
</div>
</div>
@@ -69,7 +69,7 @@
<!-- Inquire Mode Button -->
{% if inquire_mode_enabled %}
<a href="/inquire"
- class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:opacity-80 transition-opacity text-sm flex items-center gap-2 min-w-[120px] justify-center">
+ class="px-2 py-1.5 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:opacity-80 transition-opacity text-sm sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
<i class="fas fa-search"></i>
<span class="hidden sm:inline">Inquire</span>
</a>
@@ -77,19 +77,20 @@
<!-- New Recording Button -->
<button @click="switchToUploadView"
- class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-sm flex items-center gap-2 min-w-[120px] justify-center">
- <i class="fas fa-plus"></i>
- <span class="hidden sm:inline">New Recording</span>
+ class="px-3 py-1.5 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-sm sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
+ <i class="fas fa-plus mr-1"></i>New
+ <span class="hidden sm:inline">Recording</span>
</button>
<!-- User menu -->
{% if current_user.is_authenticated %}
<div class="relative">
<button @click="isUserMenuOpen = !isUserMenuOpen"
- class="flex items-center gap-2 p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200">
+ class="flex items-center gap-1 sm:gap-2 p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200"
+ title="User Menu">
<i class="fas fa-user-circle text-lg"></i>
- <span class="hidden sm:inline">{{ current_user.name if current_user.is_authenticated else 'User' }}</span>
- <i class="fas fa-chevron-down text-xs"></i>
+ <span class="hidden lg:inline text-sm">{{ current_user.name if current_user.is_authenticated else 'User' }}</span>
+ <i class="fas fa-chevron-down text-xs hidden sm:inline"></i>
</button>
<!-- User dropdown -->
@@ -98,14 +99,17 @@
<a href="/account" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
<i class="fas fa-cog mr-2 w-4 text-center"></i>Account Settings
</a>
+ <a href="/account#tags" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-tags mr-2 w-4 text-center"></i>Tag Management
+ </a>
+ <button @click="openSharesList" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
+ <i class="fas fa-share-alt mr-2 w-4 text-center"></i>Shared Transcripts
+ </button>
{% if current_user.is_admin %}
<a href="/admin" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
<i class="fas fa-user-shield mr-2 w-4 text-center"></i>Admin
</a>
{% endif %}
- <button @click="openSharesList" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
- <i class="fas fa-share-alt mr-2 w-4 text-center"></i>Shared Transcripts
- </button>
<div class="border-t border-[var(--border-primary)] my-1"></div>
<button @click="toggleDarkMode" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
<i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'" class="mr-2 w-4 text-center"></i>
@@ -197,18 +201,28 @@
</div>
<!-- Recordings List -->
- <div class="flex-1 overflow-y-auto p-4">
- <div v-if="isLoadingRecordings" class="text-center py-8">
+ <div class="flex-1 overflow-y-auto p-4"
+ @scroll="(e) => {
+ const element = e.target;
+ const threshold = 100; // Load more when 100px from bottom
+ if (element.scrollHeight - element.scrollTop - element.clientHeight < threshold) {
+ loadMoreRecordings();
+ }
+ }">
+ <div v-if="isLoadingRecordings && recordings.length === 0" class="text-center py-8">
<i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
<p class="mt-2 text-[var(--text-muted)]">Loading recordings...</p>
</div>
- <div v-else-if="filteredRecordings.length === 0" class="text-center py-8">
+ <div v-else-if="recordings.length === 0 && !isLoadingRecordings" class="text-center py-8">
<i class="fas fa-microphone-slash text-3xl text-[var(--text-muted)] mb-3"></i>
<p class="text-[var(--text-muted)]">No recordings found</p>
+ <p v-if="searchQuery.trim()" class="text-sm text-[var(--text-muted)] mt-1">
+ Try adjusting your search or <button @click="searchQuery = ''" class="text-[var(--text-accent)] hover:underline">clear filters</button>
+ </p>
</div>
- <div v-else class="space-y-2">
+ <div v-if="recordings.length > 0" class="space-y-2">
<div v-for="group in groupedRecordings" :key="group.title" class="mb-6">
<h3 class="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-2">
${group.title}
@@ -293,6 +307,18 @@
</div>
</div>
</div>
+
+ <!-- Load More Indicator -->
+ <div v-if="isLoadingMore" class="text-center py-4">
+ <i class="fas fa-spinner fa-spin text-lg text-[var(--text-muted)]"></i>
+ <p class="text-sm text-[var(--text-muted)] mt-1">Loading more recordings...</p>
+ </div>
+
+ <!-- End of Results Indicator -->
+ <div v-else-if="!hasNextPage && totalRecordings > 0" class="text-center py-4 text-xs text-[var(--text-muted)]">
+ <i class="fas fa-check-circle mr-1"></i>
+ All recordings loaded
+ </div>
</div>
</div>
</div>
diff --git a/templates/inquire.html b/templates/inquire.html
index ca51d344..f475b8f4 100644
--- a/templates/inquire.html
+++ b/templates/inquire.html
@@ -121,19 +121,21 @@
data-current-user-name="{{ current_user.name if current_user.is_authenticated else '' }}">
<!-- Header -->
- <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">
- <!-- Left side: Back button and logo -->
- <div class="flex items-center gap-4">
- <a href="/" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200">
- <i class="fas fa-arrow-left text-lg"></i>
- </a>
+ <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-3 sm:px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">
+ <!-- Left side: Menu and logo -->
+ <div class="flex items-center gap-2 sm:gap-4 min-w-0 flex-shrink">
+ <!-- Mobile Sidebar Toggle -->
+ <button @click="isMobileSidebarOpen = !isMobileSidebarOpen"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200 lg:hidden flex-shrink-0 flex items-center justify-center">
+ <i class="fas fa-bars text-lg"></i>
+ </button>
- <!-- Logo and Title -->
- <div class="flex items-center gap-3">
- <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-8 h-8">
- <h1 class="text-xl font-bold text-[var(--text-primary)]">Speakr</h1>
- <span class="text-sm text-[var(--text-muted)] ml-2">• Inquire Mode</span>
- </div>
+ <!-- Logo and Title (clickable to go back) -->
+ <a href="/" class="flex items-center gap-2 sm:gap-3 min-w-0 hover:opacity-80 transition-opacity">
+ <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-6 h-6 sm:w-8 sm:h-8 flex-shrink-0">
+ <h1 class="text-lg sm:text-xl font-bold text-[var(--text-primary)] truncate">Speakr</h1>
+ <span class="text-xs sm:text-sm text-[var(--text-muted)] hidden sm:inline">• Inquire Mode</span>
+ </a>
</div>
<!-- Right side: User menu -->
@@ -177,13 +179,32 @@
</header>
<!-- Main Content -->
- <div class="flex-1 flex overflow-hidden">
+ <div class="flex-1 flex overflow-hidden relative">
+ <!-- Mobile Sidebar Overlay -->
+ <div v-if="isMobileSidebarOpen"
+ @click="isMobileSidebarOpen = false"
+ class="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden"></div>
+
<!-- Left Panel: Filters -->
- <div class="w-80 bg-[var(--bg-secondary)] border-r border-[var(--border-primary)] flex flex-col flex-shrink-0">
- <div class="p-4 space-y-4 flex-shrink-0">
- <div class="flex items-center justify-between">
- <h2 class="text-lg font-bold">Filters</h2>
- <button @click="clearInquireFilters" class="text-xs px-3 py-1 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] transition-colors flex items-center gap-1">
+ <div class="w-80 bg-[var(--bg-secondary)] border-r border-[var(--border-primary)] flex flex-col flex-shrink-0 transition-transform duration-300 ease-in-out z-50"
+ :class="[
+ 'lg:relative lg:translate-x-0',
+ isMobileSidebarOpen ? 'fixed inset-y-0 left-0 translate-x-0' : 'fixed inset-y-0 left-0 -translate-x-full lg:translate-x-0'
+ ]">
+ <!-- Mobile close button -->
+ <div class="lg:hidden flex items-center justify-between p-4 border-b border-[var(--border-primary)]">
+ <h2 class="text-lg font-bold">Filters</h2>
+ <button @click="isMobileSidebarOpen = false"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times text-lg"></i>
+ </button>
+ </div>
+
+ <div class="flex-1 overflow-y-auto custom-scrollbar">
+ <div class="p-4 space-y-4">
+ <div class="flex items-center justify-between lg:block">
+ <h2 class="text-lg font-bold hidden lg:block">Filters</h2>
+ <button @click="clearInquireFilters" class="text-xs px-3 py-1 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] transition-colors flex items-center gap-1 w-full lg:w-auto justify-center">
<i class="fas fa-times"></i> Clear All
</button>
</div>
@@ -252,8 +273,6 @@
</div>
</div>
</div>
-
- </div>
<!-- Recording Filters - Commented Out -->
<!--
@@ -274,8 +293,7 @@
</div>
-->
- <!-- Active Filters Summary -->
- <div class="p-4">
+ <!-- Active Filters Summary -->
<div v-if="hasActiveFilters" class="bg-[var(--bg-primary)] rounded-lg border border-[var(--border-secondary)] p-3">
<h4 class="text-sm font-medium mb-2 text-[var(--text-muted)] flex items-center">
<i class="fas fa-filter mr-2"></i>Active Filters:
@@ -292,16 +310,22 @@
</div>
</div>
</div>
- </div>
- </div>
+ </div><!-- End of p-4 space-y-4 div -->
+ </div><!-- End of flex-1 overflow-y-auto div -->
+ </div><!-- End of w-80 sidebar div -->
<!-- Right Panel: Chat -->
- <div class="flex-1 flex flex-col overflow-hidden">
+ <div class="flex-1 flex flex-col overflow-hidden"
+ :class="isMobileSidebarOpen ? 'hidden lg:flex' : 'flex'">
<!-- Chat Messages Area -->
<div ref="inquireMessagesRef" @scroll="handleScroll" class="flex-1 overflow-y-auto p-6 space-y-4 custom-scrollbar">
<!-- Welcome Message -->
<div v-if="inquireChatMessages.length === 0" class="text-center py-16">
- <i class="fas fa-search text-6xl text-[var(--text-accent)] mb-6"></i>
+ <div class="mb-6 text-[var(--text-accent)]">
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-24 w-24 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
+ </svg>
+ </div>
<h2 class="text-2xl font-bold mb-4">Ask Questions About Your Transcriptions</h2>
<p class="text-[var(--text-muted)] max-w-lg mx-auto mb-6">
Select filters on the left to narrow down your transcriptions, then ask questions to get insights from your recordings.
@@ -406,6 +430,7 @@
const speakerSearchQuery = ref('');
const isUserMenuOpen = ref(false);
+ const isMobileSidebarOpen = ref(false);
const availableFilters = reactive({
tags: [],
@@ -665,6 +690,7 @@
inquireMessagesRef,
globalError,
isUserMenuOpen,
+ isMobileSidebarOpen,
chatProcessingStatus,
showProcessingStatus,
tagSearchQuery,