Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Release v0.5.1: Enhanced UI, Inquire Mode, and system improvements
Murtaza Nasirc9516bcc0f43
diff --git a/DEPLOYMENT_GUIDE.md b/DEPLOYMENT_GUIDE.mdindex 1b8dd177..dbb7994e 100644--- a/DEPLOYMENT_GUIDE.md+++ b/DEPLOYMENT_GUIDE.md@@ -163,7 +163,7 @@ CHAT_MAX_TOKENS=5000# --- Large File Chunking (for endpoints with file size limits) ---ENABLE_CHUNKING=true-CHUNK_SIZE_MB=20+CHUNK_LIMIT=20MB # Size-based chunking (legacy CHUNK_SIZE_MB also works)CHUNK_OVERLAP_SECONDS=3# --- Admin User (created on first run) ---@@ -418,7 +418,7 @@ ASR_BASE_URL=http://localhost:9000 # or remote IP## Large File Chunking Configuration-Speakr automatically handles large files that exceed transcription API limits through intelligent chunking. This is particularly useful for endpoints like OpenAI's Whisper API which has a 25MB file size limit.+Speakr automatically handles large files that exceed transcription API limits through intelligent chunking. This feature only applies to the Standard Whisper API method (`USE_ASR_ENDPOINT=false`). **Note: Chunking is NOT used with ASR webservice endpoints.**### Environment Variables@@ -426,8 +426,15 @@ Speakr automatically handles large files that exceed transcription API limits th# Enable automatic chunking for large files (default: true)ENABLE_CHUNKING=true-# Maximum chunk size in MB (default: 20MB for safety margin with 25MB limits)-# Adjust based on your transcription endpoint's file size limit+# Chunking limit - choose ONE format:+# Size-based (for APIs with file size limits like OpenAI's 25MB)+CHUNK_LIMIT=20MB++# Duration-based (for APIs with processing time limits)+# CHUNK_LIMIT=1200s # 20 minutes in seconds+# CHUNK_LIMIT=20m # 20 minutes++# Legacy format (still supported, but CHUNK_LIMIT takes precedence)CHUNK_SIZE_MB=20# Overlap between chunks in seconds to ensure no speech is lost at boundaries@@ -445,18 +452,18 @@ CHUNK_OVERLAP_SECONDS=3### Configuration Guidelines-**For OpenAI Whisper API (25MB limit):**+**If your provider has file size limits (e.g., OpenAI, OpenRouter):**```envENABLE_CHUNKING=true-CHUNK_SIZE_MB=20 # 20MB provides 5MB safety margin-CHUNK_OVERLAP_SECONDS=3 # 3 seconds overlap for speech continuity+CHUNK_LIMIT=20MB # Use size-based chunking+CHUNK_OVERLAP_SECONDS=3```-**For APIs with different limits:**+**If your provider has processing time limits:**```envENABLE_CHUNKING=true-CHUNK_SIZE_MB=45 # For 50MB limit APIs-CHUNK_OVERLAP_SECONDS=5 # Longer overlap for better accuracy+CHUNK_LIMIT=1200s # Use duration-based chunking (20 minutes)+CHUNK_OVERLAP_SECONDS=3```**To disable chunking (for unlimited APIs):**@@ -474,7 +481,7 @@ ENABLE_CHUNKING=false### Troubleshooting Chunking**Files still failing with size errors:**-- Reduce `CHUNK_SIZE_MB` (try 15MB for OpenAI)+- Reduce chunk limit: `CHUNK_LIMIT=15MB` (or legacy `CHUNK_SIZE_MB=15`)- Check that `ENABLE_CHUNKING=true`- Verify your API endpoint's actual file size limitdiff --git a/README.md b/README.mdindex f53c6084..c51f1f2f 100644--- a/README.md+++ b/README.md@@ -22,7 +22,8 @@## What's New?-### Latest Release (Version 0.5.0)+### Latest Release (Version 0.5.1)+* **Inquire Mode (Experimental):** Revolutionary AI-powered search across all your recordings! Ask questions like "What decisions were made about the marketing budget?" and get intelligent answers with context from relevant conversations. Perfect for finding insights across multiple meetings, interviews, or sessions.* **Advanced Tagging System:** Organize recordings with multiple tags, each with custom summarization prompts and ASR defaults* **Enhanced ASR Integration:** Configure language and speaker detection directly from the UI with automatic participant extraction* **Word Document Export:** Download summaries and notes as beautifully formatted .docx files@@ -152,6 +153,7 @@## Core Features* **Self-Hosted and Private:** Keep full control over your data by hosting Speakr on your own server.+* **Inquire Mode (Experimental):** Search and chat across all your recordings using AI-powered semantic search. Ask questions about any topic and get intelligent answers with relevant context from your entire audio library.* **Advanced Transcription & Diarization:** Get accurate transcripts with optional AI-powered speaker identification (diarization) to know who said what.* **AI-Powered Insights:** Automatically generate titles and summaries for your recordings. Use the integrated chat to ask questions and pull insights directly from the transcript.* **Install as a PWA App:** Install on your phone for quick and easy recordings and note capture.@@ -222,7 +224,8 @@ You only need Docker installed for this method; you do not need to clone the rep# --- Large File Chunking (for endpoints with file size limits) ---ENABLE_CHUNKING=true- CHUNK_SIZE_MB=20+ CHUNK_LIMIT=20MB # Size-based chunking (legacy CHUNK_SIZE_MB also works)+ # CHUNK_LIMIT=1200s # Alternative: Duration-based chunking (20 minutes)# --- Application Settings ---ALLOW_REGISTRATION=false@@ -230,6 +233,9 @@ You only need Docker installed for this method; you do not need to clone the repADMIN_PASSWORD=changeme+ # --- Inquire Mode (Experimental - AI search across all recordings) ---+ # ENABLE_INQUIRE_MODE=true+# --- Docker Settings ---SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.dbUPLOAD_FOLDER=/data/uploads@@ -258,6 +264,9 @@ You only need Docker installed for this method; you do not need to clone the repADMIN_PASSWORD=changeme+ # --- Inquire Mode (Experimental - AI search across all recordings) ---+ # ENABLE_INQUIRE_MODE=true+# --- Docker Settings ---SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.dbUPLOAD_FOLDER=/data/uploads@@ -314,6 +323,13 @@ Follow these steps if you want to modify the code or build the Docker image your5. **Identify Speakers (Diarization):*** If you used the ASR method with diarization enabled, click the **Identify Speakers** button.* In the modal, assign names to the detected speakers (e.g., `SPEAKER 00`, `SPEAKER 01`). You can use the **Auto Identify** feature to let the AI suggest names based on the conversation.+6. **Use Inquire Mode (Experimental - optional):**+ * **Enable it first:** Uncomment `ENABLE_INQUIRE_MODE=true` in your `.env` file and restart the application+ * Click the **Inquire** button in the header to enter semantic search mode+ * Ask questions like "What were the main action items discussed?" or "Who mentioned the budget concerns?"+ * The AI will search across all your recordings and provide answers with relevant context+ * Use filters to search specific recordings, speakers, or date ranges+ * Perfect for finding insights across multiple meetings or discovering patterns in your conversations---<details><summary><strong>Advanced Tagging System</strong></summary>diff --git a/VERSION b/VERSIONnew file mode 100644index 00000000..a076e7fb--- /dev/null+++ b/VERSION@@ -0,0 +1 @@+v0.5.1\ No newline at end of filediff --git a/app.py b/app.pyindex 9aabf9f3..438c636e 100644--- a/app.py+++ b/app.py@@ -15,6 +15,7 @@ from werkzeug.utils import secure_filenamefrom werkzeug.exceptions import RequestEntityTooLargefrom werkzeug.middleware.proxy_fix import ProxyFixfrom sqlalchemy import select+from sqlalchemy.orm import joinedloadimport threadingfrom dotenv import load_dotenv # Import load_dotenvimport httpx@@ -47,9 +48,39 @@ import secretsimport timefrom audio_chunking import AudioChunkingService, ChunkProcessingError, ChunkingNotSupportedError+# Optional imports for embedding functionality+try:+ import numpy as np+ from sentence_transformers import SentenceTransformer+ from sklearn.metrics.pairwise import cosine_similarity+ EMBEDDINGS_AVAILABLE = True+except ImportError as e:+ EMBEDDINGS_AVAILABLE = False+ # Create dummy classes to prevent import errors+ class SentenceTransformer:+ def __init__(self, *args, **kwargs):+ pass+ def encode(self, *args, **kwargs):+ return []++ np = None+ cosine_similarity = None+# Load environment variables from .env fileload_dotenv()+# Early check for Inquire Mode configuration (needed for startup message)+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'++# Log embedding status on startup+if ENABLE_INQUIRE_MODE and EMBEDDINGS_AVAILABLE:+ print("✅ Inquire Mode: Full semantic search enabled (embeddings available)")+elif ENABLE_INQUIRE_MODE and not EMBEDDINGS_AVAILABLE:+ print("⚠️ Inquire Mode: Basic text search only (embedding dependencies not available)")+ print(" To enable semantic search, install: pip install sentence-transformers==2.7.0 huggingface-hub>=0.19.0")+elif not ENABLE_INQUIRE_MODE:+ print("ℹ️ Inquire Mode: Disabled (set ENABLE_INQUIRE_MODE=true to enable)")+# Configure logginglog_level = os.environ.get('LOG_LEVEL', 'INFO').upper()handler = logging.StreamHandler(sys.stdout)@@ -67,7 +98,7 @@ app_logger = logging.getLogger('werkzeug')app_logger.setLevel(log_level)app_logger.addHandler(handler)-# --- Rate Limiting Setup ---+# --- Rate Limiting Setup (will be configured after app creation) ---limiter = Limiter(get_remote_address,app=None, # Defer initialization@@ -419,7 +450,8 @@ login_manager.init_app(app)login_manager.login_view = 'login'login_manager.login_message_category = 'info'bcrypt.init_app(app)-limiter.init_app(app) # Initialize the limiter+limiter.init_app(app) # Initialize the limiter (uses in-memory storage by default)+csrf = CSRFProtect(app)# Add context processor to make 'now' available to all templates@@ -466,6 +498,311 @@ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)def load_user(user_id):return db.session.get(User, int(user_id))+# --- Embedding and Chunking Utilities ---++# Initialize embedding model (lazy loading)+_embedding_model = None++def get_embedding_model():+ """Get or initialize the sentence transformer model."""+ global _embedding_model++ if not EMBEDDINGS_AVAILABLE:+ return None++ if _embedding_model is None:+ try:+ _embedding_model = SentenceTransformer('all-MiniLM-L6-v2')+ app.logger.info("Embedding model loaded successfully")+ except Exception as e:+ app.logger.error(f"Failed to load embedding model: {e}")+ return None+ return _embedding_model++def chunk_transcription(transcription, max_chunk_length=500, overlap=50):+ """+ Split transcription into overlapping chunks for better context retrieval.++ Args:+ transcription (str): The full transcription text+ max_chunk_length (int): Maximum characters per chunk+ overlap (int): Character overlap between chunks++ Returns:+ list: List of text chunks+ """+ if not transcription or len(transcription) <= max_chunk_length:+ return [transcription] if transcription else []++ chunks = []+ start = 0++ while start < len(transcription):+ end = start + max_chunk_length++ # Try to break at sentence boundaries+ if end < len(transcription):+ # Look for sentence endings within the last 100 characters+ sentence_end = -1+ for i in range(max(0, end - 100), end):+ if transcription[i] in '.!?':+ # Check if it's not an abbreviation+ if i + 1 < len(transcription) and transcription[i + 1].isspace():+ sentence_end = i + 1++ if sentence_end > start:+ end = sentence_end++ chunk = transcription[start:end].strip()+ if chunk:+ chunks.append(chunk)++ # Move start position with overlap+ start = max(start + 1, end - overlap)++ # Prevent infinite loop+ if start >= len(transcription):+ break++ return chunks++def generate_embeddings(texts):+ """+ Generate embeddings for a list of texts.++ Args:+ texts (list): List of text strings++ Returns:+ list: List of embedding vectors as numpy arrays, or empty list if embeddings unavailable+ """+ if not EMBEDDINGS_AVAILABLE:+ app.logger.warning("Embeddings not available - skipping embedding generation")+ return []++ model = get_embedding_model()+ if not model or not texts:+ return []++ try:+ embeddings = model.encode(texts)+ return [embedding.astype(np.float32) for embedding in embeddings]+ except Exception as e:+ app.logger.error(f"Error generating embeddings: {e}")+ return []++def serialize_embedding(embedding):+ """Convert numpy array to binary for database storage."""+ if embedding is None or not EMBEDDINGS_AVAILABLE:+ return None+ return embedding.tobytes()++def deserialize_embedding(binary_data):+ """Convert binary data back to numpy array."""+ if binary_data is None or not EMBEDDINGS_AVAILABLE:+ return None+ return np.frombuffer(binary_data, dtype=np.float32)++def process_recording_chunks(recording_id):+ """+ Process a recording by creating chunks and generating embeddings.+ This should be called after a recording is transcribed.+ """+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording or not recording.transcription:+ return False++ # Delete existing chunks for this recording+ TranscriptChunk.query.filter_by(recording_id=recording_id).delete()++ # Create chunks+ chunks = chunk_transcription(recording.transcription)++ if not chunks:+ return True++ # Generate embeddings+ embeddings = generate_embeddings(chunks)++ # Store chunks in database+ for i, (chunk_text, embedding) in enumerate(zip(chunks, embeddings)):+ chunk = TranscriptChunk(+ recording_id=recording_id,+ user_id=recording.user_id,+ chunk_index=i,+ content=chunk_text,+ embedding=serialize_embedding(embedding) if embedding is not None else None+ )+ db.session.add(chunk)++ db.session.commit()+ app.logger.info(f"Created {len(chunks)} chunks for recording {recording_id}")+ return True++ except Exception as e:+ app.logger.error(f"Error processing chunks for recording {recording_id}: {e}")+ db.session.rollback()+ return False++def basic_text_search_chunks(user_id, query, filters=None, top_k=5):+ """+ Basic text search fallback when embeddings are not available.+ Uses simple text matching instead of semantic search.+ """+ try:+ # Build base query for chunks+ chunks_query = TranscriptChunk.query.filter_by(user_id=user_id)++ # Apply filters if provided+ if filters:+ if filters.get('tag_ids'):+ chunks_query = chunks_query.join(Recording).join(+ RecordingTag, Recording.id == RecordingTag.recording_id+ ).filter(RecordingTag.tag_id.in_(filters['tag_ids']))++ if filters.get('speaker_names'):+ # Filter by participants field in recordings instead of chunk speaker_name+ if not any(hasattr(desc, 'name') and desc.name == 'recording' for desc in chunks_query.column_descriptions):+ chunks_query = chunks_query.join(Recording)++ # Build OR conditions for each speaker name in participants+ speaker_conditions = []+ for speaker_name in filters['speaker_names']:+ speaker_conditions.append(+ Recording.participants.ilike(f'%{speaker_name}%')+ )++ chunks_query = chunks_query.filter(db.or_(*speaker_conditions))+ app.logger.info(f"Applied speaker filter for: {filters['speaker_names']}")++ if filters.get('recording_ids'):+ chunks_query = chunks_query.filter(+ TranscriptChunk.recording_id.in_(filters['recording_ids'])+ )++ if filters.get('date_from') or filters.get('date_to'):+ chunks_query = chunks_query.join(Recording)+ if filters.get('date_from'):+ chunks_query = chunks_query.filter(Recording.meeting_date >= filters['date_from'])+ if filters.get('date_to'):+ chunks_query = chunks_query.filter(Recording.meeting_date <= filters['date_to'])++ # Simple text search - split query into words and search for them+ query_words = query.lower().split()+ if query_words:+ # Create a filter that matches any of the query words in the content+ text_conditions = []+ for word in query_words:+ text_conditions.append(TranscriptChunk.content.ilike(f'%{word}%'))++ # Combine conditions with OR+ from sqlalchemy import or_+ chunks_query = chunks_query.filter(or_(*text_conditions))++ # Get chunks and return with dummy similarity scores+ chunks = chunks_query.limit(top_k).all()++ # Return chunks with dummy similarity scores (1.0 for found chunks)+ return [(chunk, 1.0) for chunk in chunks]++ except Exception as e:+ app.logger.error(f"Error in basic text search: {e}")+ return []++def semantic_search_chunks(user_id, query, filters=None, top_k=5):+ """+ Perform semantic search on transcript chunks with filtering.++ Args:+ user_id (int): User ID for permission filtering+ query (str): Search query+ filters (dict): Optional filters for tags, speakers, dates, recording_ids+ top_k (int): Number of top chunks to return++ Returns:+ list: List of relevant chunks with similarity scores+ """+ try:+ # If embeddings are not available, fall back to basic text search+ if not EMBEDDINGS_AVAILABLE:+ app.logger.info("Embeddings not available - using basic text search as fallback")+ return basic_text_search_chunks(user_id, query, filters, top_k)++ # Generate embedding for the query+ model = get_embedding_model()+ if not model:+ return basic_text_search_chunks(user_id, query, filters, top_k)++ query_embedding = model.encode([query])[0]++ # Build base query for chunks with eager loading of recording relationship+ chunks_query = TranscriptChunk.query.options(joinedload(TranscriptChunk.recording)).filter_by(user_id=user_id)++ # Apply filters if provided+ if filters:+ if filters.get('tag_ids'):+ # Join with recordings that have specified tags+ chunks_query = chunks_query.join(Recording).join(+ RecordingTag, Recording.id == RecordingTag.recording_id+ ).filter(RecordingTag.tag_id.in_(filters['tag_ids']))++ if filters.get('speaker_names'):+ # Filter by participants field in recordings instead of chunk speaker_name+ if not any(hasattr(desc, 'name') and desc.name == 'recording' for desc in chunks_query.column_descriptions):+ chunks_query = chunks_query.join(Recording)++ # Build OR conditions for each speaker name in participants+ speaker_conditions = []+ for speaker_name in filters['speaker_names']:+ speaker_conditions.append(+ Recording.participants.ilike(f'%{speaker_name}%')+ )++ chunks_query = chunks_query.filter(db.or_(*speaker_conditions))+ app.logger.info(f"Applied speaker filter for: {filters['speaker_names']}")++ if filters.get('recording_ids'):+ chunks_query = chunks_query.filter(+ TranscriptChunk.recording_id.in_(filters['recording_ids'])+ )++ if filters.get('date_from') or filters.get('date_to'):+ chunks_query = chunks_query.join(Recording)+ if filters.get('date_from'):+ chunks_query = chunks_query.filter(Recording.meeting_date >= filters['date_from'])+ if filters.get('date_to'):+ chunks_query = chunks_query.filter(Recording.meeting_date <= filters['date_to'])++ # Get chunks that have embeddings+ chunks = chunks_query.filter(TranscriptChunk.embedding.isnot(None)).all()++ if not chunks:+ return []++ # Calculate similarities+ chunk_similarities = []+ for chunk in chunks:+ try:+ chunk_embedding = deserialize_embedding(chunk.embedding)+ if chunk_embedding is not None:+ similarity = cosine_similarity(+ query_embedding.reshape(1, -1),+ chunk_embedding.reshape(1, -1)+ )[0][0]+ chunk_similarities.append((chunk, float(similarity)))+ except Exception as e:+ app.logger.warning(f"Error calculating similarity for chunk {chunk.id}: {e}")+ continue++ # Sort by similarity and return top k+ chunk_similarities.sort(key=lambda x: x[1], reverse=True)+ return chunk_similarities[:top_k]++ except Exception as e:+ app.logger.error(f"Error in semantic search: {e}")+ return []+# --- Database Models ---class User(db.Model, UserMixin):id = db.Column(db.Integer, primary_key=True)@@ -695,6 +1032,67 @@ class Recording(db.Model):'tags': [tag.to_dict() for tag in self.tags] if self.tags else []}+class TranscriptChunk(db.Model):+ """Stores chunked transcription segments for efficient retrieval and embedding."""+ id = db.Column(db.Integer, primary_key=True)+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)+ chunk_index = db.Column(db.Integer, nullable=False) # Order within the recording+ content = db.Column(db.Text, nullable=False) # The actual text chunk+ start_time = db.Column(db.Float, nullable=True) # Start time in seconds (if available)+ end_time = db.Column(db.Float, nullable=True) # End time in seconds (if available)+ speaker_name = db.Column(db.String(100), nullable=True) # Speaker for this chunk+ embedding = db.Column(db.LargeBinary, nullable=True) # Stored as binary vector+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ # Relationships+ recording = db.relationship('Recording', backref=db.backref('chunks', lazy=True, cascade='all, delete-orphan'))+ user = db.relationship('User', backref=db.backref('transcript_chunks', lazy=True, cascade='all, delete-orphan'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'recording_id': self.recording_id,+ 'chunk_index': self.chunk_index,+ 'content': self.content,+ 'start_time': self.start_time,+ 'end_time': self.end_time,+ 'speaker_name': self.speaker_name,+ 'created_at': self.created_at.isoformat() if self.created_at else None+ }++class InquireSession(db.Model):+ """Tracks inquire mode sessions and their filtering criteria."""+ id = db.Column(db.Integer, primary_key=True)+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)+ session_name = db.Column(db.String(200), nullable=True) # Optional user-defined name++ # Filter criteria (JSON stored as text)+ filter_tags = db.Column(db.Text, nullable=True) # JSON array of tag IDs+ filter_speakers = db.Column(db.Text, nullable=True) # JSON array of speaker names+ filter_date_from = db.Column(db.Date, nullable=True)+ filter_date_to = db.Column(db.Date, nullable=True)+ filter_recording_ids = db.Column(db.Text, nullable=True) # JSON array of specific recording IDs++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ last_used = db.Column(db.DateTime, default=datetime.utcnow)++ # Relationships+ user = db.relationship('User', backref=db.backref('inquire_sessions', lazy=True, cascade='all, delete-orphan'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'session_name': self.session_name,+ 'filter_tags': json.loads(self.filter_tags) if self.filter_tags else [],+ 'filter_speakers': json.loads(self.filter_speakers) if self.filter_speakers else [],+ 'filter_date_from': self.filter_date_from.isoformat() if self.filter_date_from else None,+ 'filter_date_to': self.filter_date_to.isoformat() if self.filter_date_to else None,+ 'filter_recording_ids': json.loads(self.filter_recording_ids) if self.filter_recording_ids else [],+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'last_used': self.last_used.isoformat() if self.last_used else None+ }+# --- Forms for Authentication ---# --- Custom Password Validator ---def password_check(form, field):@@ -786,6 +1184,26 @@ def delete_share(share_id):db.session.commit()return jsonify({'success': True})+# --- System Info API Endpoint ---[email protected]('/api/system/info', methods=['GET'])+def get_system_info():+ """Get system information including version and model details."""+ try:+ # Use the same version detection logic as startup+ version = get_version()++ return jsonify({+ 'version': version,+ 'llm_endpoint': TEXT_MODEL_BASE_URL,+ 'llm_model': TEXT_MODEL_NAME,+ 'whisper_endpoint': os.environ.get('TRANSCRIPTION_BASE_URL', 'https://api.openai.com/v1'),+ 'asr_enabled': USE_ASR_ENDPOINT,+ 'asr_endpoint': ASR_BASE_URL if USE_ASR_ENDPOINT else None+ })+ except Exception as e:+ app.logger.error(f"Error getting system info: {e}")+ return jsonify({'error': 'Unable to retrieve system information'}), 500+# --- Tag API Endpoints ---@app.route('/api/tags', methods=['GET'])@login_required@@ -1040,6 +1458,64 @@ with app.app_context():setting_type='integer')app.logger.info("Initialized default max_file_size_mb setting")++ # Process existing recordings for inquire mode (chunk and embed them)+ # Only run if inquire mode is enabled+ if ENABLE_INQUIRE_MODE:+ # Use a file lock to prevent multiple workers from running this simultaneously+ import fcntl+ import tempfile+ lock_file_path = os.path.join(tempfile.gettempdir(), 'inquire_migration.lock')++ try:+ with open(lock_file_path, 'w') as lock_file:+ # Try to acquire exclusive lock (non-blocking)+ try:+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ app.logger.info("Acquired migration lock, checking for existing recordings that need chunking for inquire mode...")++ completed_recordings = Recording.query.filter_by(status='COMPLETED').all()+ recordings_needing_processing = []++ for recording in completed_recordings:+ if recording.transcription: # Has transcription+ chunk_count = TranscriptChunk.query.filter_by(recording_id=recording.id).count()+ if chunk_count == 0: # No chunks yet+ recordings_needing_processing.append(recording)++ if recordings_needing_processing:+ app.logger.info(f"Found {len(recordings_needing_processing)} recordings that need chunking for inquire mode")+ app.logger.info("Processing first 10 recordings automatically. Use admin API or migration script for remaining recordings.")++ # Process first 10 recordings automatically to avoid long startup times+ batch_size = min(10, len(recordings_needing_processing))+ processed = 0++ for i in range(batch_size):+ recording = recordings_needing_processing[i]+ try:+ success = process_recording_chunks(recording.id)+ if success:+ processed += 1+ app.logger.info(f"Processed chunks for recording: {recording.title} ({recording.id})")+ except Exception as e:+ app.logger.warning(f"Failed to process chunks for recording {recording.id}: {e}")++ remaining = len(recordings_needing_processing) - processed+ if remaining > 0:+ app.logger.info(f"Successfully processed {processed} recordings. {remaining} recordings remaining.")+ app.logger.info("Use the admin migration API or run 'python migrate_existing_recordings.py' to process remaining recordings.")+ else:+ app.logger.info(f"Successfully processed all {processed} recordings for inquire mode.")+ else:+ app.logger.info("All existing recordings are already processed for inquire mode.")++ except BlockingIOError:+ app.logger.info("Migration already running in another worker, skipping...")++ except Exception as e:+ app.logger.warning(f"Error during existing recordings migration: {e}")+ app.logger.info("Existing recordings can be migrated later using the admin API or migration script.")except Exception as e:app.logger.error(f"Error during database migration: {e}")@@ -1069,6 +1545,7 @@ except Exception as client_init_e:transcription_api_key = os.environ.get("TRANSCRIPTION_API_KEY", "cant-be-empty")transcription_base_url = os.environ.get("TRANSCRIPTION_BASE_URL", "https://openrouter.ai/api/v1")+# ASR endpoint configurationUSE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'ASR_BASE_URL = os.environ.get('ASR_BASE_URL')@@ -1098,7 +1575,30 @@ chunking_service = AudioChunkingService(overlap_seconds=CHUNK_OVERLAP_SECONDS) if ENABLE_CHUNKING else None-app.logger.info(f"Using OpenRouter model for summaries: {TEXT_MODEL_NAME}")+# Get and log version information at startup+def get_version():+ # Try reading VERSION file first (works in Docker)+ try:+ with open('VERSION', 'r') as f:+ return f.read().strip()+ except FileNotFoundError:+ pass++ # Fall back to git tags (works in development)+ try:+ import subprocess+ return subprocess.check_output(['git', 'describe', '--tags', '--abbrev=0'],+ stderr=subprocess.DEVNULL).decode().strip()+ except:+ pass++ # Final fallback+ return "unknown"++version = get_version()++app.logger.info(f"=== Speakr {version} Starting Up ===")+app.logger.info(f"Using LLM endpoint: {TEXT_MODEL_BASE_URL} with model: {TEXT_MODEL_NAME}")app.logger.info(f"Using Whisper API at: {transcription_base_url}")if USE_ASR_ENDPOINT:app.logger.info(f"ASR endpoint is enabled at: {ASR_BASE_URL}")@@ -1237,6 +1737,13 @@ Title:"""recording.status = 'COMPLETED'recording.completed_at = datetime.utcnow()db.session.commit()++ # Process chunks for semantic search after completion (if inquire mode is enabled)+ if ENABLE_INQUIRE_MODE:+ try:+ process_recording_chunks(recording_id)+ except Exception as e:+ app.logger.error(f"Error processing chunks for completed recording {recording_id}: {e}")def generate_summary_only_task(app_context, recording_id):"""Generates only a summary for a recording (no title, no JSON response).@@ -1307,12 +1814,15 @@ def generate_summary_only_task(app_context, recording_id):user_summary_prompt = recording.owner.summary_promptuser_output_language = recording.owner.output_language+ # 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 limittranscript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)if transcript_limit == -1:- transcript_text = recording.transcription+ transcript_text = formatted_transcriptionelse:- transcript_text = recording.transcription[:transcript_limit]+ transcript_text = formatted_transcription[:transcript_limit]language_directive = f"Please provide the summary in {user_output_language}." if user_output_language else ""@@ -1369,6 +1879,13 @@ Respond with only the summary in Markdown format. Do NOT wrap your response in mif user_output_language:system_message_content += f" Ensure your response is in {user_output_language}."+ # 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.")+ app.logger.debug(f"=== SUMMARIZATION DEBUG for recording {recording_id} ===")+ 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 SUMMARIZATION DEBUG for recording {recording_id} ===")+try:completion = client.chat.completions.create(model=TEXT_MODEL_NAME,@@ -1405,6 +1922,51 @@ Respond with only the summary in Markdown format. Do NOT wrap your response in mrecording.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."""+ try:+ # Generate output filename with audio extension+ base_filepath, file_ext = os.path.splitext(video_filepath)+ temp_audio_filepath = f"{base_filepath}_audio_temp.{output_format}"+ final_audio_filepath = f"{base_filepath}_audio.{output_format}"++ app.logger.info(f"Extracting audio from video: {video_filepath} -> {temp_audio_filepath}")++ # Extract audio using FFmpeg - optimized for transcription+ 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+ temp_audio_filepath+ ], check=True, capture_output=True, text=True)++ app.logger.info(f"Successfully extracted audio to {temp_audio_filepath}")++ # Rename temp file to final filename+ os.rename(temp_audio_filepath, final_audio_filepath)++ # Clean up original video file if requested+ if cleanup_original:+ try:+ os.remove(video_filepath)+ app.logger.info(f"Cleaned up original video file: {video_filepath}")+ except Exception as e:+ app.logger.warning(f"Failed to clean up original video file {video_filepath}: {str(e)}")++ return final_audio_filepath, f'audio/{output_format}'++ except subprocess.CalledProcessError as e:+ app.logger.error(f"FFmpeg audio extraction failed for {video_filepath}: {e.stderr}")+ raise Exception(f"Audio extraction failed: {e.stderr}")+ except FileNotFoundError:+ app.logger.error("FFmpeg command not found. Please ensure FFmpeg is installed and in the system's PATH.")+ raise Exception("Audio conversion tool (FFmpeg) not found on server.")+ except Exception as e:+ app.logger.error(f"Error extracting audio from {video_filepath}: {str(e)}")+ raise+def transcribe_audio_asr(app_context, recording_id, filepath, original_filename, start_time, mime_type=None, language=None, diarize=False, min_speakers=None, max_speakers=None, tag_id=None):"""Transcribes audio using the ASR webservice."""with app_context:@@ -1418,7 +1980,49 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,recording.status = 'PROCESSING'db.session.commit()- with open(filepath, 'rb') as audio_file:+ # Check if we need to extract audio from video container+ actual_filepath = filepath+ actual_content_type = mime_type or mimetypes.guess_type(original_filename)[0] or 'application/octet-stream'+ actual_filename = original_filename++ # List of video MIME types that need audio extraction+ video_mime_types = [+ 'video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/webm',+ 'video/avi', 'video/x-ms-wmv', 'video/3gpp'+ ]++ # Check if file is a video container by MIME type or extension+ is_video = (+ actual_content_type.startswith('video/') or+ actual_content_type in video_mime_types or+ original_filename.lower().endswith(('.mp4', '.mov', '.avi', '.mkv', '.webm', '.wmv', '.3gp'))+ )++ if is_video:+ 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')++ # Update paths and MIME type for ASR processing+ actual_filepath = audio_filepath+ actual_content_type = audio_mime_type+ actual_filename = os.path.basename(audio_filepath)++ # Update recording with extracted audio path and new MIME type+ recording.audio_path = audio_filepath+ recording.mime_type = audio_mime_type+ db.session.commit()++ app.logger.info(f"Audio extracted successfully: {audio_filepath}")+ except Exception as e:+ app.logger.error(f"Failed to extract audio from video: {str(e)}")+ recording.status = 'FAILED'+ recording.error_msg = f"Audio extraction failed: {str(e)}"+ db.session.commit()+ return++ with open(actual_filepath, 'rb') as audio_file:url = f"{ASR_BASE_URL}/asr"params = {'encode': True,@@ -1434,10 +2038,9 @@ def transcribe_audio_asr(app_context, recording_id, filepath, original_filename,if max_speakers:params['max_speakers'] = max_speakers- # Use the stored mime_type, or guess it, with a fallback.- content_type = mime_type or mimetypes.guess_type(original_filename)[0] or 'application/octet-stream'+ content_type = actual_content_typeapp.logger.info(f"Using MIME type {content_type} for ASR upload.")- files = {'audio_file': (original_filename, audio_file, content_type)}+ files = {'audio_file': (actual_filename, audio_file, content_type)}with httpx.Client() as client:# Set reasonable timeout to prevent hanging (30 minutes max)@@ -1570,6 +2173,9 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,# Environment variable ASR_DIARIZE overrides user settingif 'ASR_DIARIZE' in os.environ:diarize_setting = ASR_DIARIZE+ elif USE_ASR_ENDPOINT:+ # When using ASR endpoint, use the configured ASR_DIARIZE value+ diarize_setting = ASR_DIARIZEelse:diarize_setting = recording.owner.diarize if recording.owner else False@@ -1662,7 +2268,42 @@ def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr,def transcribe_single_file(filepath, recording):"""Transcribe a single audio file using OpenAI Whisper API."""- with open(filepath, 'rb') as audio_file:++ # Check if we need to extract audio from video container+ actual_filepath = filepath+ mime_type = recording.mime_type if recording else None++ # Detect video containers+ is_video = False+ if mime_type:+ is_video = mime_type.startswith('video/')+ else:+ # Fallback to extension-based detection+ is_video = filepath.lower().endswith(('.mp4', '.mov', '.avi', '.mkv', '.webm', '.wmv', '.3gp'))++ if is_video:+ app.logger.info(f"Video container detected for Whisper transcription, extracting audio...")+ try:+ # Extract audio from video+ audio_filepath, audio_mime_type = extract_audio_from_video(filepath, 'wav')+ actual_filepath = audio_filepath++ # Update recording with extracted audio path and new MIME type if recording exists+ if recording:+ recording.audio_path = audio_filepath+ recording.mime_type = audio_mime_type+ db.session.commit()++ app.logger.info(f"Audio extracted successfully for Whisper: {audio_filepath}")+ except Exception as e:+ app.logger.error(f"Failed to extract audio from video for Whisper: {str(e)}")+ if recording:+ recording.status = 'FAILED'+ recording.error_msg = f"Audio extraction failed: {str(e)}"+ db.session.commit()+ raise Exception(f"Audio extraction failed: {str(e)}")++ with open(actual_filepath, 'rb') as audio_file:transcription_client = OpenAI(api_key=transcription_api_key,base_url=transcription_base_url,@@ -2790,6 +3431,9 @@ def reprocess_transcription(recording_id):max_speakers = Noneif 'ASR_DIARIZE' in os.environ:diarize_setting = ASR_DIARIZE+ elif USE_ASR_ENDPOINT:+ # When using ASR endpoint, use the configured ASR_DIARIZE value+ diarize_setting = ASR_DIARIZEelse:diarize_setting = recording.owner.diarize if recording.owner else False@@ -2902,13 +3546,16 @@ 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 reprocessingtranscript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)if transcript_limit == -1:# No limit- transcript_text = recording.transcription+ transcript_text = formatted_transcriptionelse:- transcript_text = recording.transcription[:transcript_limit]+ 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.@@ -2933,11 +3580,14 @@ JSON Response:"""if user_output_language:system_message_content += f" Ensure your response (both title and summary) is in {user_output_language}."- # Log the request details for debugging+ # Debug logging: Log the complete prompt being sent to the LLMapp.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 length: {len(system_message_content)}")- app.logger.debug(f"User prompt length: {len(prompt_text)}")+ 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 APIcompletion = client.chat.completions.create(@@ -3274,7 +3924,7 @@ def admin():if not current_user.is_admin:flash('You do not have permission to access the admin page.', 'danger')return redirect(url_for('index'))- return render_template('admin.html', title='Admin Dashboard')+ return render_template('admin.html', title='Admin Dashboard', inquire_mode_enabled=ENABLE_INQUIRE_MODE)@app.route('/admin/users', methods=['GET'])@login_required@@ -3412,6 +4062,12 @@ def admin_delete_user(user_id):return jsonify({'error': 'User not found'}), 404# Delete user's recordings and audio files+ total_chunks = 0+ if ENABLE_INQUIRE_MODE:+ total_chunks = TranscriptChunk.query.filter_by(user_id=user_id).count()+ if total_chunks > 0:+ app.logger.info(f"Deleting {total_chunks} transcript chunks with embeddings for user {user_id}")+for recording in user.recordings:try:if recording.audio_path and os.path.exists(recording.audio_path):@@ -3419,10 +4075,13 @@ def admin_delete_user(user_id):except Exception as e:app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")- # Delete user+ # Delete user (cascade will handle all related data including chunks/embeddings)db.session.delete(user)db.session.commit()+ if ENABLE_INQUIRE_MODE and total_chunks > 0:+ app.logger.info(f"Successfully deleted {total_chunks} embeddings and chunks for user {user_id}")+return jsonify({'success': True})@app.route('/admin/users/<int:user_id>/toggle-admin', methods=['POST'])@@ -3594,8 +4253,18 @@ def get_csrf_token():@app.route('/')@login_requireddef index():- # Pass the ASR config to the template- return render_template('index.html', use_asr_endpoint=USE_ASR_ENDPOINT)+ # Pass the ASR config and inquire mode config to the template+ return render_template('index.html', use_asr_endpoint=USE_ASR_ENDPOINT, inquire_mode_enabled=ENABLE_INQUIRE_MODE)+[email protected]('/inquire')+@login_required+def inquire():+ # Check if inquire mode is enabled+ if not ENABLE_INQUIRE_MODE:+ flash('Inquire mode is not enabled on this server.', 'warning')+ return redirect(url_for('index'))+ # Render the inquire page with user context for theming+ return render_template('inquire.html', use_asr_endpoint=USE_ASR_ENDPOINT, current_user=current_user)@app.route('/recordings', methods=['GET'])def get_recordings():@@ -3783,7 +4452,12 @@ def upload_file():should_enforce_size_limit = Trueif ENABLE_CHUNKING and chunking_service and not USE_ASR_ENDPOINT:should_enforce_size_limit = False- app.logger.info(f"Chunking enabled for OpenAI Whisper API - skipping {original_file_size/1024/1024:.1f}MB size limit check")+ # Get chunking mode for better logging+ mode, limit_value = chunking_service.parse_chunk_limit()+ if mode == 'size':+ app.logger.info(f"Size-based chunking enabled ({limit_value}MB limit) - skipping {original_file_size/1024/1024:.1f}MB size limit check")+ else:+ app.logger.info(f"Duration-based chunking enabled ({limit_value}s limit) - skipping {original_file_size/1024/1024:.1f}MB size limit check")if should_enforce_size_limit and max_content_length and original_file_size > max_content_length:raise RequestEntityTooLarge()@@ -3798,7 +4472,7 @@ def upload_file():needs_chunking_for_processing = (chunking_service andENABLE_CHUNKING andnot USE_ASR_ENDPOINT and- original_file_size > (CHUNK_SIZE_MB * 1024 * 1024)) # Use configured chunk size threshold+ chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT))# Define supported formats based on whether chunking is neededif needs_chunking_for_processing:@@ -4077,10 +4751,19 @@ def delete_recording(recording_id):except Exception as e:app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")- # Delete the database record+ # Log embeddings cleanup for Inquire Mode if enabled+ if ENABLE_INQUIRE_MODE:+ chunk_count = TranscriptChunk.query.filter_by(recording_id=recording_id).count()+ if chunk_count > 0:+ app.logger.info(f"Deleting {chunk_count} transcript chunks with embeddings for recording {recording_id}")++ # Delete the database record (cascade will handle chunks/embeddings)db.session.delete(recording)db.session.commit()app.logger.info(f"Deleted recording record ID: {recording_id}")++ if ENABLE_INQUIRE_MODE and chunk_count > 0:+ app.logger.info(f"Successfully deleted embeddings and chunks for recording {recording_id}")return jsonify({'success': True})except Exception as e:@@ -4089,6 +4772,762 @@ def delete_recording(recording_id):return jsonify({'error': 'An unexpected error occurred while deleting.'}), 500+# --- Inquire Mode API Endpoints ---+[email protected]('/api/inquire/sessions', methods=['GET'])+@login_required+def get_inquire_sessions():+ """Get all inquire sessions for the current user."""+ if not ENABLE_INQUIRE_MODE:+ return jsonify({'error': 'Inquire mode is not enabled'}), 403+ try:+ sessions = InquireSession.query.filter_by(user_id=current_user.id).order_by(InquireSession.last_used.desc()).all()+ return jsonify([session.to_dict() for session in sessions])+ except Exception as e:+ app.logger.error(f"Error getting inquire sessions: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/api/inquire/sessions', methods=['POST'])+@login_required+def create_inquire_session():+ """Create a new inquire session with filters."""+ if not ENABLE_INQUIRE_MODE:+ return jsonify({'error': 'Inquire mode is not enabled'}), 403+ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ session = InquireSession(+ user_id=current_user.id,+ session_name=data.get('session_name'),+ filter_tags=json.dumps(data.get('filter_tags', [])),+ filter_speakers=json.dumps(data.get('filter_speakers', [])),+ filter_date_from=datetime.fromisoformat(data['filter_date_from']).date() if data.get('filter_date_from') else None,+ filter_date_to=datetime.fromisoformat(data['filter_date_to']).date() if data.get('filter_date_to') else None,+ filter_recording_ids=json.dumps(data.get('filter_recording_ids', []))+ )++ db.session.add(session)+ db.session.commit()++ return jsonify(session.to_dict()), 201++ except Exception as e:+ app.logger.error(f"Error creating inquire session: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/api/inquire/search', methods=['POST'])+@login_required+def inquire_search():+ """Perform semantic search within filtered transcriptions."""+ if not ENABLE_INQUIRE_MODE:+ return jsonify({'error': 'Inquire mode is not enabled'}), 403+ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ query = data.get('query')+ if not query:+ return jsonify({'error': 'No query provided'}), 400++ # Build filters from request+ filters = {}+ if data.get('filter_tags'):+ filters['tag_ids'] = data['filter_tags']+ if data.get('filter_speakers'):+ filters['speaker_names'] = data['filter_speakers']+ if data.get('filter_recording_ids'):+ filters['recording_ids'] = data['filter_recording_ids']+ if data.get('filter_date_from'):+ filters['date_from'] = datetime.fromisoformat(data['filter_date_from']).date()+ if data.get('filter_date_to'):+ filters['date_to'] = datetime.fromisoformat(data['filter_date_to']).date()++ # Perform semantic search+ top_k = data.get('top_k', 5)+ chunk_results = semantic_search_chunks(current_user.id, query, filters, top_k)++ # Format results+ results = []+ for chunk, similarity in chunk_results:+ result = chunk.to_dict()+ result['similarity'] = similarity+ result['recording_title'] = chunk.recording.title+ result['recording_meeting_date'] = chunk.recording.meeting_date.isoformat() if chunk.recording.meeting_date else None+ results.append(result)++ return jsonify({'results': results})++ except Exception as e:+ app.logger.error(f"Error in inquire search: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/api/inquire/chat', methods=['POST'])+@login_required+def inquire_chat():+ """Chat with filtered transcriptions using RAG."""+ if not ENABLE_INQUIRE_MODE:+ return jsonify({'error': 'Inquire mode is not enabled'}), 403+ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ user_message = data.get('message')+ message_history = data.get('message_history', [])++ if not user_message:+ return jsonify({'error': 'No message provided'}), 400++ # Check if OpenRouter client is available+ if client is None:+ return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503++ # Build filters from request+ filters = {}+ if data.get('filter_tags'):+ filters['tag_ids'] = data['filter_tags']+ if data.get('filter_speakers'):+ filters['speaker_names'] = data['filter_speakers']+ if data.get('filter_recording_ids'):+ filters['recording_ids'] = data['filter_recording_ids']+ if data.get('filter_date_from'):+ filters['date_from'] = datetime.fromisoformat(data['filter_date_from']).date()+ if data.get('filter_date_to'):+ filters['date_to'] = datetime.fromisoformat(data['filter_date_to']).date()++ # Debug logging+ app.logger.info(f"Inquire chat - User: {current_user.username}, Query: '{user_message}', Filters: {filters}")++ # Capture user context before generator to avoid current_user being None+ user_id = current_user.id+ user_name = current_user.name if current_user.name else "the user"+ user_title = current_user.job_title if current_user.job_title else "professional"+ user_company = current_user.company if current_user.company else "their organization"+ user_output_language = current_user.output_language if current_user.output_language else None++ # Enhanced query processing with enrichment and debugging+ def create_status_response(status, message):+ """Helper to create SSE status updates"""+ return f"data: {json.dumps({'status': status, 'message': message})}\n\n"++ def generate_enhanced_chat():+ # Explicitly reference outer scope variables+ nonlocal user_id, user_name, user_title, user_company, user_output_language, data, filters++ try:+ # Send initial status+ yield create_status_response('processing', 'Analyzing your query...')++ # Step 1: Router - Determine if RAG lookup is needed+ router_prompt = f"""Analyze this user query to determine if it requires searching through transcription content or if it's a simple formatting/clarification request.++User query: "{user_message}"++Respond with ONLY "RAG" if the query requires searching transcriptions (asking about content, conversations, specific information from recordings).+Respond with ONLY "DIRECT" if it's a formatting request, clarification about previous responses, or doesn't require searching transcriptions.++Examples:+- "What did Beth say about the budget?" → RAG+- "Can you format this in separate headings?" → DIRECT+- "Who mentioned the timeline?" → RAG+- "Make this more structured" → DIRECT"""++ try:+ router_response = client.chat.completions.create(+ model=TEXT_MODEL_NAME,+ messages=[+ {"role": "system", "content": "You are a query router. Respond with only 'RAG' or 'DIRECT'."},+ {"role": "user", "content": router_prompt}+ ],+ temperature=0.1,+ max_tokens=10+ )++ route_decision = router_response.choices[0].message.content.strip().upper()+ app.logger.info(f"Router decision: {route_decision}")++ if route_decision == "DIRECT":+ # Direct response without RAG lookup+ yield create_status_response('responding', 'Generating direct response...')++ direct_prompt = f"""You are assisting {user_name}. Respond to their request directly using proper markdown formatting.++User request: "{user_message}"++Previous conversation context (if relevant):+{json.dumps(message_history[-2:] if message_history else [])}++Use proper markdown formatting including headings (##), bold (**text**), bullet points (-), etc."""++ stream = client.chat.completions.create(+ model=TEXT_MODEL_NAME,+ messages=[+ {"role": "system", "content": direct_prompt},+ {"role": "user", "content": user_message}+ ],+ temperature=0.7,+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),+ 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"+ return++ except Exception as e:+ app.logger.warning(f"Router failed, defaulting to RAG: {e}")++ # Step 2: Query enrichment - generate better search terms based on user intent+ yield create_status_response('enriching', 'Enriching search query...')++ # Use captured user context for personalized search terms++ enrichment_prompt = f"""You are a query enhancement assistant. Given a user's question about transcribed meetings/recordings, generate 3-5 alternative search terms or phrases that would help find relevant content in a semantic search system.++User context:+- Name: {user_name}+- Title: {user_title}+- Company: {user_company}++User question: "{user_message}"+Available context: Transcribed meetings and recordings with speakers: {', '.join(data.get('filter_speakers', []))}.++Generate search terms that would find relevant content. Focus on:+1. Key concepts and topics using the user's actual name instead of generic terms like "me"+2. Specific terminology that might be used in their professional context+3. Alternative phrasings of the question with proper names+4. Related terms that might appear in transcripts from their meetings++Examples:+- Instead of "what Beth told me" use "what Beth told {user_name}"+- Instead of "my last conversation" use "{user_name}'s conversation"+- Use their job title and company context when relevant++Respond with only a JSON array of strings: ["term1", "term2", "term3", ...]"""++ try:+ enrichment_response = client.chat.completions.create(+ model=TEXT_MODEL_NAME,+ messages=[+ {"role": "system", "content": "You are a query enhancement assistant. Respond only with valid JSON arrays of search terms."},+ {"role": "user", "content": enrichment_prompt}+ ],+ temperature=0.3,+ max_tokens=200+ )++ enriched_terms = json.loads(enrichment_response.choices[0].message.content.strip())+ app.logger.info(f"Enriched search terms: {enriched_terms}")++ # Combine original query with enriched terms for search+ search_queries = [user_message] + enriched_terms[:3] # Use original + top 3 enriched terms++ except Exception as e:+ app.logger.warning(f"Query enrichment failed, using original query: {e}")+ search_queries = [user_message]++ # Step 2: Semantic search with multiple queries+ yield create_status_response('searching', 'Searching transcriptions...')++ all_chunks = []+ seen_chunk_ids = set()++ for query in search_queries:+ with app.app_context():+ chunk_results = semantic_search_chunks(user_id, query, filters, 8)+ app.logger.info(f"Search query '{query}' returned {len(chunk_results)} chunks")++ for chunk, similarity in chunk_results:+ if chunk and chunk.id not in seen_chunk_ids:+ all_chunks.append((chunk, similarity))+ seen_chunk_ids.add(chunk.id)++ # Sort by similarity and take top results+ all_chunks.sort(key=lambda x: x[1], reverse=True)+ chunk_results = all_chunks[:data.get('context_chunks', 8)]++ app.logger.info(f"Final chunk results: {len(chunk_results)} chunks with similarities: {[f'{s:.3f}' for _, s in chunk_results]}")++ # Step 2.5: Auto-detect mentioned speakers and apply filters if needed+ with app.app_context():+ # Get available speakers+ recordings_with_participants = Recording.query.filter_by(user_id=user_id).filter(+ Recording.participants.isnot(None),+ Recording.participants != ''+ ).all()++ available_speakers = set()+ for recording in recordings_with_participants:+ if recording.participants:+ participants = [p.strip() for p in recording.participants.split(',') if p.strip()]+ available_speakers.update(participants)++ # Check if any speakers are mentioned in the user query but missing from results+ mentioned_speakers = []+ for speaker in available_speakers:+ if speaker.lower() in user_message.lower():+ # Check if this speaker appears in current chunk results+ speaker_in_results = False+ for chunk, _ in chunk_results:+ if chunk and (+ (chunk.speaker_name and speaker.lower() in chunk.speaker_name.lower()) or+ (chunk.recording and chunk.recording.participants and speaker.lower() in chunk.recording.participants.lower())+ ):+ speaker_in_results = True+ break++ if not speaker_in_results:+ mentioned_speakers.append(speaker)++ # If we found mentioned speakers not in results, automatically apply speaker filter+ if mentioned_speakers and not data.get('filter_speakers'): # Only if no speaker filter already applied+ app.logger.info(f"Auto-detected mentioned speakers not in results: {mentioned_speakers}")+ yield create_status_response('filtering', f'Detected mention of {", ".join(mentioned_speakers)}, applying speaker filter...')++ # Apply automatic speaker filter+ auto_filters = filters.copy()+ auto_filters['speaker_names'] = mentioned_speakers++ # Re-run semantic search with speaker filter+ auto_filtered_chunks = []+ auto_filtered_seen_ids = set()++ for query in search_queries:+ with app.app_context():+ auto_filtered_results = semantic_search_chunks(user_id, query, auto_filters, data.get('context_chunks', 8))+ app.logger.info(f"Auto-filtered search for '{query}' with speakers {mentioned_speakers} returned {len(auto_filtered_results)} chunks")++ for chunk, similarity in auto_filtered_results:+ if chunk and chunk.id not in auto_filtered_seen_ids:+ auto_filtered_chunks.append((chunk, similarity))+ auto_filtered_seen_ids.add(chunk.id)++ # If auto-filter found better results, use them+ if len(auto_filtered_chunks) > 0:+ auto_filtered_chunks.sort(key=lambda x: x[1], reverse=True)+ chunk_results = auto_filtered_chunks[:data.get('context_chunks', 8)]+ app.logger.info(f"Auto speaker filter found {len(chunk_results)} relevant chunks, using filtered results")+ filters = auto_filters # Update filters for context building++ # Step 3: Evaluate results and re-query if needed+ if len(chunk_results) < 2: # If we got very few results, try a broader search+ yield create_status_response('requerying', 'Expanding search scope...')++ # Try without speaker filter if it was applied+ broader_filters = filters.copy()+ if 'speaker_names' in broader_filters:+ del broader_filters['speaker_names']+ app.logger.info("Retrying search without speaker filter...")++ for query in search_queries:+ with app.app_context():+ chunk_results_broader = semantic_search_chunks(user_id, query, broader_filters, 6)+ for chunk, similarity in chunk_results_broader:+ if chunk and chunk.id not in seen_chunk_ids:+ all_chunks.append((chunk, similarity))+ seen_chunk_ids.add(chunk.id)++ # Re-sort and limit+ all_chunks.sort(key=lambda x: x[1], reverse=True)+ chunk_results = all_chunks[:data.get('context_chunks', 8)]+ app.logger.info(f"Broader search returned {len(chunk_results)} total chunks")++ # Build context from retrieved chunks+ yield create_status_response('contextualizing', 'Building context...')++ # Group chunks by recording and organize properly+ recording_chunks = {}+ recording_ids_in_context = set()++ for chunk, similarity in chunk_results:+ if not chunk or not chunk.recording:+ continue+ recording_id = chunk.recording.id+ recording_ids_in_context.add(recording_id)++ if recording_id not in recording_chunks:+ recording_chunks[recording_id] = {+ 'recording': chunk.recording,+ 'chunks': []+ }++ recording_chunks[recording_id]['chunks'].append({+ 'chunk': chunk,+ 'similarity': similarity+ })++ # Build organized context pieces+ context_pieces = []++ for recording_id, data in recording_chunks.items():+ recording = data['recording']+ chunks = data['chunks']++ # Sort chunks by their index to maintain chronological order+ chunks.sort(key=lambda x: x['chunk'].chunk_index)++ # Build recording header with complete metadata+ header = f"=== {recording.title} [Recording ID: {recording_id}] ==="+ if recording.meeting_date:+ header += f" ({recording.meeting_date})"++ # Add participants information+ if recording.participants:+ participants_list = [p.strip() for p in recording.participants.split(',') if p.strip()]+ header += f"\\nParticipants: {', '.join(participants_list)}"++ context_piece = header + "\\n\\n"++ # Process chunks and detect non-continuity+ prev_chunk_index = None+ for chunk_data in chunks:+ chunk = chunk_data['chunk']+ similarity = chunk_data['similarity']++ # Check for non-continuity+ if prev_chunk_index is not None and chunk.chunk_index != prev_chunk_index + 1:+ context_piece += "\\n[... gap in transcript - non-consecutive chunks ...]\\n\\n"++ # Add speaker information if available+ speaker_info = ""+ if chunk.speaker_name:+ speaker_info = f"{chunk.speaker_name}: "+ elif chunk.start_time is not None:+ speaker_info = f"[{chunk.start_time:.1f}s]: "++ # Add timing info if available+ timing_info = ""+ if chunk.start_time is not None and chunk.end_time is not None:+ timing_info = f" [{chunk.start_time:.1f}s-{chunk.end_time:.1f}s]"++ context_piece += f"{speaker_info}{chunk.content}{timing_info} (similarity: {similarity:.3f})\\n\\n"+ prev_chunk_index = chunk.chunk_index++ context_pieces.append(context_piece)++ app.logger.info(f"Built context from {len(chunk_results)} chunks across {len(recording_chunks)} recordings")++ # Generate response+ yield create_status_response('responding', 'Generating response...')++ # Prepare system prompt+ language_instruction = f"Please provide all your responses in {user_output_language}." if user_output_language else ""++ # Build filter description for context+ filter_description = []+ with app.app_context():+ if data.get('filter_tags'):+ tag_names = [tag.name for tag in Tag.query.filter(Tag.id.in_(data['filter_tags'])).all()]+ filter_description.append(f"tags: {', '.join(tag_names)}")+ if data.get('filter_speakers'):+ filter_description.append(f"speakers: {', '.join(data['filter_speakers'])}")+ if data.get('filter_date_from') or data.get('filter_date_to'):+ date_range = []+ if data.get('filter_date_from'):+ date_range.append(f"from {data['filter_date_from']}")+ if data.get('filter_date_to'):+ date_range.append(f"to {data['filter_date_to']}")+ filter_description.append(f"dates: {' '.join(date_range)}")++ filter_text = f" (filtered by {'; '.join(filter_description)})" if filter_description else ""++ context_text = "\n\n".join(context_pieces) if context_pieces else "No relevant context found."++ # Get transcript length limit setting and available speakers+ with app.app_context():+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)++ # Get all available speakers for this user+ recordings_with_participants = Recording.query.filter_by(user_id=user_id).filter(+ Recording.participants.isnot(None),+ Recording.participants != ''+ ).all()++ available_speakers = set()+ for recording in recordings_with_participants:+ if recording.participants:+ participants = [p.strip() for p in recording.participants.split(',') if p.strip()]+ available_speakers.update(participants)++ available_speakers = sorted(list(available_speakers))++ system_prompt = f"""You are a professional meeting and audio transcription analyst assisting {user_name}, who is a(n) {user_title} at {user_company}. {language_instruction}++You are analyzing transcriptions from multiple recordings{filter_text}. The following context has been retrieved based on semantic similarity to the user's question:++<<start context>>+{context_text}+<<end context>>++The system has automatically analyzed your query and retrieved the most relevant context from your transcriptions. The search returned {len(chunk_results)} chunks from {len(recording_ids_in_context)} recording(s).++**Available speakers in your recordings**: {', '.join(available_speakers) if available_speakers else 'None available'}++**Recording IDs in context**: {list(recording_ids_in_context)}++IMPORTANT FORMATTING INSTRUCTIONS:+You MUST use proper markdown formatting in your responses. Structure your response as follows:++1. **Always use markdown syntax** - Use `#`, `##`, `###` for headings, `**bold**`, `*italic*`, `-` for lists, etc.+2. Start with a brief summary or preamble if helpful+3. Organize information by source transcript using clear markdown headings+4. Use the format: `## [Recording Title] - [Date if available]`+5. Under each heading, provide the relevant information from that specific recording using bullet points and formatting+6. Include speaker names when referring to specific statements using **bold** formatting+7. Use bullet points (`-`) and sub-bullets for organizing information clearly++**Required Example Structure:**+Brief summary with **key points** highlighted...++## Meeting Discussion on Project Implementation - 2024-06-18+- **Speaker A** mentioned that "there's significant support needed for implementation"+- **Speaker B** confirmed the upcoming meeting with the technical team+- Key topics discussed:+ - Budget planning considerations+ - Timeline coordination needs++## Budget Planning Meeting - 2024-05-30+- **Speaker A** reviewed the budget document+- **Speaker C** will approve the final version for submission+- Important details:+ - Budget represents approximately 1/3 of the project total+ - Coordination needed for upcoming milestones++Order your response with notes from the most recent meetings first. Always use proper markdown formatting and structure by source recording for maximum clarity and readability."""++ # Prepare messages array+ messages = [{"role": "system", "content": system_prompt}]+ if message_history:+ messages.extend(message_history)+ messages.append({"role": "user", "content": user_message})++ # Enable streaming+ stream = client.chat.completions.create(+ model=TEXT_MODEL_NAME,+ messages=messages,+ temperature=0.7,+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),+ stream=True+ )++ # Buffer content to detect full transcript requests+ response_buffer = ""++ for chunk in stream:+ content = chunk.choices[0].delta.content+ if content:+ response_buffer += content++ # Check if this is a full transcript request+ if response_buffer.strip().startswith("REQUEST_FULL_TRANSCRIPT:"):+ lines = response_buffer.split('\n')+ request_line = lines[0].strip()++ if ':' in request_line:+ try:+ recording_id = int(request_line.split(':')[1])+ app.logger.info(f"Agent requested full transcript for recording {recording_id}")++ # Fetch full transcript+ yield create_status_response('fetching', f'Retrieving full transcript for recording {recording_id}...')++ with app.app_context():+ recording = db.session.get(Recording, recording_id)+ if recording and recording.user_id == user_id and recording.transcription:+ # Apply transcript length limit+ if transcript_limit == -1:+ full_transcript = recording.transcription+ else:+ full_transcript = recording.transcription[:transcript_limit]++ # Add full transcript to context+ full_context = f"{context_text}\n\n<<FULL TRANSCRIPT - {recording.title}>>\n{full_transcript}\n<<END FULL TRANSCRIPT>>"++ # Update system prompt with full transcript+ updated_system_prompt = system_prompt.replace(+ f"<<start context>>\n{context_text}\n<<end context>>",+ f"<<start context>>\n{full_context}\n<<end context>>"+ )++ # Create new messages with updated context+ updated_messages = [{"role": "system", "content": updated_system_prompt}]+ if message_history:+ updated_messages.extend(message_history)+ updated_messages.append({"role": "user", "content": user_message})++ # Generate new response with full context+ yield create_status_response('responding', 'Analyzing full transcript...')++ new_stream = client.chat.completions.create(+ model=TEXT_MODEL_NAME,+ messages=updated_messages,+ temperature=0.7,+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),+ 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"+ return+ else:+ # Recording not found or no permission+ error_msg = f"\n\nError: Unable to access full transcript for recording {recording_id}. Recording may not exist or you may not have permission."+ yield f"data: {json.dumps({'delta': error_msg})}\n\n"+ yield f"data: {json.dumps({'end_of_stream': True})}\n\n"+ return++ except (ValueError, IndexError):+ app.logger.warning(f"Invalid transcript request format: {request_line}")+ # Continue with normal streaming+ pass++ # Normal streaming - yield content as it comes+ yield f"data: {json.dumps({'delta': content})}\n\n"++ yield f"data: {json.dumps({'end_of_stream': True})}\n\n"++ except Exception as e:+ app.logger.error(f"Error in enhanced chat generation: {e}")+ yield f"data: {json.dumps({'error': str(e)})}\n\n"++ return Response(generate_enhanced_chat(), mimetype='text/event-stream')++ except Exception as e:+ app.logger.error(f"Error in inquire chat endpoint: {str(e)}")+ return jsonify({'error': str(e)}), 500+[email protected]('/api/recording/<int:recording_id>/process_chunks', methods=['POST'])+@login_required+def process_recording_chunks_endpoint(recording_id):+ """Process chunks for a specific recording."""+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ if recording.user_id != current_user.id:+ return jsonify({'error': 'Permission denied'}), 403++ success = process_recording_chunks(recording_id)+ if success:+ return jsonify({'message': 'Chunks processed successfully'})+ else:+ return jsonify({'error': 'Failed to process chunks'}), 500++ except Exception as e:+ app.logger.error(f"Error in process chunks endpoint: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/api/inquire/available_filters', methods=['GET'])+@login_required+def get_available_filters():+ """Get available filter options for the user."""+ if not ENABLE_INQUIRE_MODE:+ return jsonify({'error': 'Inquire mode is not enabled'}), 403+ try:+ # Get user's tags+ tags = Tag.query.filter_by(user_id=current_user.id).all()++ # Get unique speakers from user's recordings participants field+ recordings_with_participants = Recording.query.filter_by(user_id=current_user.id).filter(+ Recording.participants.isnot(None),+ Recording.participants != ''+ ).all()++ speaker_names = set()+ for recording in recordings_with_participants:+ if recording.participants:+ # Split participants by comma and clean up+ participants = [p.strip() for p in recording.participants.split(',') if p.strip()]+ speaker_names.update(participants)++ speaker_names = sorted(list(speaker_names))++ # Get user's recordings for recording-specific filtering+ recordings = Recording.query.filter_by(user_id=current_user.id).filter(+ Recording.status == 'COMPLETED'+ ).order_by(Recording.created_at.desc()).all()++ return jsonify({+ 'tags': [tag.to_dict() for tag in tags],+ 'speakers': speaker_names,+ 'recordings': [{'id': r.id, 'title': r.title, 'meeting_date': r.meeting_date.isoformat() if r.meeting_date else None} for r in recordings]+ })++ except Exception as e:+ app.logger.error(f"Error getting available filters: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/api/admin/migrate_recordings', methods=['POST'])+@login_required+def migrate_existing_recordings_api():+ """API endpoint to migrate existing recordings for inquire mode (admin only)."""+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized. Admin access required.'}), 403++ try:+ # Count recordings that need processing+ completed_recordings = Recording.query.filter_by(status='COMPLETED').all()+ recordings_needing_processing = []++ for recording in completed_recordings:+ if recording.transcription: # Has transcription+ chunk_count = TranscriptChunk.query.filter_by(recording_id=recording.id).count()+ if chunk_count == 0: # No chunks yet+ recordings_needing_processing.append(recording)++ if len(recordings_needing_processing) == 0:+ return jsonify({+ 'success': True,+ 'message': 'All recordings are already processed for inquire mode',+ 'processed': 0,+ 'total': len(completed_recordings)+ })++ # Process in small batches to avoid timeout+ batch_size = min(5, len(recordings_needing_processing)) # Process max 5 at a time+ processed = 0+ errors = 0++ for i in range(min(batch_size, len(recordings_needing_processing))):+ recording = recordings_needing_processing[i]+ try:+ success = process_recording_chunks(recording.id)+ if success:+ processed += 1+ else:+ errors += 1+ except Exception as e:+ app.logger.error(f"Error processing recording {recording.id} for migration: {e}")+ errors += 1++ remaining = max(0, len(recordings_needing_processing) - batch_size)++ return jsonify({+ 'success': True,+ 'message': f'Processed {processed} recordings. {remaining} remaining.',+ 'processed': processed,+ 'errors': errors,+ 'remaining': remaining,+ 'total': len(recordings_needing_processing)+ })++ except Exception as e:+ app.logger.error(f"Error in migration API: {e}")+ return jsonify({'error': str(e)}), 500++# --- Auto-Processing File Monitor Integration ---def initialize_file_monitor():"""Initialize file monitor after app is fully loaded to avoid circular imports."""@@ -4202,6 +5641,126 @@ def admin_update_auto_process_config():app.logger.error(f"Error updating auto-process config: {e}")return jsonify({'error': str(e)}), 500[email protected]('/admin/inquire/process-recordings', methods=['POST'])+@login_required+def admin_process_recordings_for_inquire():+ """Process all remaining recordings for inquire mode (chunk and embed them)."""+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ try:+ # Get optional parameters from request+ data = request.json or {}+ batch_size = data.get('batch_size', 10)+ max_recordings = data.get('max_recordings', None)++ # Find recordings that need processing+ completed_recordings = Recording.query.filter_by(status='COMPLETED').all()+ recordings_needing_processing = []++ for recording in completed_recordings:+ if recording.transcription: # Has transcription+ chunk_count = TranscriptChunk.query.filter_by(recording_id=recording.id).count()+ if chunk_count == 0: # No chunks yet+ recordings_needing_processing.append(recording)+ if max_recordings and len(recordings_needing_processing) >= max_recordings:+ break++ total_to_process = len(recordings_needing_processing)++ if total_to_process == 0:+ return jsonify({+ 'success': True,+ 'message': 'All recordings are already processed for inquire mode.',+ 'processed': 0,+ 'total': 0+ })++ # Process recordings in batches+ processed = 0+ failed = []++ for recording in recordings_needing_processing:+ try:+ success = process_recording_chunks(recording.id)+ if success:+ processed += 1+ app.logger.info(f"Admin API: Processed chunks for recording: {recording.title} ({recording.id})")+ else:+ failed.append({'id': recording.id, 'title': recording.title, 'reason': 'Processing returned false'})+ except Exception as e:+ app.logger.error(f"Admin API: Failed to process recording {recording.id}: {e}")+ failed.append({'id': recording.id, 'title': recording.title, 'reason': str(e)})++ # Commit after each batch+ if processed % batch_size == 0:+ db.session.commit()++ # Final commit+ db.session.commit()++ return jsonify({+ 'success': True,+ 'message': f'Processed {processed} out of {total_to_process} recordings.',+ 'processed': processed,+ 'total': total_to_process,+ 'failed': failed+ })++ except Exception as e:+ app.logger.error(f"Error in admin process recordings endpoint: {e}")+ db.session.rollback()+ return jsonify({'error': str(e)}), 500+[email protected]('/admin/inquire/status', methods=['GET'])+@login_required+def admin_inquire_status():+ """Get the status of recordings for inquire mode."""+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ try:+ # Count total completed recordings+ total_completed = Recording.query.filter_by(status='COMPLETED').count()++ # Count recordings with transcriptions+ recordings_with_transcriptions = Recording.query.filter(+ Recording.status == 'COMPLETED',+ Recording.transcription.isnot(None),+ Recording.transcription != ''+ ).count()++ # Count recordings that have been processed for inquire mode+ processed_recordings = db.session.query(Recording.id).join(+ TranscriptChunk, Recording.id == TranscriptChunk.recording_id+ ).distinct().count()++ # Count recordings that still need processing+ completed_recordings = Recording.query.filter_by(status='COMPLETED').all()+ need_processing = 0++ for recording in completed_recordings:+ if recording.transcription: # Has transcription+ chunk_count = TranscriptChunk.query.filter_by(recording_id=recording.id).count()+ if chunk_count == 0: # No chunks yet+ need_processing += 1++ # Get total chunks and embeddings count+ total_chunks = TranscriptChunk.query.count()++ return jsonify({+ 'total_completed_recordings': total_completed,+ 'recordings_with_transcriptions': recordings_with_transcriptions,+ 'processed_for_inquire': processed_recordings,+ 'need_processing': need_processing,+ 'total_chunks': total_chunks,+ 'embeddings_available': EMBEDDINGS_AVAILABLE+ })++ except Exception as e:+ app.logger.error(f"Error getting inquire status: {e}")+ return jsonify({'error': str(e)}), 500+with app.app_context():# Set dynamic MAX_CONTENT_LENGTH based on database settingmax_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)diff --git a/audio_chunking.py b/audio_chunking.pyindex dde8705c..5e610c2f 100644--- a/audio_chunking.py+++ b/audio_chunking.py@@ -11,6 +11,8 @@ import jsonimport subprocessimport tempfileimport logging+import math+import refrom typing import List, Dict, Any, Optional, Tuplefrom datetime import datetimeimport mimetypes@@ -21,39 +23,61 @@ logger = logging.getLogger(__name__)class AudioChunkingService:"""Service for chunking large audio files and processing them with OpenAI Whisper API."""- def __init__(self, max_chunk_size_mb: int = 20, overlap_seconds: int = 3):+ def __init__(self, max_chunk_size_mb: int = 20, overlap_seconds: int = 3, max_chunk_duration_seconds: int = None):"""Initialize the chunking service.Args:max_chunk_size_mb: Maximum size for each chunk in MB (default 20MB for safety margin)overlap_seconds: Overlap between chunks in seconds for context continuity+ max_chunk_duration_seconds: Maximum duration for each chunk in seconds (optional)"""self.max_chunk_size_mb = max_chunk_size_mbself.overlap_seconds = overlap_secondsself.max_chunk_size_bytes = max_chunk_size_mb * 1024 * 1024+ self.max_chunk_duration_seconds = max_chunk_duration_secondsself.chunk_stats = [] # Track processing statisticsdef needs_chunking(self, file_path: str, use_asr_endpoint: bool = False) -> bool:"""Check if a file needs to be chunked based on size and endpoint being used.+ NOTE: For duration-based limits, this may return True even if chunking isn't needed,+ because we need to convert the file first to check duration. The actual chunking+ decision is made after conversion in calculate_optimal_chunking().+Args:file_path: Path to the audio fileuse_asr_endpoint: Whether ASR endpoint is being used (no chunking needed)Returns:- True if file needs chunking, False otherwise+ True if file might need chunking, False otherwise"""if use_asr_endpoint:return Falsetry:file_size = os.path.getsize(file_path)- # Use configured chunk size limit from environment- chunk_size_mb = float(os.environ.get('CHUNK_SIZE_MB', '20')) # Default 20MB- chunk_size_bytes = chunk_size_mb * 1024 * 1024- return file_size > chunk_size_bytes+ mode, limit_value = self.parse_chunk_limit()++ if mode == 'size':+ # For size-based limits, we can determine immediately+ chunk_size_bytes = limit_value * 1024 * 1024+ needs_it = file_size > chunk_size_bytes+ logger.info(f"Size check: {file_size/1024/1024:.1f}MB vs limit {limit_value}MB - needs chunking: {needs_it}")+ return needs_it+ else:+ # For duration-based limits, we need to check the actual duration+ # Try to get duration without conversion first (fast check)+ duration = self.get_audio_duration(file_path)+ if duration:+ needs_it = duration > limit_value+ logger.info(f"Duration check: {duration:.1f}s vs limit {limit_value}s - needs chunking: {needs_it}")+ return needs_it+ else:+ # Can't determine duration without conversion, assume might need chunking+ logger.info(f"Duration-based limit set ({limit_value}s) but can't check duration yet - will check after conversion")+ return True # Proceed to conversion and checkexcept OSError:logger.error(f"Could not get file size for {file_path}")return False@@ -130,45 +154,103 @@ class AudioChunkingService:logger.error(f"Error converting file to WAV: {e}")raise- def calculate_chunk_duration_from_wav(self, wav_size: float, wav_duration: float) -> float:+ def parse_chunk_limit(self) -> Tuple[str, float]:+ """+ Parse the CHUNK_LIMIT environment variable to determine chunking mode and value.++ Supports formats:+ - Size-based: "20MB", "10MB"+ - Duration-based: "1200s", "20m"+ - Legacy: CHUNK_SIZE_MB environment variable (for backwards compatibility)++ Returns:+ Tuple of (mode, value) where mode is 'size' or 'duration'"""- Calculate optimal chunk duration based on actual WAV file size.+ chunk_limit = os.environ.get('CHUNK_LIMIT', '').strip().upper()++ # Check for new CHUNK_LIMIT format+ if chunk_limit:+ # Size-based: ends with MB+ if chunk_limit.endswith('MB'):+ try:+ size_mb = float(re.sub(r'[^0-9.]', '', chunk_limit))+ return 'size', size_mb+ except ValueError:+ logger.warning(f"Invalid CHUNK_LIMIT format: {chunk_limit}")++ # Duration-based: ends with s or m+ elif chunk_limit.endswith('S'):+ try:+ seconds = float(re.sub(r'[^0-9.]', '', chunk_limit))+ return 'duration', seconds+ except ValueError:+ logger.warning(f"Invalid CHUNK_LIMIT format: {chunk_limit}")++ elif chunk_limit.endswith('M'):+ try:+ minutes = float(re.sub(r'[^0-9.]', '', chunk_limit))+ return 'duration', minutes * 60+ except ValueError:+ logger.warning(f"Invalid CHUNK_LIMIT format: {chunk_limit}")++ # Fallback to legacy CHUNK_SIZE_MB for backwards compatibility+ legacy_size = os.environ.get('CHUNK_SIZE_MB', '20')+ try:+ size_mb = float(legacy_size)+ logger.info(f"Using legacy CHUNK_SIZE_MB: {size_mb}MB")+ return 'size', size_mb+ except ValueError:+ logger.warning(f"Invalid CHUNK_SIZE_MB format: {legacy_size}")+ return 'size', 20.0 # Ultimate fallback++ def calculate_optimal_chunking(self, converted_size: float, total_duration: float) -> Tuple[int, float]:+ """+ Calculate optimal number of chunks and chunk duration based on the configured limit.Args:- wav_size: Size of the WAV file in bytes- wav_duration: Duration of the WAV file in seconds+ converted_size: Size of the converted audio file in bytes+ total_duration: Total duration of the audio file in secondsReturns:- Chunk duration in seconds+ Tuple of (num_chunks, chunk_duration_seconds)"""try:- # Calculate actual bitrate from the WAV file- bitrate_bytes_per_sec = wav_size / wav_duration+ mode, limit_value = self.parse_chunk_limit()- # Use configured chunk size with improved safety factor- chunk_size_mb = float(os.environ.get('CHUNK_SIZE_MB', '20')) # Default 20MB- safety_factor = 0.95 # Use 95% of max size for better target accuracy- target_chunk_size = chunk_size_mb * 1024 * 1024 * safety_factor-- # Calculate duration based on target size, accounting for overlap- chunk_duration = (target_chunk_size / bitrate_bytes_per_sec) - self.overlap_seconds+ if mode == 'size':+ # Size-based chunking+ max_size_bytes = limit_value * 1024 * 1024 * 0.95 # 95% safety factor+ num_chunks = max(1, math.ceil(converted_size / max_size_bytes))++ logger.info(f"Size-based chunking: {limit_value}MB limit")+ logger.info(f"File size {converted_size/1024/1024:.1f}MB requires {num_chunks} chunks")++ else: # duration-based+ # Duration-based chunking with API safety limit+ effective_limit = min(limit_value, 1400) # Cap at OpenAI safe limit+ num_chunks = max(1, math.ceil(total_duration / effective_limit))++ logger.info(f"Duration-based chunking: {limit_value}s limit (effective: {effective_limit}s)")+ logger.info(f"File duration {total_duration:.1f}s requires {num_chunks} chunks")- # More flexible duration limits to allow reaching target chunk size- # Minimum 5 minutes, but allow longer chunks if needed to reach target size- min_duration = 300 # 5 minutes minimum- max_duration = max(3600, chunk_duration * 1.1) # At least 1 hour, or 110% of calculated duration+ # Calculate chunk duration+ chunk_duration = total_duration / num_chunks- chunk_duration = max(min_duration, min(max_duration, chunk_duration))+ # Apply minimum duration (5 minutes) but don't exceed file duration+ chunk_duration = min(max(300, chunk_duration), total_duration)- # Calculate what the actual chunk size will be with this duration- actual_chunk_size_mb = (bitrate_bytes_per_sec * (chunk_duration + self.overlap_seconds)) / (1024 * 1024)+ # Log final chunking plan+ expected_chunk_size_mb = (converted_size / num_chunks) / (1024 * 1024)+ logger.info(f"Chunking plan: {num_chunks} chunks of ~{chunk_duration:.1f}s each (~{expected_chunk_size_mb:.1f}MB each)")- logger.info(f"Calculated chunk duration: {chunk_duration:.1f}s (target: {target_chunk_size/1024/1024:.1f}MB, estimated actual: {actual_chunk_size_mb:.1f}MB) based on bitrate {bitrate_bytes_per_sec:.0f} bytes/sec")- return chunk_duration+ return num_chunks, chunk_durationexcept Exception as e:- logger.error(f"Error calculating chunk duration from WAV: {e}")- return 600 # Default 10 minutes (increased from 5)+ logger.error(f"Error calculating optimal chunking: {e}")+ # Conservative fallback+ fallback_chunks = max(2, math.ceil(total_duration / 600)) # 10-minute chunks+ fallback_duration = total_duration / fallback_chunks+ return fallback_chunks, fallback_durationdef create_chunks(self, file_path: str, temp_dir: str) -> List[Dict[str, Any]]:"""@@ -191,22 +273,61 @@ class AudioChunkingService:# Step 1: Convert to WAV and get accurate size/duration infowav_path, wav_duration, wav_size = self.convert_to_wav_and_get_info(file_path, temp_dir)- # Step 2: Calculate optimal chunk duration based on actual WAV file- chunk_duration = self.calculate_chunk_duration_from_wav(wav_size, wav_duration)+ # Step 2: Calculate optimal chunking strategy+ num_chunks, chunk_duration = self.calculate_optimal_chunking(wav_size, wav_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")+ # 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_path = os.path.join(temp_dir, chunk_filename)++ # Copy the converted file as the single chunk+ import shutil+ shutil.copy2(wav_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)+ }+ chunks.append(chunk_info)+ logger.info(f"Created single chunk for entire file: {wav_duration:.1f}s")+ return chunks++ # Calculate step size to create exactly num_chunks with overlap+ # Total coverage needed: wav_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)+ else:+ step_duration = wav_duration- step_duration = chunk_duration - self.overlap_secondscurrent_start = 0chunk_index = 0- logger.info(f"Splitting {file_path} into chunks of {chunk_duration}s with {self.overlap_seconds}s overlap")+ logger.info(f"Splitting {file_path} into {num_chunks} chunks of ~{chunk_duration:.1f}s with {self.overlap_seconds}s overlap")- while current_start < wav_duration:+ for chunk_index in range(num_chunks):+ # Calculate start position for this chunk+ if chunk_index > 0:+ current_start = chunk_index * step_duration+# Calculate end time for this chunkchunk_end = min(current_start + chunk_duration, wav_duration)actual_duration = chunk_end - current_start- # Skip very short chunks at the end+ # Skip very short chunks at the end (shouldn't happen with proper calculation)if actual_duration < 10: # Less than 10 seconds+ logger.warning(f"Skipping short chunk {chunk_index}: {actual_duration:.1f}s")break# Generate chunk filename@@ -252,10 +373,6 @@ class AudioChunkingService:logger.info(f"Created chunk {chunk_index}: {current_start:.1f}s-{chunk_end:.1f}s ({chunk_size/1024/1024:.1f}MB)")else:logger.error(f"Chunk file not created: {chunk_path}")-- # Move to next chunk- current_start += step_duration- chunk_index += 1logger.info(f"Created {len(chunks)} chunks for {file_path}")return chunksdiff --git a/env.asr.example b/env.asr.exampleindex bb60c861..37fefc6c 100644--- a/env.asr.example+++ b/env.asr.example@@ -14,6 +14,7 @@ TEXT_MODEL_NAME=openai/gpt-4o-mini# --- Transcription Service (ASR Endpoint) ---# Setting this to true enables all ASR features including speaker diarization+# Note: File chunking is NOT supported with ASR endpointsUSE_ASR_ENDPOINT=true# ASR Endpoint URL (e.g., http://localhost:9000 or http://your_asr_host:9000)@@ -40,6 +41,11 @@ ADMIN_USERNAME=adminADMIN_PASSWORD=changeme+# --- Inquire Mode (AI search across all recordings) ---+# Set to "true" to enable semantic search and chat across all recordings+# Requires additional dependencies (sentence-transformers, faiss-cpu, numpy)+# ENABLE_INQUIRE_MODE=false+# --- Automated File Processing (Black Hole Directory) ---# Set to "true" to enable automated file processingENABLE_AUTO_PROCESSING=falsediff --git a/env.whisper.example b/env.whisper.exampleindex 6482103b..f0a46f77 100644--- a/env.whisper.example+++ b/env.whisper.example@@ -27,11 +27,31 @@ CHAT_MAX_TOKENS=5000# Options: DEBUG, INFO, WARNING, ERRORLOG_LEVEL="INFO"+# --- Large File Chunking ---+# Automatically splits large files to work with API limits+ENABLE_CHUNKING=true++# Choose chunking method based on your provider's limits:+# For size-based limits (e.g., OpenAI's 25MB limit):+CHUNK_LIMIT=20MB++# For duration-based limits (uncomment and use instead):+# CHUNK_LIMIT=1200s # 20 minutes+# CHUNK_LIMIT=20m # Alternative format++# Overlap between chunks (seconds)+CHUNK_OVERLAP_SECONDS=3+# --- Admin User (created on first run) ---ADMIN_USERNAME=adminADMIN_PASSWORD=changeme+# --- Inquire Mode (AI search across all recordings) ---+# Set to "true" to enable semantic search and chat across all recordings+# Requires additional dependencies (sentence-transformers, faiss-cpu, numpy)+# ENABLE_INQUIRE_MODE=false+# --- Automated File Processing (Black Hole Directory) ---# Set to "true" to enable automated file processingENABLE_AUTO_PROCESSING=falsediff --git a/migrate_docker.sh b/migrate_docker.shnew file mode 100644index 00000000..780f1fa2--- /dev/null+++ b/migrate_docker.sh@@ -0,0 +1,44 @@+#!/bin/bash+# Manual migration script for Docker deployments+# NOTE: The first 10 recordings are processed automatically on startup.+# This script is for processing any remaining recordings.++echo "🎯 Inquire Mode Manual Migration for Docker"+echo "============================================="++# Check if container is running+if ! docker-compose ps | grep -q "speakr.*Up"; then+ echo "❌ Speakr container is not running. Please start it first with:"+ echo " docker-compose up -d"+ exit 1+fi++echo "ℹ️ Note: The first 10 recordings are processed automatically on startup."+echo "ℹ️ This script processes any remaining recordings that need chunking."+echo ""+echo "🔍 Checking how many recordings still need processing..."++# First, do a dry run to see what would be processed+docker-compose exec app python migrate_existing_recordings.py --dry-run++echo ""+echo "⚠️ Do you want to proceed with processing these recordings?"+echo "⚠️ This will create embeddings and may take several minutes."+read -p "Continue? (y/N): " -n 1 -r+echo++if [[ $REPLY =~ ^[Yy]$ ]]; then+ echo "🚀 Starting migration..."+ docker-compose exec app python migrate_existing_recordings.py --process --batch-size 5++ if [ $? -eq 0 ]; then+ echo "✅ Migration completed successfully!"+ echo "🎉 Your existing recordings are now ready for Inquire Mode!"+ else+ echo "❌ Migration failed. Check the logs above for details."+ exit 1+ fi+else+ echo "❌ Migration cancelled."+ exit 0+fi\ No newline at end of filediff --git a/migrate_existing_recordings.py b/migrate_existing_recordings.pynew file mode 100644index 00000000..83bb311a--- /dev/null+++ b/migrate_existing_recordings.py@@ -0,0 +1,142 @@+#!/usr/bin/env python3+"""+Migration script to process existing recordings for Inquire Mode.+This script will chunk and vectorize all existing recordings that haven't been processed yet.+"""+import os+import sys+from app import app, db, Recording, TranscriptChunk, process_recording_chunks++def count_recordings_needing_processing():+ """Count how many recordings need chunk processing."""+ with app.app_context():+ # Get all completed recordings+ completed_recordings = Recording.query.filter_by(status='COMPLETED').all()++ # Check which ones don't have chunks+ recordings_needing_processing = []+ for recording in completed_recordings:+ if recording.transcription: # Has transcription+ chunk_count = TranscriptChunk.query.filter_by(recording_id=recording.id).count()+ if chunk_count == 0: # No chunks yet+ recordings_needing_processing.append(recording)++ return recordings_needing_processing++def migrate_existing_recordings(batch_size=10, dry_run=False):+ """+ Process existing recordings in batches to create chunks and embeddings.++ Args:+ batch_size (int): Number of recordings to process at once+ dry_run (bool): If True, just show what would be processed+ """+ with app.app_context():+ recordings_to_process = count_recordings_needing_processing()++ print(f"🔍 Found {len(recordings_to_process)} recordings that need chunk processing")++ if len(recordings_to_process) == 0:+ print("✅ All recordings are already processed!")+ return True++ if dry_run:+ print("\n📋 Recordings that would be processed:")+ for i, recording in enumerate(recordings_to_process, 1):+ print(f" {i}. {recording.title} (ID: {recording.id}) - {len(recording.transcription)} chars")+ print(f"\nThis is a dry run. Use --process to actually run the migration.")+ return True++ print(f"🚀 Processing {len(recordings_to_process)} recordings in batches of {batch_size}")++ processed = 0+ errors = 0++ for i in range(0, len(recordings_to_process), batch_size):+ batch = recordings_to_process[i:i + batch_size]+ print(f"\n📦 Processing batch {i//batch_size + 1} ({len(batch)} recordings)...")++ for recording in batch:+ try:+ print(f" ⏳ Processing: {recording.title} (ID: {recording.id})")++ success = process_recording_chunks(recording.id)+ if success:+ processed += 1+ # Get chunk count to report+ chunk_count = TranscriptChunk.query.filter_by(recording_id=recording.id).count()+ print(f" ✅ Created {chunk_count} chunks")+ else:+ errors += 1+ print(f" ❌ Failed to process recording {recording.id}")++ except Exception as e:+ errors += 1+ print(f" ❌ Error processing recording {recording.id}: {e}")++ # Commit batch+ try:+ db.session.commit()+ print(f" 💾 Batch committed successfully")+ except Exception as e:+ db.session.rollback()+ print(f" ❌ Error committing batch: {e}")+ errors += len(batch)++ print(f"\n📊 Migration Summary:")+ print(f" ✅ Successfully processed: {processed}")+ print(f" ❌ Errors: {errors}")+ print(f" 📈 Success rate: {(processed/(processed+errors)*100):.1f}%" if (processed+errors) > 0 else "N/A")++ return errors == 0++def main():+ """Main function to handle command line arguments."""+ import argparse++ parser = argparse.ArgumentParser(description='Migrate existing recordings for Inquire Mode')+ parser.add_argument('--dry-run', action='store_true',+ help='Show what would be processed without actually processing')+ parser.add_argument('--process', action='store_true',+ help='Actually process the recordings')+ parser.add_argument('--batch-size', type=int, default=10,+ help='Number of recordings to process in each batch (default: 10)')++ args = parser.parse_args()++ if not args.dry_run and not args.process:+ print("❌ Please specify either --dry-run or --process")+ print("Use --help for more information")+ return False++ print("🎯 Inquire Mode Migration Tool")+ print("=" * 40)++ try:+ if args.dry_run:+ success = migrate_existing_recordings(args.batch_size, dry_run=True)+ else:+ print("⚠️ This will process all existing recordings and create embeddings.")+ print("⚠️ This may take a while and use significant CPU/memory.")++ confirm = input("Continue? (y/N): ")+ if confirm.lower() != 'y':+ print("❌ Migration cancelled by user")+ return False++ success = migrate_existing_recordings(args.batch_size, dry_run=False)++ return success++ except KeyboardInterrupt:+ print("\n❌ Migration cancelled by user")+ return False+ except Exception as e:+ print(f"❌ Migration failed: {e}")+ import traceback+ traceback.print_exc()+ return False++if __name__ == "__main__":+ success = main()+ sys.exit(0 if success else 1)\ No newline at end of filediff --git a/requirements.txt b/requirements.txtindex daa59aba..c2180d0b 100644--- a/requirements.txt+++ b/requirements.txt@@ -14,3 +14,7 @@ pytz==2024.1Babel==2.12.1bleach==6.1.0python-docx==1.1.0+numpy==1.24.3+sentence-transformers==2.7.0+scikit-learn==1.3.0+huggingface-hub>=0.19.0diff --git a/static/css/styles.css b/static/css/styles.cssindex 170e9b29..3d3c167f 100644--- a/static/css/styles.css+++ b/static/css/styles.css@@ -208,6 +208,8 @@ body.unloaded {--border-focus: #10b981; /* keep focus visible */--ring-focus: #384838; /* visible ring */--bg-audio-player: var(--bg-tertiary);+ --scrollbar-thumb: #485548; /* emerald tinted scrollbar */+ --scrollbar-thumb-hover: #556655; /* brighter emerald on hover */}.dark.theme-dark-purple {@@ -226,6 +228,8 @@ body.unloaded {--border-focus: #8b5cf6; /* keep focus visible */--ring-focus: #423c48; /* visible ring */--bg-audio-player: var(--bg-tertiary);+ --scrollbar-thumb: #555058; /* purple tinted scrollbar */+ --scrollbar-thumb-hover: #666068; /* brighter purple on hover */}.dark.theme-dark-rose {@@ -244,6 +248,8 @@ body.unloaded {--border-focus: #f43f5e; /* keep focus visible */--ring-focus: #483c40; /* visible ring */--bg-audio-player: var(--bg-tertiary);+ --scrollbar-thumb: #554850; /* rose tinted scrollbar */+ --scrollbar-thumb-hover: #665860; /* brighter rose on hover */}.dark.theme-dark-amber {@@ -262,6 +268,8 @@ body.unloaded {--border-focus: #f59e0b; /* keep focus visible */--ring-focus: #484038; /* visible ring */--bg-audio-player: var(--bg-tertiary);+ --scrollbar-thumb: #585548; /* amber tinted scrollbar */+ --scrollbar-thumb-hover: #686658; /* brighter amber on hover */}.dark.theme-dark-teal {@@ -280,6 +288,8 @@ body.unloaded {--border-focus: #14b8a6; /* keep focus visible */--ring-focus: #384848; /* visible ring */--bg-audio-player: var(--bg-tertiary);+ --scrollbar-thumb: #485555; /* teal tinted scrollbar */+ --scrollbar-thumb-hover: #586666; /* brighter teal on hover */}/* Modern UI styles */@@ -287,18 +297,27 @@ body.unloaded {.drag-area { transition: background-color 0.3s ease, border-color 0.3s ease; }/* Global Scrollbar Styles */::-webkit-scrollbar {- width: 8px;- height: 8px;+ width: 10px;+ height: 10px;}::-webkit-scrollbar-track {- background: var(--scrollbar-track);+ background: transparent;+ border-radius: 10px;}::-webkit-scrollbar-thumb {background: var(--scrollbar-thumb);border-radius: 10px;+ border: 2px solid transparent;+ background-clip: padding-box;}::-webkit-scrollbar-thumb:hover {background: var(--scrollbar-thumb-hover);+ border: 2px solid transparent;+ background-clip: padding-box;+}+/* Fix scrollbar corner for rounded containers */+::-webkit-scrollbar-corner {+ background: transparent;}html { /* Apply base colors to html for smoother transitions */background-color: var(--bg-primary);@@ -414,11 +433,14 @@ main {min-height: 0; /* Critical for flex shrinking */max-height: 100%; /* Prevent expansion beyond parent */overflow-y: auto; /* Enable scrolling */+ overflow-x: hidden; /* Prevent horizontal overflow *//* Keep existing styling */background-color: var(--bg-tertiary);padding: 1rem;border-radius: 0.75rem;border: 1px solid var(--border-primary);+ /* Fix scrollbar clipping rounded corners */+ scrollbar-gutter: stable;color: var(--text-secondary);box-shadow: 0 1px 2px rgba(0,0,0,0.03);}@@ -1733,8 +1755,11 @@ body {border-radius: 0.75rem;padding: 1rem;overflow-y: auto;+ overflow-x: hidden;font-size: 0.875rem;line-height: 1.5;+ /* Fix scrollbar clipping rounded corners */+ scrollbar-gutter: stable;color: var(--text-secondary);min-height: 0;}diff --git a/static/js/app.js b/static/js/app.jsindex 60b671eb..47f118e4 100644--- a/static/js/app.js+++ b/static/js/app.js@@ -1810,12 +1810,21 @@ document.addEventListener('DOMContentLoaded', () => {max_speakers: asrMaxSpeakers.value};- // Check if it's an audio file or has AMR extension+ // Check if it's an audio file or video container with audioconst isAudioFile = fileObject && (fileObject.type.startsWith('audio/') ||+ fileObject.type === 'video/mp4' ||+ fileObject.type === 'video/quicktime' ||+ fileObject.type === 'video/x-msvideo' ||+ fileObject.type === 'video/webm' ||fileObject.name.toLowerCase().endsWith('.amr') ||fileObject.name.toLowerCase().endsWith('.3gp') ||- fileObject.name.toLowerCase().endsWith('.3gpp')+ fileObject.name.toLowerCase().endsWith('.3gpp') ||+ fileObject.name.toLowerCase().endsWith('.mp4') ||+ fileObject.name.toLowerCase().endsWith('.mov') ||+ fileObject.name.toLowerCase().endsWith('.avi') ||+ fileObject.name.toLowerCase().endsWith('.mkv') ||+ fileObject.name.toLowerCase().endsWith('.webm'));if (isAudioFile) {@@ -1838,7 +1847,7 @@ document.addEventListener('DOMContentLoaded', () => {});filesAdded++;} else if (fileObject) {- setGlobalError(`Invalid file type "${fileObject.name}". Only audio files (including AMR) are accepted. File skipped.`);+ setGlobalError(`Invalid file type "${fileObject.name}". Only audio files and video containers with audio (MP3, WAV, MP4, MOV, AVI, etc.) are accepted. File skipped.`);}}if(filesAdded > 0) {@@ -3612,6 +3621,35 @@ document.addEventListener('DOMContentLoaded', () => {editingMeetingDate.value = false;editingSummary.value = false;editingNotes.value = false;++ // Fix WebM duration issue by forcing metadata load+ if (newVal?.id) {+ nextTick(() => {+ const audioElements = document.querySelectorAll('audio');+ audioElements.forEach(audio => {+ if (audio.src && audio.src.includes(`/audio/${newVal.id}`)) {+ // For WebM files, we need to seek to end to get duration+ const fixDuration = () => {+ if (!isFinite(audio.duration) || audio.duration === 0) {+ audio.currentTime = 1e101; // Seek to "infinity" to load duration+ audio.addEventListener('timeupdate', function resetTime() {+ audio.currentTime = 0;+ audio.removeEventListener('timeupdate', resetTime);+ }, { once: true });+ }+ };++ // Try to fix duration when metadata loads+ audio.addEventListener('loadedmetadata', fixDuration, { once: true });++ // Also try immediately in case metadata is already loaded+ if (audio.readyState >= 1) {+ fixDuration();+ }+ }+ });+ });+ }}});diff --git a/templates/account.html b/templates/account.htmlindex ad9621d7..ce3ce6ff 100644--- a/templates/account.html+++ b/templates/account.html@@ -46,7 +46,7 @@<header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]"><h1 class="text-3xl font-bold text-[var(--text-primary)]"><a href="{{ url_for('index') }}" class="flex items-center">- <img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">+ <img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">Speakr</a></h1>@@ -93,6 +93,9 @@<a href="#" id="tab-tags" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]">Tag Management</a>+ <a href="#" id="tab-about" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]">+ About+ </a></nav></div>@@ -292,11 +295,232 @@</div></div></div>++ <div id="content-about" class="hidden">+ <div class="space-y-8">+ <!-- Header Section -->+ <div class="text-center">+ <div class="flex items-center justify-center mb-4">+ <img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-16 w-16 mr-4">+ <div>+ <h2 class="text-3xl font-bold text-[var(--text-primary)]">Speakr</h2>+ <p class="text-[var(--text-secondary)]">AI-Powered Audio Transcription & Note-Taking</p>+ </div>+ </div>+ <div class="inline-flex items-center px-3 py-1 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-full text-sm font-medium">+ <i class="fas fa-tag mr-2"></i>+ Version <span id="system-version" class="ml-1 font-mono">Loading...</span>+ </div>+ </div>++ <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">+ <!-- System Information -->+ <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center mb-4">+ <div class="p-2 bg-[var(--bg-accent)] rounded-lg mr-3">+ <i class="fas fa-cogs text-[var(--text-accent)] text-lg"></i>+ </div>+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">System Configuration</h3>+ </div>++ <div class="space-y-4">+ <div class="border-l-4 border-[var(--border-accent)] pl-4">+ <h4 class="font-medium text-[var(--text-primary)] mb-2">Large Language Model</h4>+ <div class="space-y-1 text-sm">+ <p class="text-[var(--text-secondary)]">+ <span class="font-medium">Model:</span>+ <span id="llm-model" class="font-mono text-[var(--text-primary)] bg-[var(--bg-tertiary)] px-2 py-1 rounded ml-1">Loading...</span>+ </p>+ <p class="text-[var(--text-secondary)]">+ <span class="font-medium">Endpoint:</span>+ <span id="llm-endpoint" class="font-mono text-xs text-[var(--text-muted)] break-all ml-1">Loading...</span>+ </p>+ </div>+ </div>++ <div class="border-l-4 border-green-500 pl-4">+ <h4 class="font-medium text-[var(--text-primary)] mb-2">Speech Recognition</h4>+ <div class="space-y-1 text-sm">+ <p class="text-[var(--text-secondary)]">+ <span class="font-medium">Whisper API:</span>+ <span id="whisper-endpoint" class="font-mono text-xs text-[var(--text-muted)] ml-1">Loading...</span>+ </p>+ <p class="text-[var(--text-secondary)]">+ <span class="font-medium">ASR Enabled:</span>+ <span id="asr-status" class="ml-1">Loading...</span>+ </p>+ <div id="asr-endpoint-row" style="display: none;">+ <p class="text-[var(--text-secondary)]">+ <span class="font-medium">ASR Endpoint:</span>+ <span id="asr-endpoint" class="font-mono text-xs text-[var(--text-muted)] ml-1">-</span>+ </p>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- Project Information -->+ <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center mb-4">+ <div class="p-2 bg-gray-800 rounded-lg mr-3">+ <i class="fab fa-github text-white text-lg"></i>+ </div>+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Project Links</h3>+ </div>++ <div class="space-y-3">+ <a href="https://github.com/murtaza-nasir/speakr" target="_blank" rel="noopener noreferrer"+ class="flex items-center p-3 bg-gray-800 hover:bg-gray-700 text-white rounded-lg transition-all duration-200 group transform hover:scale-[1.02]">+ <i class="fab fa-github text-xl mr-3"></i>+ <div class="flex-1">+ <div class="font-medium">GitHub Repository</div>+ <div class="text-sm text-gray-300">Source code, issues, and releases</div>+ </div>+ <i class="fas fa-external-link-alt text-sm opacity-70 group-hover:opacity-100"></i>+ </a>++ <a href="https://hub.docker.com/r/learnedmachine/speakr" target="_blank" rel="noopener noreferrer"+ class="flex items-center p-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-all duration-200 group transform hover:scale-[1.02]">+ <i class="fab fa-docker text-xl mr-3"></i>+ <div class="flex-1">+ <div class="font-medium">Docker Hub</div>+ <div class="text-sm text-blue-100">Official Docker images</div>+ </div>+ <i class="fas fa-external-link-alt text-sm opacity-70 group-hover:opacity-100"></i>+ </a>++ <a href="https://github.com/murtaza-nasir/speakr/wiki" target="_blank" rel="noopener noreferrer"+ class="flex items-center p-3 bg-green-600 hover:bg-green-500 text-white rounded-lg transition-all duration-200 group transform hover:scale-[1.02]">+ <i class="fas fa-book text-xl mr-3"></i>+ <div class="flex-1">+ <div class="font-medium">Documentation</div>+ <div class="text-sm text-green-100">Setup guides and user manual</div>+ </div>+ <i class="fas fa-external-link-alt text-sm opacity-70 group-hover:opacity-100"></i>+ </a>+ </div>++ <div class="mt-6 p-3 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">+ <p class="text-sm text-[var(--text-secondary)] leading-relaxed">+ <i class="fas fa-info-circle text-[var(--text-accent)] mr-2"></i>+ Transform your audio recordings into organized, searchable notes with AI-powered transcription, summarization, and interactive chat features.+ </p>+ </div>+ </div>+ </div>++ <!-- Key Features -->+ <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center mb-6">+ <div class="p-2 bg-purple-600 rounded-lg mr-3">+ <i class="fas fa-star text-white text-lg"></i>+ </div>+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Key Features</h3>+ </div>++ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">+ <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">+ <div class="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg mr-3 mt-1">+ <i class="fas fa-microphone text-blue-600 dark:text-blue-400"></i>+ </div>+ <div>+ <h4 class="font-medium text-[var(--text-primary)] mb-1">Audio Transcription</h4>+ <p class="text-sm text-[var(--text-secondary)]">Whisper API and custom ASR support with high accuracy</p>+ </div>+ </div>++ <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">+ <div class="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg mr-3 mt-1">+ <i class="fas fa-robot text-purple-600 dark:text-purple-400"></i>+ </div>+ <div>+ <h4 class="font-medium text-[var(--text-primary)] mb-1">AI Summarization</h4>+ <p class="text-sm text-[var(--text-secondary)]">OpenRouter and Ollama integration with custom prompts</p>+ </div>+ </div>++ <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">+ <div class="p-2 bg-green-100 dark:bg-green-900 rounded-lg mr-3 mt-1">+ <i class="fas fa-users text-green-600 dark:text-green-400"></i>+ </div>+ <div>+ <h4 class="font-medium text-[var(--text-primary)] mb-1">Speaker Diarization</h4>+ <p class="text-sm text-[var(--text-secondary)]">Identify and label different speakers automatically</p>+ </div>+ </div>++ <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">+ <div class="p-2 bg-orange-100 dark:bg-orange-900 rounded-lg mr-3 mt-1">+ <i class="fas fa-comments text-orange-600 dark:text-orange-400"></i>+ </div>+ <div>+ <h4 class="font-medium text-[var(--text-primary)] mb-1">Interactive Chat</h4>+ <p class="text-sm text-[var(--text-secondary)]">Chat with your transcriptions using AI</p>+ </div>+ </div>++ <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">+ <div class="p-2 bg-indigo-100 dark:bg-indigo-900 rounded-lg mr-3 mt-1">+ <i class="fas fa-search text-indigo-600 dark:text-indigo-400"></i>+ </div>+ <div>+ <h4 class="font-medium text-[var(--text-primary)] mb-1">Inquire Mode</h4>+ <p class="text-sm text-[var(--text-secondary)]">Semantic search across all your recordings</p>+ </div>+ </div>++ <div class="flex items-start p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-accent)] transition-colors">+ <div class="p-2 bg-teal-100 dark:bg-teal-900 rounded-lg mr-3 mt-1">+ <i class="fas fa-share-alt text-teal-600 dark:text-teal-400"></i>+ </div>+ <div>+ <h4 class="font-medium text-[var(--text-primary)] mb-1">Sharing & Export</h4>+ <p class="text-sm text-[var(--text-secondary)]">Share recordings and export to various formats</p>+ </div>+ </div>+ </div>+ </div>++ <!-- Technology Stack -->+ <div class="bg-[var(--bg-secondary)] rounded-xl p-6 border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center mb-4">+ <div class="p-2 bg-red-500 rounded-lg mr-3">+ <i class="fas fa-code text-white text-lg"></i>+ </div>+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Technology Stack</h3>+ </div>++ <div class="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">+ <i class="fab fa-python text-3xl text-blue-500 mb-2"></i>+ <p class="text-sm font-medium text-[var(--text-primary)]">Python Flask</p>+ <p class="text-xs text-[var(--text-muted)]">Backend</p>+ </div>+ <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">+ <i class="fab fa-vuejs text-3xl text-green-500 mb-2"></i>+ <p class="text-sm font-medium text-[var(--text-primary)]">Vue.js</p>+ <p class="text-xs text-[var(--text-muted)]">Frontend</p>+ </div>+ <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">+ <i class="fas fa-database text-3xl text-purple-500 mb-2"></i>+ <p class="text-sm font-medium text-[var(--text-primary)]">SQLite</p>+ <p class="text-xs text-[var(--text-muted)]">Database</p>+ </div>+ <div class="text-center p-3 bg-[var(--bg-tertiary)] rounded-lg">+ <i class="fab fa-docker text-3xl text-blue-600 mb-2"></i>+ <p class="text-sm font-medium text-[var(--text-primary)]">Docker</p>+ <p class="text-xs text-[var(--text-muted)]">Deployment</p>+ </div>+ </div>+ </div>+ </div>+ </div></div></main><footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">- Speakr © {{ now.year }}+ <span id="footer-text">Speakr © {{ now.year }}</span></footer></div>@@ -472,15 +696,19 @@</div></div>+<script>document.addEventListener('DOMContentLoaded', function() {const tabAccount = document.getElementById('tab-account');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 contentShares = document.getElementById('content-shares');const contentTags = document.getElementById('content-tags');+ const contentAbout = document.getElementById('content-about');const sharesContainer = document.getElementById('shares-container');+function showAccountTab() {tabAccount.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]');@@ -489,9 +717,12 @@tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');contentAccount.classList.remove('hidden');contentShares.classList.add('hidden');contentTags.classList.add('hidden');+ contentAbout.classList.add('hidden');}function showSharesTab() {@@ -501,9 +732,12 @@tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');contentShares.classList.remove('hidden');contentAccount.classList.add('hidden');contentTags.classList.add('hidden');+ contentAbout.classList.add('hidden');loadShares();}@@ -514,12 +748,31 @@tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabAbout.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabAbout.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');contentTags.classList.remove('hidden');contentAccount.classList.add('hidden');contentShares.classList.add('hidden');+ contentAbout.classList.add('hidden');loadTags();}+ function showAboutTab() {+ tabAbout.classList.add('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabAbout.classList.remove('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabAccount.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabAccount.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabShares.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabShares.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ tabTags.classList.add('border-transparent', 'text-[var(--text-muted)]', 'hover:text-[var(--text-secondary)]', 'hover:border-[var(--border-secondary)]');+ tabTags.classList.remove('border-[var(--border-accent)]', 'text-[var(--text-accent)]');+ contentAbout.classList.remove('hidden');+ contentAccount.classList.add('hidden');+ contentShares.classList.add('hidden');+ contentTags.classList.add('hidden');+ loadSystemInfo();+ }+tabAccount.addEventListener('click', (e) => {e.preventDefault();showAccountTab();@@ -535,6 +788,44 @@showTagsTab();});+ tabAbout.addEventListener('click', (e) => {+ e.preventDefault();+ showAboutTab();+ });++ async function loadSystemInfo() {+ try {+ const response = await fetch('/api/system/info');+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);+ }++ const data = await response.json();++ // Update version in multiple places+ document.getElementById('system-version').textContent = data.version;++ // Update LLM info+ document.getElementById('llm-endpoint').textContent = data.llm_endpoint;+ document.getElementById('llm-model').textContent = data.llm_model;++ // Update Whisper/ASR info+ document.getElementById('whisper-endpoint').textContent = data.whisper_endpoint;+ document.getElementById('asr-status').textContent = data.asr_enabled ? 'Yes' : 'No';++ if (data.asr_enabled && data.asr_endpoint) {+ document.getElementById('asr-endpoint').textContent = data.asr_endpoint;+ document.getElementById('asr-endpoint-row').style.display = 'block';+ }+ } catch (error) {+ document.getElementById('system-version').textContent = 'Failed to load';+ document.getElementById('llm-endpoint').textContent = 'Failed to load';+ document.getElementById('llm-model').textContent = 'Failed to load';+ document.getElementById('whisper-endpoint').textContent = 'Failed to load';+ document.getElementById('asr-status').textContent = 'Failed to load';+ }+ }+async function loadShares() {sharesContainer.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin text-2xl"></i></div>';try {@@ -643,6 +934,25 @@div.textContent = text;return div.innerHTML;}++ // Update footer with version+ async function updateFooter() {+ try {+ const response = await fetch('/api/system/info');+ if (response.ok) {+ const data = await response.json();+ const footerText = document.getElementById('footer-text');+ if (footerText && data.version) {+ footerText.textContent = `Speakr ${data.version} © {{ now.year }}`;+ }+ }+ } catch (error) {+ console.log('Could not fetch version for footer');+ }+ }++ // Update footer on page load+ updateFooter();});// Dark mode toggle functionality@@ -1304,7 +1614,7 @@showToast(`Failed to save tag: ${error.message}`, 'error');}});-+</script></body></html>diff --git a/templates/admin.html b/templates/admin.htmlindex d10898ae..6221c278 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -47,7 +47,7 @@<header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]"><h1 class="text-3xl font-bold text-[var(--text-primary)]"><a href="{{ url_for('index') }}" class="flex items-center">- <img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">+ <img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">Speakr</a></h1>@@ -111,6 +111,12 @@class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"><i class="fas fa-cogs mr-2"></i> System Settings</button>+ <button @click="activeTab = 'vectorstore'"+ :class="activeTab === 'vectorstore' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"+ class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"+ v-if="inquireModeEnabled">+ <i class="fas fa-database mr-2"></i> Vector Store+ </button></nav></div>@@ -348,6 +354,166 @@</div></div></div>++ <!-- Vector Store Tab -->+ <div v-show="activeTab === 'vectorstore'" v-if="inquireModeEnabled">+ <div class="flex justify-between items-center mb-6">+ <h3 class="text-lg font-medium text-[var(--text-secondary)]">Vector Store Management</h3>+ <button @click="loadInquireStatus" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">+ <i class="fas fa-sync-alt mr-2"></i> Refresh Status+ </button>+ </div>++ <!-- Vector Store Info -->+ <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)] mb-6">+ <h4 class="text-md font-semibold text-[var(--text-primary)] mb-4">+ <i class="fas fa-info-circle mr-2"></i>About Inquire Mode+ </h4>+ <p class="text-sm text-[var(--text-secondary)] mb-3">+ Inquire Mode allows users to search across multiple transcriptions using natural language questions.+ It works by breaking transcriptions into chunks and creating searchable embeddings using AI models.+ </p>+ <div class="grid grid-cols-2 gap-4 text-sm">+ <div>+ <span class="text-[var(--text-muted)]">Chunk Size:</span>+ <span class="ml-2 text-[var(--text-primary)]">500 characters</span>+ </div>+ <div>+ <span class="text-[var(--text-muted)]">Overlap:</span>+ <span class="ml-2 text-[var(--text-primary)]">50 characters</span>+ </div>+ <div>+ <span class="text-[var(--text-muted)]">Embedding Model:</span>+ <span class="ml-2 text-[var(--text-primary)]">all-MiniLM-L6-v2</span>+ </div>+ <div>+ <span class="text-[var(--text-muted)]">Vector Dimensions:</span>+ <span class="ml-2 text-[var(--text-primary)]">384</span>+ </div>+ </div>+ </div>++ <!-- Statistics Grid -->+ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center justify-between">+ <div>+ <p class="text-sm text-[var(--text-muted)]">Total Recordings</p>+ <p class="text-2xl font-semibold text-[var(--text-primary)]">${ inquireStatus.total_completed_recordings || 0 }</p>+ </div>+ <i class="fas fa-file-audio text-3xl text-[var(--text-accent)] opacity-50"></i>+ </div>+ </div>++ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center justify-between">+ <div>+ <p class="text-sm text-[var(--text-muted)]">Processed for Inquire</p>+ <p class="text-2xl font-semibold text-[var(--text-success-strong)]">${ inquireStatus.processed_for_inquire || 0 }</p>+ </div>+ <i class="fas fa-check-circle text-3xl text-[var(--text-success-strong)] opacity-50"></i>+ </div>+ </div>++ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center justify-between">+ <div>+ <p class="text-sm text-[var(--text-muted)]">Need Processing</p>+ <p class="text-2xl font-semibold" :class="inquireStatus.need_processing > 0 ? 'text-[var(--text-warning-strong)]' : 'text-[var(--text-primary)]'">+ ${ inquireStatus.need_processing || 0 }+ </p>+ </div>+ <i class="fas fa-clock text-3xl opacity-50" :class="inquireStatus.need_processing > 0 ? 'text-[var(--text-warning-strong)]' : 'text-[var(--text-muted)]'"></i>+ </div>+ </div>++ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center justify-between">+ <div>+ <p class="text-sm text-[var(--text-muted)]">Total Chunks</p>+ <p class="text-2xl font-semibold text-[var(--text-primary)]">${ inquireStatus.total_chunks || 0 }</p>+ </div>+ <i class="fas fa-th text-3xl text-[var(--text-accent)] opacity-50"></i>+ </div>+ </div>++ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center justify-between">+ <div>+ <p class="text-sm text-[var(--text-muted)]">Embeddings Status</p>+ <p class="text-lg font-semibold" :class="inquireStatus.embeddings_available ? 'text-[var(--text-success-strong)]' : 'text-[var(--text-warning-strong)]'">+ <i :class="inquireStatus.embeddings_available ? 'fas fa-check-circle' : 'fas fa-exclamation-triangle'" class="mr-2"></i>+ ${ inquireStatus.embeddings_available ? 'Available' : 'Text Search Only' }+ </p>+ </div>+ <i class="fas fa-brain text-3xl opacity-50" :class="inquireStatus.embeddings_available ? 'text-[var(--text-success-strong)]' : 'text-[var(--text-warning-strong)]'"></i>+ </div>+ </div>++ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center justify-between">+ <div>+ <p class="text-sm text-[var(--text-muted)]">Processing Progress</p>+ <div class="mt-2">+ <div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2.5">+ <div class="bg-[var(--text-accent)] h-2.5 rounded-full" :style="{width: getProcessingProgress() + '%'}"></div>+ </div>+ <p class="text-xs text-[var(--text-muted)] mt-1">${ getProcessingProgress() }% complete</p>+ </div>+ </div>+ <i class="fas fa-tasks text-3xl text-[var(--text-accent)] opacity-50"></i>+ </div>+ </div>+ </div>++ <!-- Processing Actions -->+ <div class="bg-[var(--bg-tertiary)] p-6 rounded-lg border border-[var(--border-primary)]">+ <h4 class="text-md font-semibold text-[var(--text-primary)] mb-4">+ <i class="fas fa-cog mr-2"></i>Processing Actions+ </h4>++ <div v-if="inquireStatus.need_processing > 0" class="mb-4">+ <p class="text-sm text-[var(--text-secondary)] mb-4">+ There are <span class="font-semibold text-[var(--text-warning-strong)]">${ inquireStatus.need_processing }</span> recordings that need to be processed for Inquire Mode.+ </p>++ <div class="flex flex-wrap gap-3">+ <button @click="processAllRecordings"+ :disabled="isProcessingRecordings"+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed">+ <i :class="isProcessingRecordings ? 'fas fa-spinner fa-spin' : 'fas fa-play'" class="mr-2"></i>+ ${ isProcessingRecordings ? 'Processing...' : 'Process All Recordings' }+ </button>++ <button @click="processBatchRecordings(10)"+ :disabled="isProcessingRecordings"+ class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded-lg shadow hover:bg-[var(--bg-tertiary)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed">+ <i class="fas fa-forward mr-2"></i>+ Process Next 10+ </button>+ </div>++ <div v-if="processingResult" class="mt-4 p-4 rounded-lg"+ :class="processingResult.success ? 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]' : 'bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]'">+ <p class="font-medium">${ processingResult.message }</p>+ <div v-if="processingResult.failed && processingResult.failed.length > 0" class="mt-2">+ <p class="text-sm font-medium">Failed recordings:</p>+ <ul class="text-xs mt-1 space-y-1">+ <li v-for="fail in processingResult.failed" :key="fail.id">+ ID ${ fail.id }: ${ fail.title } - ${ fail.reason }+ </li>+ </ul>+ </div>+ </div>+ </div>++ <div v-else class="text-center py-4">+ <i class="fas fa-check-circle text-4xl text-[var(--text-success-strong)] mb-3"></i>+ <p class="text-[var(--text-success-strong)] font-medium">All recordings are processed!</p>+ <p class="text-sm text-[var(--text-muted)] mt-1">The vector store is up to date.</p>+ </div>+ </div>+ </div></div></main>@@ -479,6 +645,19 @@const editingUser = ref(null);const userToDelete = ref(null);+ // Inquire Mode state+ const inquireModeEnabled = ref({{ 'true' if inquire_mode_enabled else 'false' }});+ const inquireStatus = ref({+ total_completed_recordings: 0,+ recordings_with_transcriptions: 0,+ processed_for_inquire: 0,+ need_processing: 0,+ total_chunks: 0,+ embeddings_available: false+ });+ const isProcessingRecordings = ref(false);+ const processingResult = ref(null);+// Computed propertiesconst filteredUsers = computed(() => {if (!userSearchQuery.value) return users.value;@@ -798,11 +977,101 @@}};+ // Inquire Mode methods+ const loadInquireStatus = async () => {+ try {+ const response = await fetch('/admin/inquire/status');+ if (!response.ok) throw new Error('Failed to load inquire status');++ const data = await response.json();+ inquireStatus.value = data;+ } catch (error) {+ console.error('Error loading inquire status:', error);+ }+ };++ const processAllRecordings = async () => {+ if (isProcessingRecordings.value) return;++ isProcessingRecordings.value = true;+ processingResult.value = null;++ try {+ const response = await fetch('/admin/inquire/process-recordings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')+ },+ body: JSON.stringify({})+ });++ if (!response.ok) throw new Error('Failed to process recordings');++ const data = await response.json();+ processingResult.value = data;++ // Reload status after processing+ await loadInquireStatus();+ } catch (error) {+ console.error('Error processing recordings:', error);+ processingResult.value = {+ success: false,+ message: 'Failed to process recordings. Please try again.'+ };+ } finally {+ isProcessingRecordings.value = false;+ }+ };++ const processBatchRecordings = async (batchSize) => {+ if (isProcessingRecordings.value) return;++ isProcessingRecordings.value = true;+ processingResult.value = null;++ try {+ const response = await fetch('/admin/inquire/process-recordings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')+ },+ body: JSON.stringify({ max_recordings: batchSize })+ });++ if (!response.ok) throw new Error('Failed to process recordings');++ const data = await response.json();+ processingResult.value = data;++ // Reload status after processing+ await loadInquireStatus();+ } catch (error) {+ console.error('Error processing recordings:', error);+ processingResult.value = {+ success: false,+ message: 'Failed to process recordings. Please try again.'+ };+ } finally {+ isProcessingRecordings.value = false;+ }+ };++ const getProcessingProgress = () => {+ const total = (inquireStatus.value.processed_for_inquire || 0) + (inquireStatus.value.need_processing || 0);+ if (total === 0) return 100;+ return Math.round((inquireStatus.value.processed_for_inquire / total) * 100);+ };+// Lifecycle hooksonMounted(() => {loadUsers();loadStats();initializeDarkMode();+ if (inquireModeEnabled.value) {+ loadInquireStatus();+ }});// Watch for tab changes to reload data@@ -836,8 +1105,15 @@editingUser,userToDelete,+ // Inquire Mode state+ inquireModeEnabled,+ inquireStatus,+ isProcessingRecordings,+ processingResult,+// ComputedfilteredUsers,+ getProcessingProgress,// MethodsloadUsers,@@ -853,7 +1129,12 @@deleteUser,toggleAdminStatus,formatFileSize,- toggleDarkMode+ toggleDarkMode,++ // Inquire Mode methods+ loadInquireStatus,+ processAllRecordings,+ processBatchRecordings};},delimiters: ['${', '}'] // Use different delimiters to avoid conflict with Flask's Jinja2diff --git a/templates/index.html b/templates/index.htmlindex ce6b5eae..07d6e2d1 100644--- a/templates/index.html+++ b/templates/index.html@@ -66,9 +66,18 @@<!-- Right side: User menu and controls --><div class="flex items-center gap-3">+ <!-- 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">+ <i class="fas fa-search"></i>+ <span class="hidden sm:inline">Inquire</span>+ </a>+ {% endif %}+<!-- New Recording Button --><button @click="switchToUploadView"- 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 flex items-center gap-2">+ 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></button>@@ -130,10 +139,18 @@<div class="p-4 border-b border-[var(--border-primary)] flex-shrink-0"><div class="flex items-center justify-between mb-4"><h2 class="text-lg font-semibold">Recordings</h2>- <button @click="switchToUploadView"- 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">- <i class="fas fa-plus mr-1"></i>New- </button>+ <div class="flex gap-2">+ {% if inquire_mode_enabled %}+ <a href="/inquire"+ class="px-2 py-1.5 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:opacity-80 transition-opacity text-sm">+ <i class="fas fa-search"></i>+ </a>+ {% endif %}+ <button @click="switchToUploadView"+ 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">+ <i class="fas fa-plus mr-1"></i>New+ </button>+ </div></div><!-- Search and Sort Controls -->@@ -301,9 +318,9 @@:class="['border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all duration-300', dragover ? 'border-[var(--border-accent)] bg-[var(--bg-accent)]' : 'border-[var(--border-secondary)] hover:border-[var(--border-accent)]']"><i class="fas fa-cloud-upload-alt text-3xl text-[var(--text-muted)] mb-3"></i><p class="text-[var(--text-secondary)] mb-2">Click to upload or drag and drop</p>- <p class="text-xs text-[var(--text-muted)]">Supports MP3, WAV, M4A, AMR, and more</p>+ <p class="text-xs text-[var(--text-muted)]">Supports MP3, WAV, M4A, MP4, MOV, AVI, AMR, and more</p></div>- <input ref="fileInput" type="file" @change="handleFileSelect" accept="audio/*" multiple class="hidden">+ <input ref="fileInput" type="file" @change="handleFileSelect" accept="audio/*,video/mp4,video/quicktime,video/x-msvideo,video/webm,.mp4,.mov,.avi,.mkv,.webm" multiple class="hidden"><!-- Divider --><div class="my-6 flex items-center">@@ -766,7 +783,7 @@<div class="flex-1 overflow-y-auto p-4"><!-- Transcript Panel --><div v-if="mobileTab === 'transcript'" class="h-full flex flex-col space-y-4">- <div class="flex items-center justify-end gap-2 flex-shrink-0">+ <div class="flex items-center justify-end gap-2 flex-shrink-0 pr-3"><div v-if="processedTranscription.hasDialogue" class="view-mode-toggle"><button @click="toggleTranscriptionViewMode" :class="['toggle-button', transcriptionViewMode === 'simple' ? 'active' : '']"><i class="fas fa-list"></i></button><button @click="toggleTranscriptionViewMode" :class="['toggle-button', transcriptionViewMode === 'bubble' ? 'active' : '']"><i class="fas fa-comments"></i></button>@@ -810,9 +827,10 @@</div><!-- Summary Panel --><div v-if="mobileTab === 'summary'" class="h-full flex flex-col space-y-4">- <div class="flex items-center justify-end gap-2 flex-shrink-0">- <button @click="copySummary" class="copy-btn"><i class="fas fa-copy"></i></button>- <button @click="toggleEditSummary" class="copy-btn"><i class="fas fa-edit"></i></button>+ <div class="flex items-center justify-end gap-2 flex-shrink-0 pr-3">+ <button @click="copySummary" class="copy-btn" title="Copy Summary"><i class="fas fa-copy"></i></button>+ <button @click="downloadSummary" class="copy-btn" title="Download as Word"><i class="fas fa-download"></i></button>+ <button @click="toggleEditSummary" class="copy-btn" title="Edit Summary"><i class="fas fa-edit"></i></button></div><div class="flex-grow overflow-y-auto mobile-content-box"><div v-if="editingSummary" class="h-full flex flex-col">@@ -843,9 +861,10 @@</div><!-- Notes Panel --><div v-if="mobileTab === 'notes'" class="h-full flex flex-col space-y-4">- <div class="flex items-center justify-end gap-2 flex-shrink-0">- <button @click="copyNotes" class="copy-btn"><i class="fas fa-copy"></i></button>- <button @click="toggleEditNotes" class="copy-btn"><i class="fas fa-edit"></i></button>+ <div class="flex items-center justify-end gap-2 flex-shrink-0 pr-3">+ <button @click="copyNotes" class="copy-btn" title="Copy Notes"><i class="fas fa-copy"></i></button>+ <button @click="downloadNotes" class="copy-btn" title="Download as Word"><i class="fas fa-download"></i></button>+ <button @click="toggleEditNotes" class="copy-btn" title="Edit Notes"><i class="fas fa-edit"></i></button></div><div class="flex-grow overflow-y-auto mobile-content-box"><div v-if="editingNotes" class="h-full flex flex-col">@@ -1197,20 +1216,20 @@</div><div v-else class="content-box relative">- <div v-if="!editingSummary" class="absolute top-2 right-2 flex gap-1 z-10">+ <div v-if="!editingSummary" class="absolute top-2 right-4 flex gap-1 z-10"><button @click="copySummary"title="Copy Summary"- class="w-8 h-8 flex items-center justify-center bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md border border-[var(--border-secondary)] transition-all duration-200">+ class="w-8 h-8 flex items-center justify-center bg-transparent hover:bg-[var(--bg-secondary)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md border border-transparent hover:border-[var(--border-secondary)] transition-all duration-200 opacity-60 hover:opacity-100"><i class="fas fa-copy text-sm"></i></button><button @click="downloadSummary"title="Download Summary as Word Document"- class="w-8 h-8 flex items-center justify-center bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md border border-[var(--border-secondary)] transition-all duration-200">+ class="w-8 h-8 flex items-center justify-center bg-transparent hover:bg-[var(--bg-secondary)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md border border-transparent hover:border-[var(--border-secondary)] transition-all duration-200 opacity-60 hover:opacity-100"><i class="fas fa-download text-sm"></i></button><button @click="toggleEditSummary"title="Edit Summary"- class="w-8 h-8 flex items-center justify-center bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md border border-[var(--border-secondary)] transition-all duration-200">+ class="w-8 h-8 flex items-center justify-center bg-transparent hover:bg-[var(--bg-secondary)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md border border-transparent hover:border-[var(--border-secondary)] transition-all duration-200 opacity-60 hover:opacity-100"><i class="fas fa-edit text-sm"></i></button></div>@@ -1244,20 +1263,20 @@<!-- Notes Tab --><div v-if="selectedTab === 'notes'" class="h-full p-4 overflow-y-auto"><div class="content-box h-full relative">- <div v-if="!editingNotes" class="absolute top-2 right-2 flex gap-1 z-10">+ <div v-if="!editingNotes" class="absolute top-2 right-4 flex gap-1 z-10"><button @click="copyNotes"title="Copy Notes"- class="w-8 h-8 flex items-center justify-center bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md border border-[var(--border-secondary)] transition-all duration-200">+ class="w-8 h-8 flex items-center justify-center bg-transparent hover:bg-[var(--bg-secondary)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md border border-transparent hover:border-[var(--border-secondary)] transition-all duration-200 opacity-60 hover:opacity-100"><i class="fas fa-copy text-sm"></i></button><button @click="downloadNotes"title="Download Notes as Word Document"- class="w-8 h-8 flex items-center justify-center bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md border border-[var(--border-secondary)] transition-all duration-200">+ class="w-8 h-8 flex items-center justify-center bg-transparent hover:bg-[var(--bg-secondary)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md border border-transparent hover:border-[var(--border-secondary)] transition-all duration-200 opacity-60 hover:opacity-100"><i class="fas fa-download text-sm"></i></button><button @click="toggleEditNotes"title="Edit Notes"- class="w-8 h-8 flex items-center justify-center bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md border border-[var(--border-secondary)] transition-all duration-200">+ class="w-8 h-8 flex items-center justify-center bg-transparent hover:bg-[var(--bg-secondary)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md border border-transparent hover:border-[var(--border-secondary)] transition-all duration-200 opacity-60 hover:opacity-100"><i class="fas fa-edit text-sm"></i></button></div>@@ -1391,61 +1410,73 @@<!-- Upload Progress Popup --><div v-if="uploadQueue.length > 0 && !progressPopupClosed":class="[- 'progress-popup',+ 'fixed bottom-4 left-4 z-[100] w-96 transition-all duration-300',progressPopupMinimized ? 'minimized' : '']">- <div class="bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg overflow-hidden">+ <div class="bg-[var(--bg-secondary)] border-2 border-[var(--bg-accent)] rounded-lg shadow-2xl overflow-hidden backdrop-blur-sm bg-opacity-95+ ring-4 ring-[var(--bg-accent)] ring-opacity-20"+ style="box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04), 0 0 0 1px var(--bg-accent), 0 0 20px rgba(var(--bg-accent-rgb), 0.3)"><!-- Progress Header -->- <div class="bg-[var(--bg-tertiary)] px-4 py-3 flex items-center justify-between">- <div class="flex items-center gap-2">- <i class="fas fa-upload text-[var(--text-accent)]"></i>- <span class="font-medium">Upload Progress</span>- <span class="text-sm text-[var(--text-muted)]">(${completedInQueue}/${totalInQueue})</span>+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] px-3 py-2">+ <!-- Top row: Title and buttons -->+ <div class="flex items-center justify-between mb-1">+ <div class="flex items-center gap-2 min-w-0">+ <i class="fas fa-upload text-[var(--text-accent)] animate-pulse text-sm"></i>+ <span class="font-semibold text-[var(--text-accent)] text-sm truncate">Upload Progress</span>+ </div>+ <div class="flex items-center gap-1 flex-shrink-0">+ <button v-if="completedInQueue > 0" @click="clearCompletedUploads()"+ class="px-1.5 py-0.5 text-xs bg-white bg-opacity-20 hover:bg-opacity-30 rounded transition-colors text-[var(--text-accent)] border border-white border-opacity-30"+ title="Clear completed uploads">+ <i class="fas fa-broom"></i>+ </button>+ <button @click="progressPopupMinimized = !progressPopupMinimized"+ class="p-0.5 rounded hover:bg-white hover:bg-opacity-20 transition-colors text-[var(--text-accent)]">+ <i :class="progressPopupMinimized ? 'fas fa-chevron-up text-xs' : 'fas fa-chevron-down text-xs'"></i>+ </button>+ <button @click="progressPopupClosed = true"+ class="p-0.5 rounded hover:bg-red-500 hover:bg-opacity-20 text-red-200 hover:text-red-100 transition-colors">+ <i class="fas fa-times text-xs"></i>+ </button>+ </div></div>- <div class="flex items-center gap-2">- <button v-if="completedInQueue > 0" @click="clearCompletedUploads()"- class="px-2 py-1 text-xs bg-[var(--bg-accent)] hover:bg-[var(--bg-accent-hover)] rounded transition-colors text-[var(--text-secondary)]"- title="Clear completed uploads">- <i class="fas fa-broom mr-1"></i>Clear- </button>- <button @click="progressPopupMinimized = !progressPopupMinimized"- class="p-1 rounded hover:bg-[var(--bg-accent)] transition-colors">- <i :class="progressPopupMinimized ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i>- </button>- <button @click="progressPopupClosed = true"- class="p-1 rounded hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors">- <i class="fas fa-times"></i>- </button>+ <!-- Bottom row: Progress count -->+ <div class="flex items-center justify-between">+ <span class="text-xs text-[var(--text-accent)] opacity-80 font-medium">${completedInQueue} of ${totalInQueue} completed</span>+ <div class="w-24 bg-white bg-opacity-20 rounded-full h-1.5">+ <div class="bg-white h-1.5 rounded-full transition-all duration-300"+ :style="{width: (completedInQueue / Math.max(totalInQueue, 1) * 100) + '%'}"></div>+ </div></div></div><!-- Progress Content -->- <div v-if="!progressPopupMinimized" class="p-4 max-h-64 overflow-y-auto">- <div v-if="currentlyProcessingFile" class="mb-4 p-3 bg-[var(--bg-accent)] rounded-lg">- <div class="flex items-center justify-between mb-2">- <span class="font-medium truncate min-w-0">${currentlyProcessingFile.file.name}</span>- <span class="text-sm flex-shrink-0 ml-2">${processingProgress}%</span>+ <div v-if="!progressPopupMinimized" class="p-3 max-h-64 overflow-y-auto">+ <div v-if="currentlyProcessingFile" class="mb-3 p-2.5 bg-[var(--bg-accent)] rounded-lg">+ <div class="flex items-center justify-between mb-1.5">+ <span class="font-medium truncate min-w-0 text-sm">${currentlyProcessingFile.file.name}</span>+ <span class="text-xs flex-shrink-0 ml-2 font-semibold">${processingProgress}%</span></div>- <div class="w-full bg-[var(--bg-secondary)] rounded-full h-2">- <div class="bg-[var(--bg-button)] h-2 rounded-full transition-all duration-300"+ <div class="w-full bg-[var(--bg-secondary)] rounded-full h-1.5 mb-1.5">+ <div class="bg-[var(--bg-button)] h-1.5 rounded-full transition-all duration-300":style="{width: processingProgress + '%'}"></div></div>- <p class="text-sm text-[var(--text-muted)] mt-1">${processingMessage}</p>+ <p class="text-xs text-[var(--text-muted)]">${processingMessage}</p></div>- <div v-if="finishedFilesInQueue.length > 0" class="space-y-2">- <h4 class="text-sm font-medium text-[var(--text-secondary)]">Completed</h4>+ <div v-if="finishedFilesInQueue.length > 0" class="space-y-1.5">+ <h4 class="text-xs font-medium text-[var(--text-secondary)] uppercase tracking-wide">Completed</h4><div v-for="item in finishedFilesInQueue":key="item.clientId"- class="progress-list-item p-2 bg-[var(--bg-tertiary)] rounded">+ class="progress-list-item p-1.5 bg-[var(--bg-tertiary)] rounded flex items-center gap-2"><i :class="[- 'fas',+ 'fas text-xs',item.status === 'completed' ? 'fa-check-circle text-green-500' : 'fa-exclamation-circle text-red-500']"></i>- <span class="truncate">${item.file.name}</span>+ <span class="truncate text-sm flex-1">${item.file.name}</span><span :class="[- 'text-xs',- item.status === 'completed' ? 'text-green-600' : 'text-red-600'+ 'text-xs px-1.5 py-0.5 rounded font-medium',+ item.status === 'completed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700']">${item.status === 'completed' ? 'Done' : 'Failed'}</span>@@ -1961,8 +1992,8 @@<!-- Audio Player Section --><div class="mb-4 flex-shrink-0"><h4 class="font-semibold text-[var(--text-secondary)] mb-2">Audio Player</h4>- <div class="bg-[var(--bg-audio-player)] p-3 rounded-lg shadow border border-[var(--border-primary)]">- <audio controls class="w-full h-10 speaker-modal-transcript" :key="selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">+ <div class="audio-player-container">+ <audio controls class="w-full speaker-modal-transcript" :key="selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">Your browser does not support the audio element.</audio></div>diff --git a/templates/inquire.html b/templates/inquire.htmlnew file mode 100644index 00000000..ca51d344--- /dev/null+++ b/templates/inquire.html@@ -0,0 +1,693 @@+<!DOCTYPE html>+<html lang="en" class="h-full">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <meta name="csrf-token" content="{{ csrf_token() }}">+ <title>Inquire Mode - Speakr</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}">+ <link rel="icon" type="image/png" sizes="32x32" href="{{ url_for('static', filename='img/icon-32x32.png') }}">+ <script>+ tailwind.config = {+ darkMode: 'class',+ theme: {+ extend: {+ colors: {+ primary: 'var(--bg-primary)',+ secondary: 'var(--bg-secondary)',+ accent: 'var(--bg-accent)'+ }+ }+ }+ }+ </script>+ <style>+ /* Custom checkbox styling for better visual feedback */+ .filter-checkbox {+ appearance: none;+ background-color: var(--bg-input);+ border: 2px solid var(--border-secondary);+ border-radius: 4px;+ width: 16px;+ height: 16px;+ position: relative;+ transition: all 0.2s ease;+ }++ .filter-checkbox:checked {+ background-color: var(--text-accent);+ border-color: var(--text-accent);+ }++ .filter-checkbox:checked::after {+ content: '✓';+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ color: white;+ font-size: 10px;+ font-weight: bold;+ }++ .filter-checkbox:focus {+ outline: 2px solid var(--text-accent);+ outline-offset: 2px;+ }++ .filter-checkbox:hover {+ border-color: var(--text-accent);+ }++ /* Enhanced markdown styling for Inquire Mode chat messages */+ .chat-message .prose h1,+ .chat-message .prose h2,+ .chat-message .prose h3,+ .chat-message .prose h4 {+ color: var(--text-primary);+ font-weight: 600;+ margin-top: 1.5em;+ margin-bottom: 0.75em;+ line-height: 1.3;+ }++ .chat-message .prose h1 { font-size: 1.25em; }+ .chat-message .prose h2 { font-size: 1.15em; }+ .chat-message .prose h3 { font-size: 1.05em; }++ .chat-message .prose p {+ color: var(--text-primary);+ margin-bottom: 1em;+ line-height: 1.6;+ }++ .chat-message .prose ul,+ .chat-message .prose ol {+ color: var(--text-primary);+ margin: 0.75em 0;+ padding-left: 1.5em;+ }++ .chat-message .prose li {+ color: var(--text-primary);+ margin: 0.25em 0;+ line-height: 1.6;+ }++ .chat-message .prose strong {+ color: var(--text-primary);+ font-weight: 700;+ }++ .chat-message .prose ul { list-style-type: disc; }+ .chat-message .prose ol { list-style-type: decimal; }++ .chat-message .prose code {+ background-color: var(--bg-accent);+ color: var(--text-accent);+ padding: 0.15em 0.3em;+ border-radius: 3px;+ font-size: 0.9em;+ }+ </style>+</head>+<body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">+ <div id="inquire-app" v-cloak class="h-full flex flex-col"+ 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>++ <!-- 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>+ </div>++ <!-- Right side: User menu -->+ <div class="flex items-center gap-3">+ <!-- New Recording Button -->+ <a href="/"+ 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 flex items-center gap-2">+ <i class="fas fa-plus"></i>+ <span class="hidden sm:inline">New Recording</span>+ </a>++ <!-- 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">+ <i class="fas fa-user-circle text-lg"></i>+ <span class="hidden sm:inline">{{ current_user.name if current_user.name else current_user.username }}</span>+ <i class="fas fa-chevron-down text-xs"></i>+ </button>++ <!-- User dropdown -->+ <div v-if="isUserMenuOpen"+ class="absolute right-0 mt-2 w-56 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-50">+ <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>+ {% 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-shield-alt mr-2 w-4 text-center"></i>Admin Dashboard+ </a>+ {% endif %}+ <div class="border-t border-[var(--border-primary)] my-2"></div>+ <a href="/logout" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] text-red-500 transition-colors">+ <i class="fas fa-sign-out-alt mr-2 w-4 text-center"></i>Sign Out+ </a>+ </div>+ </div>+ {% endif %}+ </div>+ </header>++ <!-- Main Content -->+ <div class="flex-1 flex overflow-hidden">+ <!-- 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">+ <i class="fas fa-times"></i> Clear All+ </button>+ </div>++ <!-- Tag Filters -->+ <div class="bg-[var(--bg-primary)] rounded-lg border border-[var(--border-secondary)] p-3">+ <h3 class="font-medium mb-2 flex items-center text-[var(--text-primary)]">+ <i class="fas fa-tags mr-2 text-[var(--text-accent)]"></i>Tags+ </h3>+ <!-- Tag search input -->+ <div class="mb-3">+ <input type="text" v-model="tagSearchQuery" placeholder="Search tags..."+ class="w-full px-2 py-1 text-sm bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded text-[var(--text-primary)] focus:border-[var(--border-focus)] focus:ring-1 focus:ring-[var(--border-focus)] transition-colors">+ </div>+ <div class="space-y-1 max-h-40 overflow-y-auto custom-scrollbar">+ <label v-for="tag in filteredTags" :key="tag.id" class="flex items-center cursor-pointer hover:bg-[var(--bg-tertiary)] p-2 rounded transition-colors group">+ <input type="checkbox" :value="tag.id" v-model="inquireFilters.selectedTags"+ class="filter-checkbox">+ <span class="ml-2 text-sm font-medium flex-1" :style="{color: tag.color}">${tag.name}</span>+ <span class="text-xs px-1.5 py-0.5 bg-[var(--bg-tertiary)] text-[var(--text-muted)] rounded-full">${tag.recording_count}</span>+ </label>+ </div>+ </div>++ <!-- Speaker Filters -->+ <div class="bg-[var(--bg-primary)] rounded-lg border border-[var(--border-secondary)] p-3">+ <h3 class="font-medium mb-2 flex items-center text-[var(--text-primary)]">+ <i class="fas fa-users mr-2 text-[var(--text-accent)]"></i>Speakers+ </h3>+ <div v-if="availableFilters.speakers.length > 0">+ <!-- Speaker search input -->+ <div class="mb-3">+ <input type="text" v-model="speakerSearchQuery" placeholder="Search speakers..."+ class="w-full px-2 py-1 text-sm bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded text-[var(--text-primary)] focus:border-[var(--border-focus)] focus:ring-1 focus:ring-[var(--border-focus)] transition-colors">+ </div>+ <div class="space-y-1 max-h-40 overflow-y-auto custom-scrollbar">+ <label v-for="speaker in filteredSpeakers" :key="speaker" class="flex items-center cursor-pointer hover:bg-[var(--bg-tertiary)] p-2 rounded transition-colors group">+ <input type="checkbox" :value="speaker" v-model="inquireFilters.selectedSpeakers"+ class="filter-checkbox">+ <span class="ml-2 text-sm text-[var(--text-primary)] flex-1">${speaker}</span>+ </label>+ </div>+ </div>++ <!-- No Speakers Message -->+ <div v-if="availableFilters.speakers.length === 0" class="text-center py-3">+ <i class="fas fa-users text-xl text-[var(--text-muted)] mb-2"></i>+ <p class="text-sm text-[var(--text-muted)]">No speaker data available</p>+ <p class="text-xs text-[var(--text-muted)] mt-1">Speaker identification requires recordings with multiple speakers</p>+ </div>+ </div>++ <!-- Date Range Filters -->+ <div class="bg-[var(--bg-primary)] rounded-lg border border-[var(--border-secondary)] p-3">+ <h3 class="font-medium mb-2 flex items-center text-[var(--text-primary)]">+ <i class="fas fa-calendar mr-2 text-[var(--text-accent)]"></i>Date Range+ </h3>+ <div class="space-y-2">+ <div>+ <label class="block text-xs text-[var(--text-muted)] mb-1 font-medium">From</label>+ <input type="date" v-model="inquireFilters.dateFrom" class="w-full px-2 py-1 text-sm bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded text-[var(--text-primary)] focus:border-[var(--border-focus)] focus:ring-1 focus:ring-[var(--border-focus)] transition-colors">+ </div>+ <div>+ <label class="block text-xs text-[var(--text-muted)] mb-1 font-medium">To</label>+ <input type="date" v-model="inquireFilters.dateTo" class="w-full px-2 py-1 text-sm bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded text-[var(--text-primary)] focus:border-[var(--border-focus)] focus:ring-1 focus:ring-[var(--border-focus)] transition-colors">+ </div>+ </div>+ </div>++ </div>++ <!-- Recording Filters - Commented Out -->+ <!--+ <div class="flex-1 flex flex-col px-6 pb-6 min-h-0">+ <div class="bg-[var(--bg-primary)] rounded-lg border border-[var(--border-secondary)] p-4 flex flex-col flex-1 min-h-0">+ <h3 class="font-medium mb-3 flex items-center flex-shrink-0 text-[var(--text-primary)]">+ <i class="fas fa-file-audio mr-2 text-[var(--text-accent)]"></i>Recordings+ </h3>+ <div class="space-y-1 flex-1 overflow-y-auto custom-scrollbar pr-2 min-h-0">+ <label v-for="recording in availableFilters.recordings" :key="recording.id" class="flex items-center cursor-pointer hover:bg-[var(--bg-tertiary)] p-3 rounded-md transition-colors border border-transparent hover:border-[var(--border-secondary)]">+ <input type="checkbox" :value="recording.id" v-model="inquireFilters.selectedRecordings" class="h-4 w-4 rounded border-[var(--border-secondary)] text-[var(--text-accent)] focus:ring-[var(--border-focus)] flex-shrink-0">+ <div class="ml-3 flex-1 min-w-0">+ <div class="text-sm font-medium truncate text-[var(--text-primary)]" :title="recording.title">${recording.title}</div>+ <div v-if="recording.meeting_date" class="text-xs text-[var(--text-muted)] mt-1">${formatDate(recording.meeting_date)}</div>+ </div>+ </label>+ </div>+ </div>+ -->++ <!-- Active Filters Summary -->+ <div class="p-4">+ <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:+ </h4>+ <div class="space-y-1 text-xs">+ <div v-if="inquireFilters.selectedTags.length" class="flex items-center px-2 py-1 bg-[var(--bg-tertiary)] rounded text-[var(--text-secondary)]">+ <span><i class="fas fa-tags mr-1"></i>${inquireFilters.selectedTags.length} tags</span>+ </div>+ <div v-if="inquireFilters.selectedSpeakers.length" class="flex items-center px-2 py-1 bg-[var(--bg-tertiary)] rounded text-[var(--text-secondary)]">+ <span><i class="fas fa-users mr-1"></i>${inquireFilters.selectedSpeakers.length} speakers</span>+ </div>+ <div v-if="inquireFilters.dateFrom || inquireFilters.dateTo" class="flex items-center px-2 py-1 bg-[var(--bg-tertiary)] rounded text-[var(--text-secondary)]">+ <span><i class="fas fa-calendar mr-1"></i>Date range active</span>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- Right Panel: Chat -->+ <div class="flex-1 flex flex-col overflow-hidden">+ <!-- 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>+ <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.+ </p>+ <div class="bg-[var(--bg-tertiary)] rounded-xl p-4 max-w-md mx-auto">+ <h4 class="font-medium mb-2">Example Questions:</h4>+ <ul class="text-sm text-[var(--text-secondary)] space-y-1 text-left">+ <li>"What action items were discussed?"</li>+ <li>"When did we decide to change the timeline?"</li>+ <li>"What concerns were raised about the budget?"</li>+ <li>"Who was responsible for the marketing tasks?"</li>+ </ul>+ </div>+ </div>++ <!-- Chat Messages -->+ <div v-for="(message, index) in inquireChatMessages" :key="index"+ :class="['flex', message.role === 'user' ? 'justify-end' : 'justify-start']">+ <div :class="['max-w-3xl px-4 py-4 rounded-xl chat-message',+ message.role === 'user'+ ? 'bg-[var(--bg-accent)] text-[var(--text-accent)]'+ : 'bg-[var(--bg-tertiary)] text-[var(--text-primary)]']">+ <div class="prose prose-sm max-w-none text-[var(--text-primary)]"+ :class="message.role === 'user' ? 'prose-invert' : ''"+ v-html="message.html || message.content">+ </div>+ </div>+ </div>++ <!-- Loading indicator with status -->+ <div v-if="isInquireChatLoading" class="flex justify-start">+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 rounded-xl max-w-md">+ <div class="flex items-center space-x-2">+ <div class="animate-spin h-5 w-5 border-2 border-[var(--text-accent)] border-t-transparent rounded-full flex-shrink-0"></div>+ <span class="text-sm text-[var(--text-muted)]" v-if="showProcessingStatus">${chatProcessingStatus}</span>+ <span class="text-sm text-[var(--text-muted)]" v-else>Analyzing transcriptions...</span>+ </div>++ <!-- Progress steps indicator -->+ <div v-if="showProcessingStatus" class="mt-2 flex space-x-1">+ <div class="h-1 w-4 bg-[var(--text-accent)] rounded" :class="{ 'animate-pulse': chatProcessingStatus.includes('Analyzing') }"></div>+ <div class="h-1 w-4 rounded" :class="chatProcessingStatus.includes('Enriching') || chatProcessingStatus.includes('Searching') || chatProcessingStatus.includes('Responding') ? 'bg-[var(--text-accent)]' : 'bg-[var(--border-secondary)]'"></div>+ <div class="h-1 w-4 rounded" :class="chatProcessingStatus.includes('Searching') || chatProcessingStatus.includes('Responding') ? 'bg-[var(--text-accent)]' : 'bg-[var(--border-secondary)]'"></div>+ <div class="h-1 w-4 rounded" :class="chatProcessingStatus.includes('Contextualizing') || chatProcessingStatus.includes('Responding') ? 'bg-[var(--text-accent)]' : 'bg-[var(--border-secondary)]'"></div>+ <div class="h-1 w-4 rounded" :class="chatProcessingStatus.includes('Responding') ? 'bg-[var(--text-accent)] animate-pulse' : 'bg-[var(--border-secondary)]'"></div>+ </div>+ </div>+ </div>+ </div>++ <!-- Chat Input Area -->+ <div class="flex-shrink-0 border-t border-[var(--border-primary)] p-6 bg-[var(--bg-secondary)]">+ <div class="flex gap-4">+ <textarea v-model="inquireChatInput"+ @keydown="handleInquireChatKeydown"+ placeholder="Ask questions about your filtered transcriptions..."+ class="flex-1 px-4 py-3 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-xl resize-none focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:border-transparent text-[var(--text-primary)]"+ rows="3"></textarea>+ <button @click="sendInquireChatMessage"+ :disabled="!inquireChatInput.trim() || isInquireChatLoading"+ class="px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-xl hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center min-w-[60px]">+ <i class="fas fa-paper-plane text-lg"></i>+ </button>+ </div>+ <div class="text-xs text-[var(--text-muted)] mt-3 flex items-center justify-between">+ <span>Press Enter to send • Ctrl+Enter for new line</span>+ <span v-if="hasActiveFilters" class="text-[var(--text-accent)]">+ <i class="fas fa-filter mr-1"></i>Filters active+ </span>+ </div>+ </div>+ </div>+ </div>++ <!-- Toast Container -->+ <div id="toastContainer" class="fixed bottom-4 right-4 z-50 space-y-2"></div>+ </div>++ <!-- CSRF Token Management -->+ <script src="{{ url_for('static', filename='js/csrf-refresh.js') }}"></script>++ <!-- Inquire Mode Vue App -->+ <script>+ const { createApp, ref, reactive, computed, onMounted, onUnmounted, nextTick } = Vue;++ document.addEventListener('DOMContentLoaded', () => {+ const csrfToken = ref(document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'));++ createApp({+ setup() {+ // --- State ---+ const inquireFilters = reactive({+ selectedTags: [],+ selectedSpeakers: [],+ selectedRecordings: [],+ dateFrom: null,+ dateTo: null+ });++ // Search queries for filters+ const tagSearchQuery = ref('');+ const speakerSearchQuery = ref('');++ const isUserMenuOpen = ref(false);++ const availableFilters = reactive({+ tags: [],+ speakers: [],+ recordings: []+ });++ const inquireChatMessages = ref([]);+ const inquireChatInput = ref('');+ const isInquireChatLoading = ref(false);+ const chatProcessingStatus = ref('');+ const showProcessingStatus = ref(false);+ const inquireMessagesRef = ref(null);+ const globalError = ref(null);+ const shouldAutoScroll = ref(true); // Track if we should auto-scroll++ // --- Computed ---+ const hasActiveFilters = computed(() => {+ return inquireFilters.selectedTags.length > 0 ||+ inquireFilters.selectedSpeakers.length > 0 ||+ inquireFilters.selectedRecordings.length > 0 ||+ inquireFilters.dateFrom ||+ inquireFilters.dateTo;+ });++ const filteredTags = computed(() => {+ if (!tagSearchQuery.value) return availableFilters.tags;+ return availableFilters.tags.filter(tag =>+ tag.name.toLowerCase().includes(tagSearchQuery.value.toLowerCase())+ );+ });++ const filteredSpeakers = computed(() => {+ if (!speakerSearchQuery.value) return availableFilters.speakers;+ return availableFilters.speakers.filter(speaker =>+ speaker.toLowerCase().includes(speakerSearchQuery.value.toLowerCase())+ );+ });++ // --- Functions ---+ const setGlobalError = (message, duration = 7000) => {+ globalError.value = message;+ if (duration > 0) {+ setTimeout(() => { if (globalError.value === message) globalError.value = null; }, duration);+ }+ };++ const loadAvailableFilters = async () => {+ try {+ const response = await fetch('/api/inquire/available_filters');+ if (response.ok) {+ const data = await response.json();+ availableFilters.tags = data.tags;+ availableFilters.speakers = data.speakers;+ availableFilters.recordings = data.recordings;+ }+ } catch (error) {+ console.error('Error loading available filters:', error);+ }+ };++ const sendInquireChatMessage = async () => {+ if (!inquireChatInput.value.trim() || isInquireChatLoading.value) return;++ const userMessage = inquireChatInput.value.trim();+ inquireChatMessages.value.push({ role: 'user', content: userMessage, html: userMessage });+ inquireChatInput.value = '';+ isInquireChatLoading.value = true;+ showProcessingStatus.value = true;+ chatProcessingStatus.value = 'Initializing...';++ // Always scroll to bottom when user sends a message+ shouldAutoScroll.value = true;+ await nextTick();+ scrollToBottom();++ try {+ const response = await fetch('/api/inquire/chat', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken.value+ },+ body: JSON.stringify({+ message: userMessage,+ message_history: inquireChatMessages.value.slice(0, -1),+ filter_tags: inquireFilters.selectedTags,+ filter_speakers: inquireFilters.selectedSpeakers,+ filter_recording_ids: inquireFilters.selectedRecordings,+ filter_date_from: inquireFilters.dateFrom,+ filter_date_to: inquireFilters.dateTo,+ context_chunks: 8+ })+ });++ if (!response.ok) {+ throw new Error('Chat request failed');+ }++ // Handle streaming response+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let assistantMessage = reactive({ role: 'assistant', content: '', html: '' });+ let messageAdded = false;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ const chunk = decoder.decode(value, { stream: true });+ const lines = chunk.split('\n');++ for (const line of lines) {+ if (line.startsWith('data: ')) {+ try {+ const data = JSON.parse(line.slice(6));+ if (data.status && data.message) {+ // Update processing status+ chatProcessingStatus.value = data.message;+ } else if (data.delta) {+ // Hide status and start showing response+ if (!messageAdded) {+ inquireChatMessages.value.push(assistantMessage);+ messageAdded = true;+ showProcessingStatus.value = false;+ }+ assistantMessage.content += data.delta;+ assistantMessage.html = marked.parse(assistantMessage.content);+ // Smart scroll during streaming+ await nextTick();+ scrollToBottom();+ } else if (data.end_of_stream) {+ return;+ } else if (data.error) {+ throw new Error(data.error);+ }+ } catch (parseError) {+ console.warn('Failed to parse SSE data:', line);+ }+ }+ }+ }+ } catch (error) {+ console.error('Error in inquire chat:', error);+ setGlobalError('Chat failed. Please try again.');+ } finally {+ isInquireChatLoading.value = false;+ showProcessingStatus.value = false;+ await nextTick();+ scrollToBottom(); // Use smart scrolling+ }+ };++ const handleInquireChatKeydown = (event) => {+ if (event.key === 'Enter') {+ if (event.ctrlKey || event.shiftKey) {+ return;+ } else {+ event.preventDefault();+ sendInquireChatMessage();+ }+ }+ };++ const clearInquireFilters = () => {+ inquireFilters.selectedTags = [];+ inquireFilters.selectedSpeakers = [];+ inquireFilters.selectedRecordings = [];+ inquireFilters.dateFrom = null;+ inquireFilters.dateTo = null;+ inquireChatMessages.value = [];+ };++ const formatDate = (dateString) => {+ if (!dateString) return '';+ const date = new Date(dateString);+ return date.toLocaleDateString();+ };++ // Smart scrolling functions+ const isNearBottom = () => {+ if (!inquireMessagesRef.value) return true;+ const container = inquireMessagesRef.value;+ const threshold = 100; // pixels from bottom+ return container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;+ };++ const scrollToBottom = () => {+ if (inquireMessagesRef.value && shouldAutoScroll.value) {+ inquireMessagesRef.value.scrollTop = inquireMessagesRef.value.scrollHeight;+ }+ };++ const handleScroll = () => {+ if (inquireMessagesRef.value) {+ shouldAutoScroll.value = isNearBottom();+ }+ };++ // Close user menu when clicking outside+ const handleClickOutside = (event) => {+ if (isUserMenuOpen.value && !event.target.closest('.relative')) {+ isUserMenuOpen.value = false;+ }+ };++ // --- Theme Management (from main app.js) ---+ const applyThemeFromStorage = () => {+ const savedDarkMode = localStorage.getItem('darkMode');+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ const isDark = savedDarkMode !== null ? savedDarkMode === 'true' : prefersDark;++ document.documentElement.classList.toggle('dark', isDark);++ const savedScheme = localStorage.getItem('colorScheme') || 'blue';+ const currentMode = isDark ? 'dark' : 'light';+ const themeClass = savedScheme === 'blue' ? '' : `theme-${currentMode}-${savedScheme}`;++ // Remove all existing theme classes+ document.documentElement.className = document.documentElement.className+ .replace(/theme-(?:light|dark)-\w+/g, '');++ if (themeClass) {+ document.documentElement.classList.add(themeClass);+ }+ };++ // --- Lifecycle ---+ onMounted(async () => {+ // Apply theme from localStorage on page load+ applyThemeFromStorage();++ loadAvailableFilters();+ document.addEventListener('click', handleClickOutside);++ // Add scroll listener for smart auto-scroll after DOM is ready+ await nextTick();+ if (inquireMessagesRef.value) {+ inquireMessagesRef.value.addEventListener('scroll', handleScroll);+ }+ });++ onUnmounted(() => {+ document.removeEventListener('click', handleClickOutside);+ if (inquireMessagesRef.value) {+ inquireMessagesRef.value.removeEventListener('scroll', handleScroll);+ }+ });++ return {+ // State+ inquireFilters,+ availableFilters,+ inquireChatMessages,+ inquireChatInput,+ isInquireChatLoading,+ inquireMessagesRef,+ globalError,+ isUserMenuOpen,+ chatProcessingStatus,+ showProcessingStatus,+ tagSearchQuery,+ speakerSearchQuery,++ // Computed+ hasActiveFilters,+ filteredTags,+ filteredSpeakers,++ // Functions+ sendInquireChatMessage,+ handleInquireChatKeydown,+ clearInquireFilters,+ loadAvailableFilters,+ setGlobalError,+ formatDate,+ handleScroll+ };+ },+ delimiters: ['${', '}']+ }).mount('#inquire-app');+ });+ </script>+</body>+</html>\ No newline at end of filediff --git a/test_inquire_mode.py b/test_inquire_mode.pynew file mode 100644index 00000000..61a68aca--- /dev/null+++ b/test_inquire_mode.py@@ -0,0 +1,183 @@+#!/usr/bin/env python3+"""+Test script for Inquire Mode functionality+"""+import os+import sys+from app import app, db, User, Recording, TranscriptChunk, InquireSession, Tag++def test_database_models():+ """Test that the new database models work correctly."""+ with app.app_context():+ print("🔍 Testing Inquire Mode Database Models...")++ # Test that tables exist+ from sqlalchemy import inspect+ inspector = inspect(db.engine)+ tables = inspector.get_table_names()++ required_tables = ['transcript_chunk', 'inquire_session']+ for table in required_tables:+ if table in tables:+ print(f"✅ Table '{table}' exists")+ else:+ print(f"❌ Table '{table}' missing")+ return False++ # Test creating sample data+ try:+ # Create a test user (or get existing one)+ user = User.query.first()+ if not user:+ print("❌ No users found. Please create a user first.")+ return False++ print(f"📝 Using test user: {user.username}")++ # Create a test recording if none exist+ recording = Recording.query.filter_by(user_id=user.id).first()+ if not recording:+ print("❌ No recordings found. Please create a recording first.")+ return False++ print(f"🎵 Using test recording: {recording.title}")++ # Test TranscriptChunk creation+ chunk = TranscriptChunk(+ recording_id=recording.id,+ user_id=user.id,+ chunk_index=0,+ content="This is a test transcription chunk.",+ start_time=0.0,+ end_time=5.0,+ speaker_name="Test Speaker"+ )++ db.session.add(chunk)++ # Test InquireSession creation+ session = InquireSession(+ user_id=user.id,+ session_name="Test Session",+ filter_tags='[]',+ filter_speakers='["Test Speaker"]'+ )++ db.session.add(session)+ db.session.commit()++ print("✅ Successfully created test TranscriptChunk and InquireSession")++ # Clean up test data+ db.session.delete(chunk)+ db.session.delete(session)+ db.session.commit()++ print("✅ Test data cleaned up")++ except Exception as e:+ print(f"❌ Error testing models: {e}")+ return False++ return True++def test_chunking_functions():+ """Test the chunking and embedding functions."""+ with app.app_context():+ print("🔧 Testing Chunking Functions...")++ try:+ from app import chunk_transcription, generate_embeddings, serialize_embedding, deserialize_embedding++ # Test chunking+ test_text = "This is a test sentence. This is another sentence for testing. And here's a third sentence to make sure chunking works properly with longer text that should be split into multiple chunks."+ chunks = chunk_transcription(test_text, max_chunk_length=100, overlap=20)++ if len(chunks) > 1:+ print(f"✅ Chunking works: {len(chunks)} chunks created")+ else:+ print("✅ Text too short for chunking (expected behavior)")++ # Test embeddings (will only work if sentence-transformers is installed)+ try:+ embeddings = generate_embeddings(["test sentence", "another test"])+ if len(embeddings) == 2:+ print("✅ Embedding generation works")++ # Test serialization+ if embeddings[0] is not None:+ serialized = serialize_embedding(embeddings[0])+ deserialized = deserialize_embedding(serialized)+ if deserialized is not None and len(deserialized) > 0:+ print("✅ Embedding serialization/deserialization works")+ else:+ print("❌ Embedding serialization/deserialization failed")+ else:+ print("❌ Embedding generation returned wrong number of embeddings")++ except Exception as e:+ print(f"⚠️ Embedding test skipped (sentence-transformers may not be installed): {e}")++ except Exception as e:+ print(f"❌ Error testing chunking functions: {e}")+ return False++ return True++def test_api_imports():+ """Test that all API endpoints can be imported."""+ print("🔌 Testing API Endpoint Imports...")++ try:+ from app import (+ get_inquire_sessions, create_inquire_session, inquire_search,+ inquire_chat, get_available_filters, process_recording_chunks_endpoint+ )+ print("✅ All inquire mode API endpoints imported successfully")+ return True+ except ImportError as e:+ print(f"❌ Failed to import API endpoints: {e}")+ return False++def main():+ """Run all tests."""+ print("🚀 Starting Inquire Mode Tests...\n")++ tests = [+ ("Database Models", test_database_models),+ ("Chunking Functions", test_chunking_functions),+ ("API Imports", test_api_imports)+ ]++ results = []+ for test_name, test_func in tests:+ print(f"\n--- {test_name} ---")+ try:+ success = test_func()+ results.append((test_name, success))+ except Exception as e:+ print(f"❌ {test_name} failed with exception: {e}")+ results.append((test_name, False))++ print("\n" + "="*50)+ print("📊 Test Results Summary:")+ print("="*50)++ all_passed = True+ for test_name, success in results:+ status = "✅ PASS" if success else "❌ FAIL"+ print(f"{status} - {test_name}")+ if not success:+ all_passed = False++ print("\n" + "="*50)+ if all_passed:+ print("🎉 All tests passed! Inquire Mode is ready to use.")+ else:+ print("⚠️ Some tests failed. Please check the output above.")++ return all_passed++if __name__ == "__main__":+ success = main()+ sys.exit(0 if success else 1)\ No newline at end of filediff --git a/update_version.py b/update_version.pynew file mode 100644index 00000000..15128646--- /dev/null+++ b/update_version.py@@ -0,0 +1,60 @@+#!/usr/bin/env python3+"""+Simple script to update the VERSION file.+Usage: python update_version.py v0.4.3+"""+import sys+import re++def update_version(new_version):+ # Validate version format (basic check)+ if not re.match(r'^v?\d+\.\d+\.\d+', new_version):+ print(f"Warning: Version '{new_version}' doesn't follow standard format (v1.2.3)")++ # Ensure version starts with 'v'+ if not new_version.startswith('v'):+ new_version = 'v' + new_version++ # Write to VERSION file+ try:+ with open('VERSION', 'w') as f:+ f.write(new_version)+ print(f"✅ Updated VERSION file to: {new_version}")++ # Optional: Create git tag if in a git repo+ import subprocess+ try:+ # Check if we're in a git repo+ subprocess.check_output(['git', 'status'], stderr=subprocess.DEVNULL)++ # Create and push tag+ subprocess.check_output(['git', 'tag', new_version], stderr=subprocess.DEVNULL)+ print(f"✅ Created git tag: {new_version}")++ # Ask user if they want to push+ response = input("Push tag to remote? (y/N): ").strip().lower()+ if response == 'y':+ subprocess.check_output(['git', 'push', 'origin', new_version])+ print(f"✅ Pushed tag {new_version} to remote")++ except subprocess.CalledProcessError:+ print("ℹ️ Not in a git repo or git tag already exists")+ except Exception as e:+ print(f"ℹ️ Git operations failed: {e}")++ except Exception as e:+ print(f"❌ Failed to update VERSION file: {e}")+ return False++ return True++if __name__ == "__main__":+ if len(sys.argv) != 2:+ print("Usage: python update_version.py <version>")+ print("Example: python update_version.py v0.4.3")+ print("Example: python update_version.py 0.4.3-alpha")+ sys.exit(1)++ new_version = sys.argv[1]+ success = update_version(new_version)+ sys.exit(0 if success else 1)\ No newline at end of file